From 1ed16fc516abe25177a06bff6ae8bfffb1a0ccb0 Mon Sep 17 00:00:00 2001 From: Eliver Date: Wed, 14 Oct 2026 20:09:16 +0800 Subject: [PATCH 01/20] feat: codex native install/remove with self-starting silent proxy service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four faces written by `bili plugin install codex`: model route, [mcp_servers.bili], [[hooks.SessionStart]], and the bili skill. - src/codex-integration/*: hook/skill/route/status planners, each additive and ownership-scoped so a foreign entry (lean-ctx and friends) is never rewritten. - hooks.ts: the pre-write guard no longer mistakes Codex's own [hooks.state.':::'] trust ledger for a malformed stage table. Matching a bare `hooks` prefix rejected the whole config, so the hook face was silently skipped on any config where a hook had ever been trusted — a self-closing deadlock, since that ledger only exists once Codex trusts us. - src/proxy-service/*: Windows (schtasks) and Linux (systemd --user) self-start backends behind one interface, so install starts the proxy and remove stops it. - Windows silence: the task action goes through wscript.exe + a hidden-mode .vbs launcher. only hides the Task Scheduler entry; a console-subsystem node.exe started under InteractiveToken still allocates a conhost window. The launcher waits (Run(cmd, 0, True)) so the task keeps owning the process, and uninstall reaps the recorded pid when /End cannot reach a reparented node. --- ...ex-native-install-test-and-remove.zh-CN.md | 168 +++ src/codex-integration/cc-switch.ts | 122 ++ src/codex-integration/chatgpt-capability.ts | 16 + src/codex-integration/hooks.ts | 342 +++++ src/codex-integration/route.ts | 412 ++++++ src/codex-integration/skill.ts | 169 +++ src/codex-integration/status.ts | 207 ++++ src/codex-integration/toml-field.ts | 288 +++++ src/codex/bootstrap-hook.ts | 98 ++ src/proxy-service/index.ts | 25 + src/proxy-service/service.ts | 1102 +++++++++++++++++ src/proxy-service/systemd.ts | 218 ++++ src/proxy-service/task-scheduler.ts | 226 ++++ tests/codex-cc-switch.test.ts | 44 + tests/codex-chatgpt-capability.test.ts | 18 + tests/codex-hooks-skill.test.ts | 378 ++++++ tests/codex-install-faces.test.ts | 145 +++ tests/codex-integration-status.test.ts | 209 ++++ tests/codex-route.test.ts | 155 +++ tests/proxy-service.test.ts | 693 +++++++++++ 20 files changed, 5035 insertions(+) create mode 100644 docs/codex-native-install-test-and-remove.zh-CN.md create mode 100644 src/codex-integration/cc-switch.ts create mode 100644 src/codex-integration/chatgpt-capability.ts create mode 100644 src/codex-integration/hooks.ts create mode 100644 src/codex-integration/route.ts create mode 100644 src/codex-integration/skill.ts create mode 100644 src/codex-integration/status.ts create mode 100644 src/codex-integration/toml-field.ts create mode 100644 src/codex/bootstrap-hook.ts create mode 100644 src/proxy-service/index.ts create mode 100644 src/proxy-service/service.ts create mode 100644 src/proxy-service/systemd.ts create mode 100644 src/proxy-service/task-scheduler.ts create mode 100644 tests/codex-cc-switch.test.ts create mode 100644 tests/codex-chatgpt-capability.test.ts create mode 100644 tests/codex-hooks-skill.test.ts create mode 100644 tests/codex-install-faces.test.ts create mode 100644 tests/codex-integration-status.test.ts create mode 100644 tests/codex-route.test.ts create mode 100644 tests/proxy-service.test.ts diff --git a/docs/codex-native-install-test-and-remove.zh-CN.md b/docs/codex-native-install-test-and-remove.zh-CN.md new file mode 100644 index 0000000000..480c817144 --- /dev/null +++ b/docs/codex-native-install-test-and-remove.zh-CN.md @@ -0,0 +1,168 @@ +# Codex 原生安装、真实请求验证与移除(Windows) + +本文用于在本机验证 `bili plugin install codex` 写入的**原生 Codex 配置路由**。它与 `bili codex` 启动器测试不同:验证时会直接运行 `codex`,让 Codex 自己读取 `CODEX_HOME/config.toml`,并让模型请求经过本机 bili 代理。 + +先完成临时目录流程;它不会使用或修改日常 `~/.codex` 配置。临时目录里的 Codex 登录状态与日常登录隔离。若你希望复用现有 ChatGPT 登录,请看后面的“使用日常 CODEX_HOME”。 + +## 前提 + +- Windows PowerShell。 +- 已安装 `bili`,并确认 `bili --version` 能运行。 +- 已安装 Codex CLI,确认 `codex --version` 能运行。 +- 要验证真实请求,必须有当前 Codex 支持的认证方式和可用模型。临时 `CODEX_HOME` 不继承日常登录;需要在该临时 home 自行完成官方 Codex 登录,或使用它所支持的其他本机认证方式。不要复制 `auth.json`、cookie 或 token 到临时目录。 +- 测试会真实调用模型,可能消耗账户额度。先选用适合的模型和短提示。 + +## A. 临时 CODEX_HOME:安装、请求验证、移除 + +在一个新的 PowerShell 窗口按顺序执行。此流程会创建 `$env:TEMP\bili-codex-native-test`,安装 bili MCP + 模型路由;请不要在测试过程中手动修改该目录里的 `config.toml`。 + +```powershell +$testRoot = Join-Path $env:TEMP 'bili-codex-native-test' +$env:CODEX_HOME = Join-Path $testRoot 'codex-home' +New-Item -ItemType Directory -Force -Path $env:CODEX_HOME | Out-Null + +bili --version +codex --version +bili plugin install codex +bili plugin list | Select-String codex +``` + +安装器应报告四个面:`mcp: installed ...`、`model route: ... routed through bili`、`hook: SessionStart hook added`、`skill: ACP skill installed`。检查实际写入内容: + +```powershell +Get-Content (Join-Path $env:CODEX_HOME 'config.toml') +Get-Content (Join-Path $env:CODEX_HOME 'skills\bili\SKILL.md') +``` + +预期根级配置包含类似下面的 URL(端口可能不同): + +```toml +openai_base_url = "http://127.0.0.1:/bili/https://api.openai.com/v1" +``` + +同时应看到一个 hook 条目(脚本路径指向你本机 bili 的 `dist/codex/bootstrap-hook.js`): + +```toml +[[hooks.SessionStart]] +hooks = [{ type = "command", command = "node \".../dist/codex/bootstrap-hook.js\"", timeout = 15 }] +``` + +**必须是 `[[hooks.SessionStart]]` 数组表形式,且 handler 必须嵌在 `hooks = [...]` 数组里。** 这两点各自对应一种失败,互不相同: + +1. **响的失败**:Codex 把 `hooks` 反序列化为序列,写成 `[hooks.SessionStart]` 加 `hooks = [{...}]`(map 形式)会让配置无法加载,进而导致 Codex 桌面端打不开——而且报错文本可能完全不指向这里(实测只显示 `AbsolutePathBuf deserialized without a base path in model_catalog json`)。 +2. **哑的失败**:每个条目是 `MatcherGroup`——`{ matcher?, hooks = [ { type, command, timeout } ] }`。把 `type`/`command`/`timeout` 直接写在条目上,这些字段会被 Codex **静默丢弃**:配置能加载、`codex mcp list` 也成功,但 hook 从不注册。这种失败**任何"配置能否加载"的检查都发现不了**——只有 Codex 自己的 `hooks/list` app-server RPC 能看见。 + +安装器在写入前会做结构自检,拒绝任何一种已知会失败的形状,并把发现的旧扁平条目就地升级。想确认配置仍可加载,用 `codex mcp list`(`codex --version` 不加载配置,查不出来);想确认 hook 真的被注册,要看 Codex 自己的 hook 列表(待确认钩子列表里应出现 `bootstrap-hook.js`)。 + +这个数组可以共存多个条目:若你已经用 lean-ctx 之类的工具写过 SessionStart hook,bili 会**追加**自己的条目并保留你的,卸载时也只删自己那一条。 + +Codex 只有在 `[features] hooks = true` 时才会执行 hook。若你的配置里没有这一项(或显式设为 `false`),bili 会写入 hook 条目并明确提示,但不会替你改写该开关;需要时自行加上 `[features]` 下的 `hooks = true`。hook 只做 attach:代理没在运行时它直接退出 0,不影响 Codex 启动。 + +不要手动将它改成模型厂商 URL;这条 loopback 地址确保代理不可用时请求失败关闭,不会悄悄绕过 bili。 + +启动持久代理。如果希望用 per-user 登录计划任务: + +```powershell +bili service install +bili service status +``` + +`bili service install` 会在 Codex 稳定端口注册并启动 per-user 代理任务。若已有 `bili start` 进程,只有在它监听的端口与上面 `openai_base_url` 中的端口一致时才能复用;否则应安装此服务,或让现有进程监听该端口。用 `bili doctor` 检查状态:健康端口只会显示 `proxy-ready` 或 `configured`,这还不代表观察到了模型请求。 + +现在直接调用本机 Codex CLI,而不是 `bili codex`: + +```powershell +codex exec --skip-git-repo-check --model gpt-5-codex "请只回复:native-route-ok" +``` + +模型名按你的账户可用模型调整。也可以在启动前先明确指定短时覆盖: + +```powershell +$env:BILI_MCP_PROXY = 'http://127.0.0.1:' +codex exec --skip-git-repo-check --model gpt-5-codex "请只回复:native-route-ok" +Remove-Item Env:BILI_MCP_PROXY +``` + +`BILI_MCP_PROXY` 只用于 MCP 工具连接;模型路由由 `config.toml` 决定。替换示例端口时使用安装器写入的真实代理端口。若当前 Codex 配置使用自定义 provider,安装器仅在检测到 CC Switch 明确处于 Direct 模式时,才会把当前选中的 `[model_providers.].base_url` 包装到 bili;不会更改 CC Switch 数据库、provider 选择或其他配置。CC Switch 切换 provider/模式或同步配置时可能重写该字段;bili 不运行 watcher 与其抢写。若安装报告冲突,先查看 CC Switch 当前模式及 provider,不要手工覆盖字段。 + +成功响应后,再检查: + +```powershell +bili doctor +``` + +只有代理统计里观察到 Codex 模型请求,Codex 集成才会报告 `verified`。`configured` 表示配置存在但还没有观察到请求;`proxy-ready` 只表示代理健康;`bypassed` 表示路由被其他设置遮蔽或绕过。若请求失败,先检查 `bili doctor`、代理是否仍在运行、`config.toml` 中 provider 的 `base_url`,以及 Codex CLI 的认证状态;不要为了“让它能通”把路由直接改到上游。 + +测试结束,先移除插件,再查看代理服务状态: + +```powershell +bili plugin remove codex +bili service status +``` + +只有状态显示这个 bili 计划任务已注册时,才执行: + +```powershell +bili service disable +bili service remove +``` + +若代理由另一个 `bili start` 进程启动,用那个终端的 Ctrl+C 停止它;不要结束其他用户服务。验证移除结果: + +```powershell +Get-Content (Join-Path $env:CODEX_HOME 'config.toml') +bili plugin list | Select-String codex +``` + +MCP block、bili 写入的 `[hooks.SessionStart]` 条目和 `skills\bili\SKILL.md` 都应已移除;若原配置没有 `openai_base_url`,bili 写入的根级路由也应还原。原先已有的非 bili 字段应仍在:这包括别人写的 hook 条目(bili 只删自己的那一条)以及同名但非 bili 所有的 skill 文件(bili 完全不碰)。只有确认 `$testRoot` 是本次创建的测试目录后,才执行下方清理;这会删除该临时目录中的 Codex 配置和可能存在的临时数据: + +```powershell +$expectedRoot = Join-Path $env:TEMP 'bili-codex-native-test' +if ($testRoot -eq $expectedRoot -and (Test-Path -LiteralPath $testRoot)) { + Remove-Item -LiteralPath $testRoot -Recurse -Force +} +Remove-Item Env:CODEX_HOME -ErrorAction SilentlyContinue +``` + +若 `bili service install` 实际创建了计划任务,`bili service remove` 会移除它;若 `bili service status` 报告有同名但非 bili 所有的任务,安装/移除操作会拒绝触碰它。不要用 `schtasks /Delete /F` 手动删除未知任务。 + +## B. 使用日常 CODEX_HOME(保留现有登录) + +仅当你明确想用日常 Codex 登录时使用此流程。它会修改真实 Codex 的 `config.toml`,但不应读取、复制或覆盖登录凭据。先关闭 Codex,备份配置,再让 bili 安装/卸载: + +```powershell +$codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $env:USERPROFILE '.codex' } +$config = Join-Path $codexHome 'config.toml' +$backup = "$config.before-bili-test.bak" +if (Test-Path -LiteralPath $config) { + Copy-Item -LiteralPath $config -Destination $backup -ErrorAction Stop +} + +bili plugin install codex +bili plugin list | Select-String codex +bili service status +``` + +如果这是由 CC Switch 管理的 Direct 配置,安装输出应明确显示 `CC Switch Direct provider routed through bili`。保持 Direct 模式和同一 provider 完成测试;切换 provider 或模式后,CC Switch 可能重写 `base_url`,此时 bili 会报告冲突并保留新值。Routing/Aggregation 模式不会被此安装器自动改写。 + +启动代理后,在同一用户环境直接运行 `codex exec`,按上面的方式发出一条短请求;确认 `bili doctor` 显示 `verified` 后,原生路由测试才算完成。若安装报告 conflict、没有本机认证或模型不可用,就停止测试并保留原配置,不要删除/覆盖已有 provider 的 `base_url`。 + +清理时先运行 `bili plugin remove codex`。安装器按 sidecar 记录恢复之前的路由值;如果你在安装后自己改过该字段,卸载会保留你的修改。核对备份和当前配置后,再自行决定是否恢复备份: + +```powershell +bili plugin remove codex +Get-Content -LiteralPath $config +if (Test-Path -LiteralPath $backup) { + Compare-Object (Get-Content -LiteralPath $backup) (Get-Content -LiteralPath $config) +} +``` + +只有确认测试期间没有需要保留的 Codex 配置变更时,才手动恢复备份。**不要删除整个 `$CODEX_HOME`,也不要删除 `auth.json` 或其他登录状态文件。**如果安装了代理服务,按 A 节执行 `bili service disable` 和 `bili service remove`。 + +## 结果判定 + +- **通过原生路由验证:** 直接执行 `codex exec` 收到模型响应,且随后 `bili doctor` 将 Codex 集成标为 `verified`。 +- **安装成功、请求未验证:** 插件列表显示 route installed,但 doctor 仍是 `configured`。这不算模型请求已接入。 +- **只测了启动器:** 执行的是 `bili codex ...`。它能验证 Codex launcher lane,但不能替代本指南中的原生命令测试。 +- **代理不可用:** 原生 Codex 请求应失败在 loopback,不应回退到直连上游。 +- **CC Switch Direct:** 对当前选中的自定义 provider,安装器可在 Codex `config.toml` 中建立可撤销的 bili `base_url` 路由;CC Switch 后续同步仍可能重写它。**Routing/Aggregation:** 仅检测并报告,不自动改写。安装器不会修改 CC Switch 数据库或增加 watcher。 diff --git a/src/codex-integration/cc-switch.ts b/src/codex-integration/cc-switch.ts new file mode 100644 index 0000000000..1257131983 --- /dev/null +++ b/src/codex-integration/cc-switch.ts @@ -0,0 +1,122 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +export type CcSwitchMode = "direct" | "routing" | "aggregation" | "unknown"; + +export interface CcSwitchDetection { + discovered: boolean; + mode: CcSwitchMode; + compatibility: "unsupported" | "config-route-only"; + evidence: string[]; + detail: string; +} + +function object(value: unknown): Record | undefined { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function modeValue(root: unknown): string | undefined { + const row = object(root); + if (!row) return undefined; + const apps = object(row.apps); + const codex = object(row.codex) ?? object(apps?.codex); + const values = [ + row.mode, + row.proxyMode, + row.routingMode, + codex?.mode, + codex?.proxyMode, + ]; + for (const candidate of values) { + if (typeof candidate === "string") + return candidate.trim().toLowerCase().replace(/[ _]/g, "-"); + } + return undefined; +} + +function normalizeMode(value: string | undefined): CcSwitchMode { + if (value === "direct" || value === "direct-mode") return "direct"; + if (value === "routing" || value === "routing-mode" || value === "proxy") + return "routing"; + if ( + value === "aggregation" || + value === "aggregator" || + value === "aggregation-mode" + ) + return "aggregation"; + return "unknown"; +} + +export function detectCcSwitchFromText( + settingsText?: string, + liveStateText?: string, +): CcSwitchDetection { + const evidence: string[] = []; + let mode: CcSwitchMode = "unknown"; + for (const [label, text] of [ + ["settings.json", settingsText], + ["live-state.json", liveStateText], + ] as const) { + if (text === undefined) continue; + evidence.push(label); + try { + const parsed: unknown = JSON.parse(text); + const found = normalizeMode(modeValue(parsed)); + if (found !== "unknown") mode = found; + } catch { + return { + discovered: true, + mode: "unknown", + compatibility: "unsupported", + evidence, + detail: `${label} exists but is not valid JSON; bili did not modify it`, + }; + } + } + if (evidence.length === 0) + return { + discovered: false, + mode: "unknown", + compatibility: "unsupported", + evidence, + detail: "CC Switch was not detected", + }; + return { + discovered: true, + mode, + compatibility: mode === "direct" ? "config-route-only" : "unsupported", + evidence, + detail: + mode === "unknown" + ? "CC Switch state was found but its Codex mode is not recognized; discovery is not proof of routing compatibility" + : mode === "direct" + ? "CC Switch Direct can use a reversible route on the active Codex provider base_url; provider-database synchronization is not integrated" + : `CC Switch reports ${mode} mode; bili does not rewrite its provider state and has no coordination interface, so this is not a compatibility claim`, + }; +} + +export function detectCcSwitch(home = os.homedir()): CcSwitchDetection { + const root = path.join(home, ".cc-switch"); + const files = ["settings.json", "live-state.json"]; + const contents: Array = files.map((name) => { + try { + return fs.readFileSync(path.join(root, name), "utf8"); + } catch { + return undefined; + } + }); + return detectCcSwitchFromText(contents[0], contents[1]); +} + +export function isProxyManagedCredential(value: string): boolean { + return ( + value + .trim() + .replace(/^Bearer\s+/i, "") + .trim() + .toUpperCase() === "PROXY_MANAGED" + ); +} diff --git a/src/codex-integration/chatgpt-capability.ts b/src/codex-integration/chatgpt-capability.ts new file mode 100644 index 0000000000..02a06b7a96 --- /dev/null +++ b/src/codex-integration/chatgpt-capability.ts @@ -0,0 +1,16 @@ +/** ChatGPT subscription/Desktop is intentionally not treated as an API route. + * This capability record is declarative: it never reads, copies, persists, or + * injects auth.json, cookies, session tokens, or desktop credentials. */ +export interface ChatGptDesktopCapability { + state: "待完成/可实现"; + credentials: "not-read-not-persisted"; + officialLoginChannels: "preserved"; + desktopMcp: "separate-from-model-routing"; +} + +export const chatGptDesktopCapability: ChatGptDesktopCapability = { + state: "待完成/可实现", + credentials: "not-read-not-persisted", + officialLoginChannels: "preserved", + desktopMcp: "separate-from-model-routing", +}; diff --git a/src/codex-integration/hooks.ts b/src/codex-integration/hooks.ts new file mode 100644 index 0000000000..6c3a14befa --- /dev/null +++ b/src/codex-integration/hooks.ts @@ -0,0 +1,342 @@ +// Ticket 08: Codex SessionStart hook (the face the user noticed was missing). +// +// Codex >= 0.160 supports hooks through `config.toml` tables plus the +// `[features] hooks = true` switch, with the SAME event names Claude Code uses +// (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, +// `SessionEnd`). The hook program receives one JSON payload on stdin and is +// expected to exit quickly; bili's hook is attach-only and fails open. +// +// Ownership mirrors the rest of the Codex lane: bili writes ONE entry it can +// recognize by content (a command naming our own hook script) and never +// rewrites a foreign entry, a foreign `hooks` switch value, or an unexpected +// table shape. `bili plugin remove codex` deletes exactly that entry. + +import { tableRegions } from "./toml-field.js"; + +/** The TOML table Codex reads hook entries from. */ +export const CODEX_HOOKS_TABLE = "hooks.SessionStart"; + +/** `[features] hooks = true` — the master switch for the hook system. */ +const FEATURES_TABLE = "features"; +const FEATURES_KEY = "hooks"; + +/** Codex's stage names it groups hook tables under. Kept in the type so a + * future ticket can add stages without re-typing the entry shape. */ +export type CodexHookStage = "session_start"; + +export interface CodexHookEntry { + kind: CodexHookStage; + command: string; + timeoutSec?: number; +} + +/** True for a hook command naming bili's own Codex hook script. Path may differ + * across installs/upgrades (checkout vs. global npm), so match the script + * name, not the absolute path — same rule as the Claude lane. */ +export function isBiliCodexHookCommand(command: string): boolean { + return /(?:^|[\\/])codex[\\/]bootstrap-hook\.(?:js|mjs|ts)["']?\s*(?:$|\s)/.test( + command.trim(), + ); +} + +/** Parse the hook entries out of a `hooks.SessionStart` region. Only `command` + * is load-bearing for us. Deliberately regex-based: an unrecognizable region + * yields an empty list, so the caller treats it as foreign structure instead + * of overwriting it. Handles both `command = "..."` on its own line (the + * array-of-tables form bili writes) and inline tables. */ +export function readCodexHookCommands(region: string): string[] { + const out: string[] = []; + for (const match of region.matchAll( + /command\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^']*)')/g, + )) { + const raw = match[1]; + if (raw === undefined) continue; + if (raw.startsWith("'")) { + out.push(raw.slice(1, -1)); + continue; + } + try { + const parsed: unknown = JSON.parse(raw); + if (typeof parsed === "string") out.push(parsed); + } catch { + // A malformed escape is not ours to repair; skip the entry. + } + } + return out; +} + +/** Does the config already carry bili's hook entry? */ +export function findBiliCodexHook(text: string): string | undefined { + for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { + const command = readCodexHookCommands(region).find(isBiliCodexHookCommand); + if (command !== undefined) return command; + } + return undefined; +} + +/** The `[features] hooks` switch, when the user has set one. Scanned by hand + * rather than via `findTableScalar`: the value is a TOML BOOLEAN + * (`hooks = true`), which the string-only scalar finder deliberately does not + * match. + * + * The `\r?` before `$` is load-bearing. Codex keeps CRLF line endings on + * Windows, and neither `[ \t]*` nor the optional comment group consumes a + * trailing `\r`, so an anchored `$` never matched: the installer reported + * "hook execution is not enabled" on a config that plainly said + * `hooks = true`, and would have nagged every Windows user. */ +export function codexHooksFeature( + text: string, +): { value: boolean; raw: string } | undefined { + for (const region of tableRegions(text, FEATURES_TABLE)) { + for (const line of region.split("\n").slice(1)) { + const match = + /^[ \t]*hooks[ \t]*=[ \t]*([^#\s]+)[ \t]*(?:#.*)?\r?$/.exec(line); + if (match === null) continue; + const raw = match[1]; + if (raw === undefined) continue; + return { value: raw.trim().toLowerCase() === "true", raw }; + } + } + return undefined; +} + +export type CodexHookPlan = + | { action: "install" | "refresh"; text: string; note: string } + | { action: "keep"; text: string; note: string }; + +/** Render the hook entry bili owns. + * + * THE NESTED `hooks = [...]` ARRAY IS LOAD-BEARING. Codex deserializes each + * `[[hooks.SessionStart]]` element as a `MatcherGroup`: + * `{ matcher?, hooks = [ { type = "command", command, timeout } ] }`. An + * earlier revision wrote `type`/`command`/`timeout` DIRECTLY on the element; + * those are unknown keys to `MatcherGroup`, so serde drops them silently — the + * config still loads, `codex mcp list` still succeeds, and the hook simply + * never registers. The host showed it as a hook missing from its + * pending-confirmation list, with no error anywhere. + * + * A load probe CANNOT catch this class of bug (both shapes load fine). The + * only red-capable loop is Codex's own app-server `hooks/list` RPC — see + * `probe-hooks.mjs` during development, and the regression test that pins this + * shape in tests/codex-hooks-skill.test.ts. */ +export function codexHookTable(command: string, timeoutSec = 15): string { + return `[[${CODEX_HOOKS_TABLE}]]\nhooks = [{ type = "command", command = ${JSON.stringify(command)}, timeout = ${timeoutSec} }]\n`; +} + +/** Is this region the nested `MatcherGroup` shape Codex actually registers? + * `false` means the region still carries handler fields directly on the entry + * (bili's older, silently-invisible output), which must be replaced whole + * rather than command-rewritten. */ +function isNestedHookRegion(region: string): boolean { + return /^\s*hooks\s*=\s*\[/m.test(region); +} + +/** The line ending a config already uses. Follows the repo convention + * (src/kimi/toml-edit.ts:21, src/launcher.ts:2466): never convert a user's + * file, and never mix endings into it — Codex keeps CRLF on Windows. */ +function detectEol(text: string): string { + return text.includes("\r\n") ? "\r\n" : "\n"; +} + +/** Replace bili's own entry inside an existing region, leaving every other + * entry (and any foreign formatting we cannot parse) untouched: only the + * matched `command = "..."` span is rewritten. */ +function rewriteBiliHookCommand(region: string, command: string): string { + let replaced = false; + return region.replace( + /command\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^']*)')/g, + (match, raw: string) => { + if (replaced) return match; + let decoded: string | undefined; + if (raw.startsWith("'")) { + decoded = raw.slice(1, -1); + } else { + try { + const parsed: unknown = JSON.parse(raw); + decoded = typeof parsed === "string" ? parsed : undefined; + } catch { + decoded = undefined; + } + } + if (decoded === undefined || !isBiliCodexHookCommand(decoded)) + return match; + replaced = true; + return `command = ${JSON.stringify(command)}`; + }, + ); +} + +/** Pure planner for the hook face. `command` is the full hook command line + * (node + our hook script). + * + * ADDITIVE, never destructive: `[[hooks.SessionStart]]` is an array of tables, + * so a foreign entry (lean-ctx and friends live there) is a SIBLING, not a + * competitor. bili appends its own entry and refreshes/removes only the entry + * whose command names our own script. An earlier revision treated any + * unrecognized region as a conflict and gave up — which, on the real machine + * (a foreign SessionStart entry already present), meant bili's hook silently + * never installed. */ +export function planCodexHook(text: string, command: string): CodexHookPlan { + const regions = tableRegions(text, CODEX_HOOKS_TABLE); + const owned = regions.find( + (region) => + readCodexHookCommands(region).find(isBiliCodexHookCommand) !== undefined, + ); + if (owned === undefined) { + const eol = detectEol(text); + const prefix = text.length === 0 || text.endsWith("\n") ? text : `${text}${eol}`; + // A foreign entry in the same array is preserved verbatim: we only append. + const suffix = + regions.length > 0 ? " (kept existing SessionStart entries)" : ""; + const entry = codexHookTable(command).replace(/\n$/, "").split("\n").join(eol); + return { + action: "install", + text: `${prefix}${eol}${entry}${eol}`, + note: `SessionStart hook added -> ${CODEX_HOOKS_TABLE}${suffix}`, + }; + } + const existing = readCodexHookCommands(owned).find(isBiliCodexHookCommand); + // Self-heal: an entry bili wrote before the MatcherGroup fix carries + // `type`/`command`/`timeout` directly on the element, which Codex silently + // ignores. Rewriting only the command string would leave it invisible + // forever, so the whole region is replaced with the nested shape. + if (!isNestedHookRegion(owned)) { + const replacement = codexHookTable(command) + .replace(/\n$/, "") + .split("\n") + .join(detectEol(text)); + return { + action: "refresh", + text: text.replace(owned, replacement), + note: "SessionStart hook upgraded to the shape Codex registers", + }; + } + if (existing === command) + return { + action: "keep", + text, + note: "SessionStart hook already installed", + }; + const next = rewriteBiliHookCommand(owned, command); + if (next === owned) + return { action: "keep", text, note: "SessionStart hook left as-is" }; + return { + action: "refresh", + text: text.replace(owned, next), + note: "SessionStart hook refreshed to the current command", + }; +} + +/** Delete bili's hook entry, keeping foreign entries. Returns the text plus + * what was removed, so the uninstall message can report it. + * + * Removal happens at ENTRY boundaries — under `[[hooks.SessionStart]]` one + * region IS one entry, so the whole region goes. An earlier version rewrote + * the inline table in place and then pattern-matched a rendered + * `{ type = "command", command = "", timeout = N }`; once bili switched to the + * array-of-tables shape that pattern never matched, and uninstall silently + * left a `command = ""` stub hook behind. */ +export function stripCodexHook(text: string): { + text: string; + removed: boolean; +} { + let removed = false; + let next = text; + for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { + const ours = readCodexHookCommands(region).find(isBiliCodexHookCommand); + if (ours === undefined) continue; + removed = true; + next = next + .replace(region, "") + .replace(/\n{3,}/g, "\n\n") + .replace(/^\n+/, ""); + if (next.length > 0 && !next.endsWith("\n")) next = `${next}\n`; + } + return { text: next, removed }; +} + +/** `[features] hooks` must be true for Codex to run the hook. Reports what the + * caller has to add, without editing an existing switch the user set. */ +export function codexHooksEnabledNote(text: string): string { + const feature = codexHooksFeature(text); + if (feature === undefined) + return `enable hook execution with [${FEATURES_TABLE}] ${FEATURES_KEY} = true`; + if (!feature.value) + return `[${FEATURES_TABLE}] ${FEATURES_KEY} = ${feature.raw} disables hooks — set it to true to activate`; + return ""; +} + +/** Last line of defence before a hook face is written to a user's real config. + * + * Two DIFFERENT failure modes have bitten this face, and the guard covers both: + * + * 1. LOUD — a config that will not load. The very first revision wrote + * `[hooks.SessionStart]` + `hooks = [{...}]`, which makes `hooks` a MAP; + * Codex reads it as a SEQUENCE and refused to load the file at all + * (`invalid type: map, expected a sequence in 'hooks'`). The host surfaced + * only an unrelated-looking `AbsolutePathBuf deserialized without a base + * path in model_catalog json` and would not start. A config that cannot + * load is worse than a missing feature, so the installer REJECTS its own + * output structurally rather than trusting the renderer. + * + * 2. SILENT — a config that loads and registers nothing. Handler fields + * (`type`/`command`/`timeout`) written DIRECTLY on a `[[hooks.SessionStart]]` + * element are unknown keys on the `MatcherGroup` serde deserializes, so they + * are dropped without a word: the file loads, `codex mcp list` succeeds, and + * the hook never appears in the host's list. Hence the nested `hooks = [...]` + * array is REQUIRED here, not merely allowed. + * + * Returns a human-readable reason when the text would not load or would load + * without registering, else `undefined`. Structural only — it cannot prove + * Codex accepts the entry (that needs the app-server `hooks/list` RPC), but it + * rules out every shape we have seen it reject or silently ignore. */ +export function assertCodexConfigLoads(text: string): string | undefined { + for (const line of text.split("\n")) { + const header = /^\s*(\[\[?[^\]]+\]\]?)\s*(?:#.*)?$/.exec(line); + if (header === null) continue; + const raw = header[1]; + if (raw === undefined) continue; + const inner = raw.replace(/^\[\[?/, "").replace(/\]\]?$/, "").trim(); + // `hooks` spans more than the stage tables bili writes: Codex keeps its + // OWN trust ledger at `[hooks.state.':::']`, written + // as a single-bracket table (it holds key/value pairs, so a table is the + // correct shape and must never be flagged). Matching a bare `hooks` + // prefix treated Codex's own output as a malformed stage table and + // rejected the whole config, which silently skipped the hook face + // whenever a hook had ever been trusted. Only what bili writes is + // inspected: the stage table, plus the flat `[[hooks]]` misuse. + if (inner !== CODEX_HOOKS_TABLE && inner !== "hooks") continue; + // `[[hooks]]` with `event = "..."` is the flat-sequence shape Codex + // rejects with `expected struct HooksToml`: a bare `hooks` array cannot + // hold stage tables keyed by name. + if (inner === "hooks") + return "`[[hooks]]` is not a hook stage — use `[[hooks.SessionStart]]` (Codex expects a struct HooksToml keyed by stage name)"; + if (raw.startsWith("[[")) continue; + return `${raw.trim()} must be [[${inner}]] (Codex reads 'hooks' as a sequence, not a table)`; + } + // A top-level `hooks = ...` assignment would also collapse the sequence. + for (const line of text.split("\n")) { + if (/^\s*\[/.test(line)) break; + if (/^\s*hooks\s*=/.test(line)) + return "a top-level `hooks = ...` key must not be set (Codex reads 'hooks' as a sequence of stage tables)"; + } + for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { + const commands = readCodexHookCommands(region); + if (commands.length === 0) + return `a ${CODEX_HOOKS_TABLE} entry carries no command`; + if (commands.some((command) => command.trim() === "")) + return `a ${CODEX_HOOKS_TABLE} entry carries an empty command`; + // The MatcherGroup shape: handler fields belong INSIDE `hooks = [...]`. + // Without this the entry loads and is silently ignored. + // + // Scoped to OUR entry on purpose. A foreign entry with the wrong shape is + // its owner's bug, and refusing to write bili's own correct entry because + // of it would strand exactly the users who already run another hook tool. + if ( + commands.some(isBiliCodexHookCommand) && + !isNestedHookRegion(region) + ) + return `a ${CODEX_HOOKS_TABLE} entry must nest its handler in a 'hooks = [{ type = "command", ... }]' array (fields set directly on the entry are dropped by Codex, which registers nothing)`; + } + return undefined; +} diff --git a/src/codex-integration/route.ts b/src/codex-integration/route.ts new file mode 100644 index 0000000000..cb42c37325 --- /dev/null +++ b/src/codex-integration/route.ts @@ -0,0 +1,412 @@ +// Ticket 01: bili-owned model route for the native Codex CLI. +// +// Ordinary API-key mode routes Codex through bili by writing the ONE field +// Codex documents for it — the top-level `openai_base_url` — pointing at +// bili's `/bili/` prefix. This is the persistent, no-wrapper entry point the +// Codex proxy spec asks for; the MCP block (plugin-install.ts codexBlock) is a +// SEPARATE concern and proves nothing about model traffic. +// +// Ownership is CONTENT-BASED, exactly like the claude lane's managed block +// (plugin-install.ts isBiliClaudeBaseUrl / unwrapBiliBaseUrl): a value shaped +// `/bili/` is ours and may be refreshed; anything +// else is the user's (or CC Switch's) and is never overwritten — the write is +// refused and reported instead, so bili can never end up fighting a provider +// manager over the same field. + +import fs from "node:fs"; +import path from "node:path"; +import { parseCodexToml } from "../client-config.js"; +import type { CodexConfig } from "../client-config.js"; +import { lanePreferredPort } from "../instance.js"; +import { + findTableScalar, + findTopLevelScalar, + removeTableScalar, + removeTopLevelScalar, + setTableScalar, + setTopLevelScalar, +} from "./toml-field.js"; + +/** The top-level Codex field this module owns. */ +export const CODEX_ROUTE_KEY = "openai_base_url"; + +/** Codex's built-in OpenAI default (codex-rs model-provider-info), used when + * the user has declared no provider and no base URL. */ +export const CODEX_DEFAULT_UPSTREAM = "https://api.openai.com/v1"; + +/** `/bili/` — the shape bili itself writes. Accepts + * any loopback port (the lane's zone port drifts with the EADDRINUSE ladder, + * #1660) and both `127.0.0.1` and `localhost`, because a user may have copied + * a documented value by hand. */ +const BILI_ROUTE_RE = + /^(http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5})\/bili\/(https?:\/\/.+)$/; + +export function isBiliCodexRoute(value: string): boolean { + return BILI_ROUTE_RE.test(value.trim()); +} + +/** Inverse of `codexRouteValue`: recover the real upstream. undefined for + * anything bili did not write. */ +export function unwrapCodexRoute(value: string): string | undefined { + const m = BILI_ROUTE_RE.exec(value.trim()); + return m ? m[2] : undefined; +} + +/** Build the routed value for a real upstream, preserving any `/bili/` + * wrapper the caller already had (so re-planning is idempotent). */ +export function codexRouteValue(origin: string, upstream: string): string { + const real = unwrapCodexRoute(upstream) ?? upstream; + return `${origin.replace(/\/+$/, "")}/bili/${real.replace(/\/+$/, "")}`; +} + +/** The origin the persistent Codex route should point at. Uses the lane's + * sticky zone port (`instance.ts` port-zone.json, honoring the existing + * BILI_ZONE_PORT override) so the route survives the proxy's +1 EADDRINUSE + * ladder and machine reboots — the same stable-origin discipline as every + * other lane (#1660). No new config/env surface is introduced for this. */ +export function codexRouteOrigin(env: NodeJS.ProcessEnv = process.env): string { + return `http://127.0.0.1:${lanePreferredPort("codex", env)}`; +} + +/** The upstream Codex would reach WITHOUT bili in the path — the provider the + * route must wrap. Mirrors launcher.ts `codexUpstreamUrl`'s precedence + * (`model_provider`'s `base_url` > top-level `openai_base_url` > OpenAI + * default) but unwraps bili's own value so re-planning never double-wraps. */ +export function codexRealUpstream(config: CodexConfig | undefined): string { + const provider = + config?.modelProvider !== undefined + ? config?.providers?.[config.modelProvider]?.baseUrl + : undefined; + if (provider !== undefined && provider !== "") + return unwrapCodexRoute(provider) ?? provider; + const direct = config?.openaiBaseUrl; + if (direct !== undefined && direct !== "") + return unwrapCodexRoute(direct) ?? direct; + return CODEX_DEFAULT_UPSTREAM; +} + +/** Why the route cannot be (or is not) the effective one. Both are reported, + * never silently "fixed": the spec forbids fighting a provider manager. */ +export type CodexRouteConflict = + /** A foreign (non-bili) `openai_base_url` is already set. */ + | { kind: "foreign-openai-base-url"; value: string } + /** `model_provider` names a provider with its own `base_url`, so Codex + * ignores the top-level field entirely — writing it would be a no-op. */ + | { kind: "shadowed-by-provider"; provider: string; value: string }; + +export interface CodexRoutePlan { + action: "install" | "refresh" | "keep" | "conflict"; + /** The full file text after the action (`keep`/`conflict` return it unchanged). */ + text: string; + /** The routed value bili owns or would own. */ + value?: string; + target?: CodexRouteTarget; + conflict?: CodexRouteConflict; + note: string; +} + +export type CodexRouteTarget = + | { kind: "top-level" } + | { kind: "provider"; provider: string }; + +export interface CodexRouteRecord { + schemaVersion: 1; + writtenValue: string; + previousValue: string | null; + upstream: string; + target?: CodexRouteTarget; +} + +export function codexRouteRecordPath(configFile: string): string { + return `${configFile}.bili-route.json`; +} + +export function readCodexRouteRecord( + file: string, +): CodexRouteRecord | undefined { + try { + const value: unknown = JSON.parse(fs.readFileSync(file, "utf8")); + if (value === null || typeof value !== "object" || Array.isArray(value)) + return undefined; + const row = value as Record; + if ( + row.schemaVersion !== 1 || + typeof row.writtenValue !== "string" || + !(typeof row.previousValue === "string" || row.previousValue === null) || + typeof row.upstream !== "string" + ) + return undefined; + const target = row.target === undefined + ? { kind: "top-level" as const } + : row.target; + if ( + target === null || + typeof target !== "object" || + !("kind" in target) || + (target.kind !== "top-level" && + (target.kind !== "provider" || !("provider" in target) || typeof target.provider !== "string")) + ) return undefined; + return { + schemaVersion: 1, + writtenValue: row.writtenValue, + previousValue: row.previousValue, + upstream: row.upstream, + target: target as CodexRouteTarget, + }; + } catch { + return undefined; + } +} + +export function writeCodexRouteRecord( + file: string, + record: CodexRouteRecord, +): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + const temporary = `${file}.${process.pid}.tmp`; + fs.writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { + mode: 0o600, + }); + fs.renameSync(temporary, file); +} + +export function removeCodexRouteRecord(file: string): void { + try { + fs.unlinkSync(file); + } catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) + throw error; + } +} + +/** Pure planner: decide what (if anything) to do to `text`. Provider-table + * routes are allowed only for an explicitly detected CC Switch Direct mode; + * Routing/Aggregation/unknown remain untouched. */ +export function planCodexRoute( + text: string, + opts: { + origin: string; + config?: CodexConfig; + ownedValue?: string; + ownedRecord?: CodexRouteRecord; + ccSwitchMode?: "direct" | "routing" | "aggregation" | "unknown"; + }, +): CodexRoutePlan { + const config = opts.config ?? parseCodexToml(text); + const provider = config.modelProvider; + const providerBase = provider ? config.providers?.[provider]?.baseUrl : undefined; + const record = opts.ownedRecord; + const recordedTarget = record?.target ?? { kind: "top-level" as const }; + const activeTarget: CodexRouteTarget = + provider && providerBase ? { kind: "provider", provider } : { kind: "top-level" }; + if ( + record && + (recordedTarget.kind !== activeTarget.kind || + (recordedTarget.kind === "provider" && + activeTarget.kind === "provider" && + recordedTarget.provider !== activeTarget.provider)) + ) { + return { + action: "conflict", + text, + conflict: provider && providerBase + ? { kind: "shadowed-by-provider", provider, value: providerBase } + : { kind: "foreign-openai-base-url", value: "active Codex target changed" }, + note: `Codex's effective route target changed since bili installed it; run bili plugin remove codex before installing the new provider route`, + }; + } + const ownProvider = + recordedTarget.kind === "provider" && + recordedTarget.provider === provider && + record?.writtenValue === providerBase; + + if (provider && providerBase) { + const target: CodexRouteTarget = { kind: "provider", provider }; + if ( + record && recordedTarget.kind === "provider" && + recordedTarget.provider === provider && providerBase !== record.writtenValue + ) { + return { + action: "conflict", + text, + conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, + note: `provider ${provider} base_url changed after bili installed it; likely a CC Switch rewrite, so it was left untouched`, + }; + } + if (ownProvider && opts.ccSwitchMode !== "direct") { + return { + action: "conflict", + text, + conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, + note: `CC Switch is no longer confirmed in Direct mode; existing bili route was left untouched`, + }; + } + if (ownProvider) { + const value = codexRouteValue(opts.origin, record!.upstream); + if (providerBase === value) + return { action: "keep", text, value, target, note: `CC Switch Direct provider ${provider} already routes through bili` }; + return { + action: "refresh", + text: setTableScalar(text, `model_providers.${provider}`, "base_url", value), + value, + target, + note: `CC Switch Direct provider ${provider} route refreshed -> ${value}`, + }; + } + if (isBiliCodexRoute(providerBase)) { + return { + action: "conflict", + text, + conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, + note: `provider ${provider} already has a bili-shaped base_url without matching ownership evidence — left untouched`, + }; + } + if (opts.ccSwitchMode !== "direct") { + return { + action: "conflict", + text, + conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, + note: `model_provider = "${provider}" declares base_url ${providerBase}; only detected CC Switch Direct mode may route this provider`, + }; + } + const value = codexRouteValue(opts.origin, providerBase); + return { + action: "install", + text: setTableScalar(text, `model_providers.${provider}`, "base_url", value), + value, + target, + note: `CC Switch Direct provider ${provider} routed through bili -> ${value}; CC Switch may rewrite it when provider or mode changes`, + }; + } + + const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); + const ownTopLevel = + recordedTarget.kind === "top-level" && + ((record?.writtenValue !== undefined && existing?.value === record.writtenValue) || + (opts.ownedValue !== undefined && existing?.value === opts.ownedValue)); + if (existing && !ownTopLevel) { + return { + action: "conflict", + text, + conflict: { kind: "foreign-openai-base-url", value: existing.value }, + note: `${CODEX_ROUTE_KEY} is already set to a non-bili value — left untouched`, + }; + } + const value = codexRouteValue(opts.origin, codexRealUpstream(config)); + if (existing?.value === value) + return { action: "keep", text, value, target: { kind: "top-level" }, note: `${CODEX_ROUTE_KEY} already routed through bili` }; + return { + action: ownTopLevel ? "refresh" : "install", + text: setTopLevelScalar(text, CODEX_ROUTE_KEY, value), + value, + target: { kind: "top-level" }, + note: ownTopLevel + ? `${CODEX_ROUTE_KEY} refreshed -> ${value}` + : `${CODEX_ROUTE_KEY} routed through bili -> ${value}`, + }; +} + +/** What bili currently finds in `text` — the read side of ownership, shared by + * status reporting and uninstall. */ +export interface CodexRouteState { + /** A bili-owned route is present. */ + routed: boolean; + /** The raw field value, when any. */ + value?: string; + /** The real upstream behind a bili-owned route. */ + upstream?: string; + conflict?: CodexRouteConflict; +} + +export function readCodexRoute( + text: string, + ownership?: CodexRouteRecord | string, +): CodexRouteState { + const config = parseCodexToml(text); + const record = typeof ownership === "string" ? undefined : ownership; + const ownedValue = typeof ownership === "string" ? ownership : record?.writtenValue; + const target = record?.target ?? { kind: "top-level" as const }; + const provider = config.modelProvider; + const providerBase = provider ? config.providers?.[provider]?.baseUrl : undefined; + const out: CodexRouteState = { routed: false }; + if (target.kind === "provider") { + if (provider === target.provider && providerBase !== undefined) { + out.value = providerBase; + if (providerBase === ownedValue && isBiliCodexRoute(providerBase)) { + out.routed = true; + out.upstream = record?.upstream ?? unwrapCodexRoute(providerBase); + } else { + out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; + } + return out; + } + if (target.provider !== provider && provider && providerBase) + out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; + return out; + } + const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); + if (existing !== undefined) { + out.value = existing.value; + if (ownedValue !== undefined && existing.value === ownedValue && isBiliCodexRoute(existing.value)) { + out.routed = true; + out.upstream = record?.upstream ?? unwrapCodexRoute(existing.value); + } else { + out.conflict = { kind: "foreign-openai-base-url", value: existing.value }; + } + } + if (provider && providerBase) + out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; + return out; +} + +/** The route value bili would write right now for `file` — used by status + * reporting to tell "configured for THIS origin" from "configured for a + * drifted one". */ +export function desiredCodexRoute(text: string, origin: string): string { + return codexRouteValue(origin, codexRealUpstream(parseCodexToml(text))); +} + +export function codexRouteFilePath(codexHome: string): string { + return path.join(codexHome, "config.toml"); +} + +export function readCodexRouteFile(file: string): string { + try { + return fs.readFileSync(file, "utf8"); + } catch { + return ""; + } +} + +/** Remove bili's route field, leaving every other byte alone. Returns the new + * text plus whether anything changed. */ +export function restoreCodexRoute( + text: string, + record?: CodexRouteRecord, +): { + text: string; + restored: boolean; + stillOwned: boolean; +} { + if (record === undefined) return { text, restored: false, stillOwned: false }; + const target = record.target ?? { kind: "top-level" as const }; + if (target.kind === "provider") { + const table = `model_providers.${target.provider}`; + const existing = findTableScalar(text, table, "base_url"); + if (existing === undefined || existing.value !== record.writtenValue) + return { text, restored: false, stillOwned: false }; + const next = + record.previousValue === null + ? removeTableScalar(text, table, "base_url") + : setTableScalar(text, table, "base_url", record.previousValue); + return { text: next, restored: true, stillOwned: true }; + } + const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); + if (existing === undefined || existing.value !== record.writtenValue) + return { text, restored: false, stillOwned: false }; + const next = + record.previousValue === null + ? removeTopLevelScalar(text, CODEX_ROUTE_KEY) + : setTopLevelScalar(text, CODEX_ROUTE_KEY, record.previousValue); + return { text: next, restored: true, stillOwned: true }; +} diff --git a/src/codex-integration/skill.ts b/src/codex-integration/skill.ts new file mode 100644 index 0000000000..765f131125 --- /dev/null +++ b/src/codex-integration/skill.ts @@ -0,0 +1,169 @@ +// Ticket 08: the ACP skill face for native Codex. +// +// Codex discovers reusable procedures as skills under +// `/skills//SKILL.md` (YAML frontmatter + markdown body) — +// the same extension point `skills/.system/*` and third-party skills use. The +// Claude lane ships the equivalent as a slash command (`/acp-cache`, see +// CLAUDE_ACP_CACHE_COMMAND in plugin-install.ts); Codex has no slash-command +// file, so the skill IS the parity surface: it tells the model which ACP tools +// exist on the `bili` MCP server and when to reach for them. +// +// Ownership: the content is embedded here (not read from a shipped asset) so +// every install form — checkout, global npm, dsh profile copy — carries the +// same bytes. bili rewrites the file only while the frontmatter still names +// `bili`; a same-named skill the user wrote themselves is reported, never +// clobbered. + +import fs from "node:fs"; +import path from "node:path"; +import { resolveCodexHome } from "../client-config.js"; + +/** Directory name under `/skills`. */ +export const CODEX_SKILL_NAME = "bili"; + +/** Ownership marker. A skill file carrying this comment is bili's and may be + * refreshed in place; a same-named file WITHOUT it belongs to the user (or + * another tool) and is never written or deleted — the same content-based rule + * the model route and the hook face use. The name alone is not proof. */ +export const CODEX_SKILL_MARKER = + ""; + +/** The skill document bili installs. Kept as a constant so `codexSkillStatus` + * and the installer cannot drift apart. */ +export const CODEX_SKILL_MARKDOWN = `--- +name: bili +description: billion-context (bili) ACP context compression for this Codex session. Use when the conversation feels summarized, when you need to read or search context that was compressed away, or when checking whether compression is working. +--- + +${CODEX_SKILL_MARKER} + +# billion-context (bili) for Codex + +bili keeps long Codex sessions inside the model's context window by folding +consumed older turns into compressed blocks and re-expanding them on demand. +The model route is persistent (bili owns one field in \`config.toml\`), and the +tools below ride along on the \`bili\` MCP server. + +## Tools + +| Tool | Use it for | +| --- | --- | +| \`acp_status\` | Context usage for this session: what is live, what is folded, compressible ranges with their refs | +| \`acp_cache\` | Prompt-cache reconciliation for this session: hit rate, what caused a miss, what a fold cost | +| \`search_context\` | Keyword search across compressed block summaries — use this BEFORE decompressing blindly | +| \`decompress\` | Restore a folded range by \`blockId\` (or \`startId\`/\`endId\`); \`full: true\` restores originals | +| \`compress\` | Fold consumed ranges into one summary you write (usually automatic; call it only when asked) | +| \`acp_retrieve\` | Read back the full original text behind an \`[acp-stored #mNNNNN]\` placeholder | + +## Rules of thumb + +- Retrieve narrowly: \`search_context\` first, then \`decompress\` the one block that matters. \`full: true\` is a last resort. +- Compression is automatic under pressure; a manual \`compress\` is a deliberate optimization, not routine hygiene. +- Numbers from \`acp_cache\`/\`acp_status\` describe THIS session. Never present them as another session's. +- A tool call failing with \`bili proxy unreachable\` means the local proxy is down: run \`bili service status\` (\`bili service restart\` to fix), then retry. + +## Troubleshooting + +- Route check: \`bili doctor\` (look at \`codex model route\` and the CC Switch section). +- Install or refresh the integration: \`bili plugin install codex\`. Revert it with \`bili plugin remove codex\`. +- CC Switch Direct mode installs a reversible route on the active provider's \`base_url\`. If CC Switch + rewrites or re-syncs that provider, bili reports a conflict and leaves the field alone rather than + fighting it — re-run \`bili plugin install codex\` after switching CC Switch modes. +`; + +/** `/skills/bili`. */ +export function codexSkillDir(env: NodeJS.ProcessEnv = process.env): string { + return path.join(resolveCodexHome(env), "skills", CODEX_SKILL_NAME); +} + +/** `/skills/bili/SKILL.md`. */ +export function codexSkillFile(env: NodeJS.ProcessEnv = process.env): string { + return path.join(codexSkillDir(env), "SKILL.md"); +} + +/** The frontmatter name a skill file declares, when parseable. */ +export function readSkillName(text: string): string | undefined { + const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(text); + const body = frontmatter?.[1]; + if (body === undefined) return undefined; + const match = /^name:\s*(.+?)\s*$/m.exec(body); + const name = match?.[1]; + if (name === undefined) return undefined; + return name.replace(/^["']|["']$/g, ""); +} + +export type CodexSkillState = "installed" | "missing" | "outdated" | "foreign"; + +/** Disk state of the skill face. `outdated` means our marker is present but the + * bytes differ (an upgrade is due, or the user edited a bili-managed file); + * `foreign` means a same-named skill bili does not own. */ +export function codexSkillStatus( + env: NodeJS.ProcessEnv = process.env, +): CodexSkillState { + let text: string; + try { + text = fs.readFileSync(codexSkillFile(env), "utf8"); + } catch { + return "missing"; + } + if (text === CODEX_SKILL_MARKDOWN) return "installed"; + return text.includes(CODEX_SKILL_MARKER) ? "outdated" : "foreign"; +} + +export interface CodexSkillInstall { + state: CodexSkillState | "written"; + note: string; + written: boolean; +} + +/** Install or refresh the skill. A file bili does not own is left alone. */ +export function installCodexSkill( + env: NodeJS.ProcessEnv = process.env, +): CodexSkillInstall { + const file = codexSkillFile(env); + const state = codexSkillStatus(env); + if (state === "installed") + return { + state, + note: "ACP skill already installed", + written: false, + }; + if (state === "foreign") + return { + state, + note: `${file} exists but is not a bili skill — left untouched`, + written: false, + }; + fs.mkdirSync(codexSkillDir(env), { recursive: true }); + fs.writeFileSync(file, CODEX_SKILL_MARKDOWN, { mode: 0o644 }); + return { + state: "written", + note: + state === "missing" + ? `ACP skill installed -> ${file}` + : `ACP skill refreshed -> ${file}`, + written: true, + }; +} + +/** Remove the skill file only when it is ours; drops the directory when empty. */ +export function removeCodexSkill(env: NodeJS.ProcessEnv = process.env): { + removed: boolean; + note: string; +} { + const state = codexSkillStatus(env); + if (state === "missing") + return { removed: false, note: "ACP skill not installed" }; + if (state === "foreign") + return { + removed: false, + note: "ACP skill directory is not owned by bili — left untouched", + }; + fs.unlinkSync(codexSkillFile(env)); + try { + fs.rmdirSync(codexSkillDir(env)); + } catch { + // A user may keep notes next to the skill; a non-empty dir stays. + } + return { removed: true, note: "ACP skill removed" }; +} diff --git a/src/codex-integration/status.ts b/src/codex-integration/status.ts new file mode 100644 index 0000000000..e638474d86 --- /dev/null +++ b/src/codex-integration/status.ts @@ -0,0 +1,207 @@ +import { resolveCodexHome } from "../client-config.js"; +import { lanePreferredPort } from "../instance.js"; +import { readCodexRoute, readCodexRouteRecord } from "./route.js"; +import { codexRouteRecordPath } from "./route.js"; +import fs from "node:fs"; +import path from "node:path"; + +export type CodexIntegrationState = + | "proxy-ready" + | "configured" + | "verified" + | "bypassed" + | "unknown"; + +export interface CodexIntegrationReport { + state: CodexIntegrationState; + route: "owned" | "foreign" | "absent"; + proxyHealthy: boolean; + observedCodexRequest: boolean; + detail: string; +} + +export interface CodexStatusDeps { + env?: NodeJS.ProcessEnv; + fetchImpl?: typeof fetch; + codexConfigText?: string; + origin?: string; +} + +/** How long a real Codex request keeps counting as evidence. Long enough that a + * session idling while the user works still reads as verified, short enough + * that a session restored from disk months ago cannot. */ +const CODEX_EVIDENCE_MAX_AGE_MS = 24 * 60 * 60_000; + +/** Upstreams bili's own tests and E2E harnesses point at. A session served from + * one of these proves the forwarding path works, never that a USER's Codex is + * routed — those fixtures are why this module needs any exclusion at all. */ +function isLoopbackUpstream(value: unknown): boolean { + if (typeof value !== "string") return false; + return /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:[/]|$)/i.test( + value.trim(), + ); +} + +/** A session that only the native Codex CLI can have created. Two independent + * signals, either sufficient: + * - `codexClient`: the bounded header hint the server stored at session + * creation; absent (null) on sessions that predate it. + * - `protocol === "responses"`: the OpenAI Responses wire API, which in this + * deployment only Codex's `wire_api = "responses"` selects (every other + * lane speaks chat-completions). + * A hint naming a DIFFERENT client vetoes the session, so a foreign Responses + * client can never be read as Codex evidence. */ +function isCodexSession(row: Record): boolean { + const hint = row.clientHint; + if (typeof hint === "string" && hint.length > 0) { + if (!hint.toLowerCase().includes("codex")) return false; + return true; + } + return row.codexClient === true || row.protocol === "responses"; +} + +function configText(env: NodeJS.ProcessEnv): string { + try { + return fs.readFileSync( + path.join(resolveCodexHome(env), "config.toml"), + "utf8", + ); + } catch { + return ""; + } +} + +/** One session row's worth of evidence: a real, recent, non-fixture Codex + * request. Kept separate from `isCodexSession` so the shape predicates and the + * freshness policy can be read (and tested) independently. */ +function isCodexEvidence(row: Record, now: number): boolean { + if (!isCodexSession(row)) return false; + if (isLoopbackUpstream(row.upstream)) return false; + if (typeof row.requests !== "number" || row.requests <= 0) return false; + const lastSeenMs = row.lastSeenMs; + const lastSeen = row.lastSeen; + const seenAt = + typeof lastSeenMs === "number" + ? lastSeenMs + : typeof lastSeen === "string" + ? Date.parse(lastSeen) + : Number.NaN; + const age = now - seenAt; + return age >= 0 && age <= CODEX_EVIDENCE_MAX_AGE_MS; +} + +interface ProxyFacts { + proxyHealthy: boolean; + observedCodexRequest: boolean; +} + +/** Read-only probe of the stable Codex lane origin. Every failure — refused + * connection, timeout, malformed payload — reads as "no evidence", never as + * negative proof about the user's setup. */ +async function probeProxy( + origin: string, + fetchImpl: typeof fetch, +): Promise { + const absent: ProxyFacts = { + proxyHealthy: false, + observedCodexRequest: false, + }; + try { + const response = await fetchImpl(`${origin}/__bili/health`, { + signal: AbortSignal.timeout(1200), + }); + if (!response.ok) return absent; + const health: unknown = await response.json(); + const healthy = + health !== null && + typeof health === "object" && + (health as Record).ok === true; + if (!healthy) return absent; + const stats = await fetchImpl(`${origin}/__bili/stats`, { + signal: AbortSignal.timeout(1600), + }); + if (!stats.ok) return { proxyHealthy: true, observedCodexRequest: false }; + const data: unknown = await stats.json(); + const sessions = + data !== null && typeof data === "object" + ? (data as Record).sessions + : undefined; + if (!Array.isArray(sessions)) + return { proxyHealthy: true, observedCodexRequest: false }; + const now = Date.now(); + return { + proxyHealthy: true, + observedCodexRequest: sessions.some( + (entry) => + entry !== null && + typeof entry === "object" && + isCodexEvidence(entry as Record, now), + ), + }; + } catch { + return absent; + } +} + +export async function inspectCodexIntegration( + deps: CodexStatusDeps = {}, +): Promise { + const env = deps.env ?? process.env; + const text = deps.codexConfigText ?? configText(env); + const file = path.join(resolveCodexHome(env), "config.toml"); + const route = readCodexRoute( + text, + readCodexRouteRecord(codexRouteRecordPath(file)), + ); + const origin = ( + deps.origin ?? `http://127.0.0.1:${lanePreferredPort("codex", env)}` + ).replace(/\/+$/, ""); + const { proxyHealthy, observedCodexRequest } = await probeProxy( + origin, + deps.fetchImpl ?? fetch, + ); + const report = ( + state: CodexIntegrationState, + detail: string, + routeOverride?: "owned" | "foreign" | "absent", + ): CodexIntegrationReport => ({ + state, + route: + routeOverride ?? + (route.routed ? "owned" : route.conflict ? "foreign" : "absent"), + proxyHealthy, + observedCodexRequest, + detail, + }); + if (observedCodexRequest) + return report("verified", "bili observed a real Codex model request"); + if (route.conflict !== undefined) + return report( + "bypassed", + route.conflict.kind === "shadowed-by-provider" + ? `Codex provider ${route.conflict.provider} owns the effective base_url` + : "openai_base_url is not owned by bili; left untouched", + "foreign", + ); + if (route.routed) + return report( + "configured", + proxyHealthy + ? "bili route is configured; no Codex model request observed yet" + : "bili route is configured; proxy health has not been confirmed", + "owned", + ); + if (proxyHealthy) + return report( + "proxy-ready", + "proxy is healthy; Codex model route is not configured", + "absent", + ); + return report( + "unknown", + text.length === 0 + ? "Codex config is unavailable and no proxy health evidence is available" + : "no route ownership or live proxy evidence is available", + "absent", + ); +} diff --git a/src/codex-integration/toml-field.ts b/src/codex-integration/toml-field.ts new file mode 100644 index 0000000000..c8cc9e0d70 --- /dev/null +++ b/src/codex-integration/toml-field.ts @@ -0,0 +1,288 @@ +// Ticket 01: top-level TOML scalar surgery for ~/.codex/config.toml. +// +// Deliberately NOT a TOML parser. Only top-level `key = "value"` lines ABOVE +// the first table header are touched, so every user comment, blank line, +// ordering and nested `[table]` survives byte-for-byte — the content-ownership +// rule from the Codex proxy spec: bili updates only its own field and never +// rewrites the rest of the file. + +/** A located top-level scalar. `line` is a 0-based index into `text.split("\n")`. */ +export interface TopLevelScalar { + key: string; + value: string; + line: number; +} + +/** TOML basic (double-quoted) and literal (single-quoted) string bodies. A + * line whose value is an array/inline-table/multiline string is NOT a scalar + * we can own — it is reported as not-found rather than mis-parsed. */ +const SCALAR_RE = + /^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')\s*(?:#.*)?$/; + +function decode(raw: string, quoted: "basic" | "literal"): string { + if (quoted === "literal") return raw; + try { + const parsed: unknown = JSON.parse(`"${raw}"`); + return typeof parsed === "string" ? parsed : raw; + } catch { + return raw; + } +} + +function preserveInlineComment(original: string, rendered: string): string { + let quote: "basic" | "literal" | undefined; + let escaped = false; + for (let i = 0; i < original.length; i++) { + const char = original[i]!; + if (quote === "basic") { + if (escaped) escaped = false; + else if (char === "\\") escaped = true; + else if (char === '"') quote = undefined; + } else if (quote === "literal") { + if (char === "'") quote = undefined; + } else if (char === '"') quote = "basic"; + else if (char === "'") quote = "literal"; + else if (char === "#") return `${rendered} ${original.slice(i).trimEnd()}`; + } + return rendered; +} + +/** Locate a top-level scalar, stopping at the first table header: a key after + * `[some.table]` belongs to that table, not to the file root. */ +export function findTopLevelScalar( + text: string, + key: string, +): TopLevelScalar | undefined { + const lines = text.split("\n"); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!.trim(); + if (line.startsWith("[")) return undefined; + if (line === "" || line.startsWith("#")) continue; + const m = SCALAR_RE.exec(line); + if (m === null || m[1] !== key) continue; + return { + key, + value: + m[2] !== undefined ? decode(m[2], "basic") : decode(m[3]!, "literal"), + line: i, + }; + } + return undefined; +} + +/** Set (or insert) a top-level scalar. JSON.stringify emits a valid TOML basic + * string — both grammars escape `\` and `"` identically — which is the same + * serialization plugin-install.ts `codexBlock` relies on. */ +export function setTopLevelScalar( + text: string, + key: string, + value: string, +): string { + const rendered = `${key} = ${JSON.stringify(value)}`; + const lines = text.split("\n"); + const existing = findTopLevelScalar(text, key); + if (existing !== undefined) { + lines[existing.line] = preserveInlineComment( + lines[existing.line]!, + rendered, + ); + return lines.join("\n"); + } + // Insert after the last top-level key; with none, at the very top so the + // key can never land inside a nested table. + let at = 0; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!.trim(); + if (line.startsWith("[")) break; + if (line === "" || line.startsWith("#")) continue; + at = i + 1; + } + lines.splice(at, 0, rendered); + return lines.join("\n"); +} + +/** Delete a top-level scalar line. Only that line goes; surrounding comments + * and blank lines are left exactly as the user had them. */ +export function removeTopLevelScalar(text: string, key: string): string { + const existing = findTopLevelScalar(text, key); + if (existing === undefined) return text; + const lines = text.split("\n"); + lines.splice(existing.line, 1); + return lines.join("\n"); +} + +/** A located scalar inside an exact TOML table. */ +export interface TableScalar extends TopLevelScalar { + table: string; +} + +export function findTableScalar( + text: string, + table: string, + key: string, +): TableScalar | undefined { + const lines = text.split("\n"); + let active = false; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!.trim(); + const header = /^\[([^\]]+)\]\s*(?:#.*)?$/.exec(line); + if (header) { + if (active) return undefined; + active = header[1]!.trim() === table; + continue; + } + if (!active || line === "" || line.startsWith("#")) continue; + const match = SCALAR_RE.exec(line); + if (!match || match[1] !== key) continue; + return { + table, + key, + value: + match[2] !== undefined + ? decode(match[2], "basic") + : decode(match[3]!, "literal"), + line: i, + }; + } + return undefined; +} + +export function setTableScalar( + text: string, + table: string, + key: string, + value: string, +): string { + const lines = text.split("\n"); + const rendered = `${key} = ${JSON.stringify(value)}`; + const existing = findTableScalar(text, table, key); + if (existing) { + lines[existing.line] = preserveInlineComment( + lines[existing.line]!, + rendered, + ); + return lines.join("\n"); + } + let tableLine = -1; + let tableEnd = lines.length; + for (let i = 0; i < lines.length; i++) { + const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); + if (!header) continue; + if (tableLine >= 0) { + tableEnd = i; + break; + } + if (header[1]!.trim() === table) tableLine = i; + } + if (tableLine < 0) { + const prefix = + text.length === 0 || text.endsWith("\n") ? text : `${text}\n`; + return `${prefix}\n[${table}]\n${rendered}\n`; + } + lines.splice(tableEnd, 0, rendered); + return lines.join("\n"); +} + +export function removeTableScalar( + text: string, + table: string, + key: string, +): string { + const existing = findTableScalar(text, table, key); + if (!existing) return text; + const lines = text.split("\n"); + lines.splice(existing.line, 1); + return lines.join("\n"); +} + +/** Insert a raw (already rendered) line inside an exact table, after its last + * scalar. Unlike `setTableScalar` this writes NON-string TOML (booleans, + * arrays, inline tables) — used for `[features] hooks = true`-style switches + * and for array-of-inline-table hook entries. Existing content is untouched; + * when the key is already present the caller decides (replace vs. refuse). */ +export function insertTableRaw( + text: string, + table: string, + rendered: string, +): string { + const lines = text.split("\n"); + let tableLine = -1; + let tableEnd = lines.length; + for (let i = 0; i < lines.length; i++) { + const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); + if (!header) continue; + if (tableLine >= 0) { + tableEnd = i; + break; + } + if (header[1]!.trim() === table) tableLine = i; + } + if (tableLine < 0) { + const prefix = + text.length === 0 || text.endsWith("\n") ? text : `${text}\n`; + return `${prefix}\n[${table}]\n${rendered}\n`; + } + // Land before trailing blank/comment lines so the new scalar stays inside + // the table's own block instead of after a user's separator comment. + let at = tableEnd; + while (at > tableLine + 1) { + const line = lines[at - 1]!.trim(); + if (line !== "" && !line.startsWith("#")) break; + at--; + } + lines.splice(at, 0, rendered); + return lines.join("\n"); +} + +/** Replace an entire table header line and its scalars with `rendered` (which + * must itself include the `[table]` header). Used for hook tables bili owns + * end-to-end; a table with foreign structure is reported, never clobbered. */ +export function replaceTable( + text: string, + table: string, + rendered: string, +): string { + const lines = text.split("\n"); + let start = -1; + let end = lines.length; + for (let i = 0; i < lines.length; i++) { + const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); + if (!header) continue; + if (start >= 0) { + end = i; + break; + } + if (header[1]!.trim() === table) start = i; + } + if (start < 0) return text; + const block = rendered.replace(/\n+$/, "").split("\n"); + lines.splice(start, end - start, ...block); + return lines.join("\n"); +} + +/** Every region of `text` covered by an exact `[table]` or `[[table]]` header + * (until the next header at any level). Lets a caller assert "this table is + * ours" before a rewrite, instead of assuming the shape it expects. + * + * Array-of-tables headers are matched too, and deliberately carry their + * brackets into the reported region: Codex requires `[[hooks.SessionStart]]`, + * and a caller that rewrote or dropped the region while leaving `[hooks...]` + * behind would silently corrupt the array into a map. */ +export function tableRegions(text: string, table: string): string[] { + const lines = text.split("\n"); + const out: string[] = []; + let current: string[] | undefined; + for (const line of lines) { + const header = /^\s*(\[\[?[^\]]+\]\]?)\s*(?:#.*)?$/.exec(line); + if (header) { + if (current !== undefined) out.push(current.join("\n")); + const raw = header[1]; + const inner = raw?.replace(/^\[\[?/, "").replace(/\]\]?$/, "").trim(); + current = inner === table ? [line] : undefined; + continue; + } + if (current !== undefined) current.push(line); + } + if (current !== undefined) out.push(current.join("\n")); + return out.filter((region) => region.trim().startsWith("[")); +} diff --git a/src/codex/bootstrap-hook.ts b/src/codex/bootstrap-hook.ts new file mode 100644 index 0000000000..699905b50e --- /dev/null +++ b/src/codex/bootstrap-hook.ts @@ -0,0 +1,98 @@ +// Codex SessionStart hook (ticket 08): best-effort, attach-only, fails open. +// +// Codex writes one JSON payload (session_id, transcript_path, cwd, hook_event_name) +// to the hook's stdin and waits for it to exit. This hook NEVER spawns a proxy — +// a short-lived parent would kill it — it only (a) confirms an already-running +// bili is reachable at the stable Codex lane origin, and (b) reports the +// session's runtime-info so the proxy can size the window before the first +// model request. Everything is wrapped: a missing proxy, a malformed payload or +// a closed stdin all exit 0, exactly like the kimi/zcode hooks. + +import { resolveProxyOrigin } from "../mcp.js"; +import { reportRuntimeInfo, runSessionStartHook } from "../agent/shared.js"; +import { codexRouteOrigin } from "../codex-integration/route.js"; + +const HOOK_HEALTH_DEADLINE_MS = 4000; + +function readStdinPayload(timeoutMs = 5000): Promise> { + return new Promise((resolve) => { + let buf = ""; + let done = false; + const finish = () => { + if (done) return; + done = true; + clearTimeout(timer); + process.stdin.removeAllListeners(); + try { + resolve(JSON.parse(buf) as Record); + } catch { + resolve({}); + } + }; + const timer = setTimeout(finish, timeoutMs); + process.stdin.setEncoding("utf8"); + process.stdin.on("data", (chunk) => { + buf += chunk; + }); + process.stdin.on("end", finish); + }); +} + +/** Any bili process listening on the Codex lane's sticky port. Attach-only: + * BILI_CODEX_HOOK_ORIGIN overrides the probe target for tests/odd setups. */ +export async function waitForProxyHealthy( + origin: string, + deadlineMs: number, + fetchImpl: typeof fetch = fetch, +): Promise { + const deadline = Date.now() + deadlineMs; + for (;;) { + try { + const response = await fetchImpl( + `${origin.replace(/\/+$/, "")}/__bili/health`, + { + signal: AbortSignal.timeout(1200), + }, + ); + if (response.ok) return true; + } catch { + // not up yet (or not ours) + } + if (Date.now() >= deadline) return false; + await new Promise((resolve) => setTimeout(resolve, 250)); + } +} + +export async function main(): Promise { + if (process.env.NODE_TEST_CONTEXT !== undefined) return; + try { + const payload = await readStdinPayload(); + const origin = + process.env.BILI_CODEX_HOOK_ORIGIN ?? + codexRouteOrigin(process.env) ?? + resolveProxyOrigin(); + if (!(await waitForProxyHealthy(origin, HOOK_HEALTH_DEADLINE_MS))) return; + const model = + typeof payload.model === "string" && payload.model.length > 0 + ? payload.model + : "codex"; + await reportRuntimeInfo(origin, { + agent: "codex", + model, + source: "session-start-hook", + ...(typeof payload.session_id === "string" && + payload.session_id.length > 0 + ? { conversationId: payload.session_id } + : {}), + }); + } catch { + return; + } +} + +if ( + process.argv[1] && + /(?:^|[\\/])bootstrap-hook\.(?:ts|js)$/.test(process.argv[1]) +) { + runSessionStartHook(main); +} diff --git a/src/proxy-service/index.ts b/src/proxy-service/index.ts new file mode 100644 index 0000000000..08e89369c0 --- /dev/null +++ b/src/proxy-service/index.ts @@ -0,0 +1,25 @@ +export { + BILI_TASK_NAME, + planTaskDelete, + planTaskDisable, + planTaskEnable, + planTaskEnd, + planTaskQuery, + planTaskRegister, + planTaskRun, + type ProxyTaskOptions, + type TaskCommand, + type TaskRunner, + type TaskRunnerResult, +} from "./task-scheduler.js"; +export { + disableProxyService, + enableProxyService, + installProxyService, + proxyServiceStatus, + removeProxyService, + restartProxyService, + type ProxyServiceConfig, + type ProxyServiceRecord, + type ProxyServiceResult, +} from "./service.js"; diff --git a/src/proxy-service/service.ts b/src/proxy-service/service.ts new file mode 100644 index 0000000000..0936c1c5a6 --- /dev/null +++ b/src/proxy-service/service.ts @@ -0,0 +1,1102 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { + isPidAlive, + isProxyInstanceFile, + lanePreferredPort, + readProxyInstanceFile, +} from "../instance.js"; +import { stateDir } from "../paths.js"; +import { + BILI_TASK_NAME, + planTaskDelete, + planTaskDisable, + planTaskEnable, + planTaskEnd, + planTaskQuery, + planTaskRegisterXml, + planTaskRun, + renderTaskLauncherVbs, + renderTaskXml, + type TaskCommand, + type TaskRunner, + type TaskRunnerResult, +} from "./task-scheduler.js"; +import { + BILI_SYSTEMD_UNIT, + planDaemonReload, + planSystemdDisable, + planSystemdEnableNow, + planSystemdIsActive, + planSystemdIsEnabled, + planSystemdStart, + planSystemdStop, + renderSystemdUnit, + systemdUnitActive, + systemdUnitEnabled, + systemdUnitMissing, + systemdUserBusUnavailable, +} from "./systemd.js"; + +const SERVICE_STATE_FILE = "proxy-service.json"; + +export interface ProxyServiceConfig { + taskName?: string; + nodePath?: string; + entryPath?: string; + port?: number; + host?: string; + platform?: NodeJS.Platform; + runner?: TaskRunner; + stateDirectory?: string; + /** Absolute path of the systemd user unit (Linux backend). Defaults to + * $XDG_CONFIG_HOME/systemd/user/. */ + unitPath?: string; +} + +export interface ProxyServiceResult { + ok: boolean; + action: + | "installed" + | "already-installed" + | "removed" + | "already-absent" + | "enabled" + | "disabled" + | "restarted" + | "status" + | "unsupported" + | "error"; + message: string; + state?: "ready" | "disabled" | "missing" | "unknown"; + output?: string; +} + +export interface ProxyServiceRecord { + taskName: string; + port: number; + host: string; + entryPath: string; + installedAt: string; +} + +/** Which backend owns the registration on this machine. Recorded so a status + * query never has to guess (and so a Windows record is never mistaken for a + * systemd unit with the same logical name). */ +type ServiceBackend = "schtasks" | "systemd"; + +interface ServiceRecord extends ProxyServiceRecord { + backend: ServiceBackend; + /** systemd only: absolute unit path written by install. */ + unitPath?: string; + /** Shape version of the registration this record describes. Bump whenever + * the GENERATED artifact changes in a way a pre-existing registration must + * adopt (e.g. adding to the Task Scheduler document). Without it + * the path-based idempotency check below would treat a task registered by an + * older bili as "already installed" and never apply the new shape. */ + registrationVersion?: number; +} + +/** Current registration shape. Bump this whenever renderTaskXml / the task + * command / the systemd unit changes in a way existing installs must adopt. + * v2 = hidden Task Scheduler document (no console window). + * v3 = task action goes through wscript.exe + a hidden-mode .vbs launcher; + * v2's alone provably did NOT stop the console window. + * v4 = launcher waits on the proxy (Run(..., 0, True)) so the task keeps + * owning the process and uninstall can actually stop it. */ +const REGISTRATION_VERSION = 4; + +/** Task names are user-visible but not filename-safe; the generated companion + * files (hidden launcher, temporary XML transport) derive their names from it. */ +function safeTaskFileName(taskName: string): string { + return taskName.replace(/[^A-Za-z0-9._-]+/g, "-"); +} + +/** Path of the persistent hidden-mode launcher the task invokes through + * wscript.exe. Lives in the state directory because the task references it at + * every logon and it must outlive the install command. */ +function taskLauncherPath(c: ResolvedConfig): string { + return path.join( + c.stateDirectory, + `${safeTaskFileName(c.taskName)}.launch.vbs`, + ); +} + +/** Legacy records (written before the Linux backend existed) carry no + * `backend`; they are by definition Task Scheduler registrations. */ +function recordBackend(record: ServiceRecord): ServiceBackend { + return record.backend === "systemd" ? "systemd" : "schtasks"; +} + +function defaultRunner(command: TaskCommand): Promise { + return new Promise((resolve, reject) => { + import("node:child_process").then(({ spawn }) => { + const child = spawn(command.file, command.args, { + windowsHide: true, + stdio: ["ignore", "pipe", "pipe"], + }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + child.stdout?.on("data", (chunk: Buffer) => stdout.push(chunk)); + child.stderr?.on("data", (chunk: Buffer) => stderr.push(chunk)); + child.once("error", reject); + child.once("close", (code) => { + const decode = (chunks: Buffer[]): string => + new TextDecoder("gbk").decode(Buffer.concat(chunks)); + resolve({ + exitCode: code ?? 1, + stdout: decode(stdout), + stderr: decode(stderr), + }); + }); + }); + }); +} + +function serviceRecordPath(directory = stateDir()): string { + return path.join(directory, SERVICE_STATE_FILE); +} + +function readRecord(file: string): ServiceRecord | undefined { + try { + const value: unknown = JSON.parse(fs.readFileSync(file, "utf8")); + if (value === null || typeof value !== "object" || Array.isArray(value)) + return undefined; + const row = value as Record; + if ( + typeof row.taskName !== "string" || + typeof row.entryPath !== "string" || + typeof row.host !== "string" || + typeof row.port !== "number" || + typeof row.installedAt !== "string" + ) + return undefined; + return { + taskName: row.taskName, + entryPath: row.entryPath, + host: row.host, + port: row.port, + installedAt: row.installedAt, + backend: row.backend === "systemd" ? "systemd" : "schtasks", + ...(typeof row.unitPath === "string" ? { unitPath: row.unitPath } : {}), + ...(typeof row.registrationVersion === "number" + ? { registrationVersion: row.registrationVersion } + : {}), + }; + } catch { + return undefined; + } +} + +function writeRecord(file: string, record: ServiceRecord): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + const temporary = `${file}.${process.pid}.tmp`; + fs.writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { + mode: 0o600, + }); + fs.renameSync(temporary, file); +} + +function removeRecord(file: string): void { + try { + fs.unlinkSync(file); + } catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) + throw error; + } +} + +function resolveConfig(config: ProxyServiceConfig) { + const taskName = config.taskName ?? BILI_TASK_NAME; + const entryPath = + config.entryPath ?? + process.argv[1] ?? + fileURLToPath(new URL("../index.js", import.meta.url)); + return { + taskName, + nodePath: config.nodePath ?? process.execPath, + entryPath, + port: config.port ?? lanePreferredPort("codex"), + host: config.host ?? "127.0.0.1", + platform: config.platform ?? process.platform, + runner: config.runner ?? defaultRunner, + stateDirectory: config.stateDirectory ?? stateDir(), + unitPath: config.unitPath ?? defaultUnitPath(), + }; +} + +/** $XDG_CONFIG_HOME/systemd/user/, defaulting under ~/.config. Mirrors + * paths.ts's XDG handling without importing its billion-context leaf dirs + * (the unit belongs to systemd's namespace, not ours). */ +function defaultUnitPath(): string { + const base = process.env["XDG_CONFIG_HOME"]?.trim(); + const root = + base !== undefined && base.length > 0 + ? path.resolve(base) + : path.join(os.homedir(), ".config"); + return path.join(root, "systemd", "user", BILI_SYSTEMD_UNIT); +} + +async function invoke( + runner: TaskRunner, + command: TaskCommand, +): Promise { + try { + return await runner(command); + } catch (error) { + return { + exitCode: 1, + stdout: "", + stderr: error instanceof Error ? error.message : String(error), + }; + } +} + +function taskExists(result: TaskRunnerResult): boolean { + return result.exitCode === 0 && /)/i.test(result.stdout); +} + +function taskDisabled(result: TaskRunnerResult): boolean { + return /false<\/Enabled>/i.test(result.stdout); +} + +function taskMissing(result: TaskRunnerResult): boolean { + return ( + result.exitCode !== 0 && + /cannot find|does not exist|not found|ERROR: The system cannot find|系统找不到|找不到指定的文件|不存在/i.test( + `${result.stdout}\n${result.stderr}`, + ) + ); +} + +function hasOwnedTask(file: string, taskName: string): boolean { + const record = readRecord(file); + return ( + record !== undefined && + record.taskName === taskName && + recordBackend(record) === "schtasks" + ); +} + +/** systemd twin of hasOwnedTask: the unit this machine's record claims, and + * only when the record says the systemd backend wrote it. */ +function hasOwnedUnit(file: string, unitPath: string): boolean { + const record = readRecord(file); + return ( + record !== undefined && + recordBackend(record) === "systemd" && + record.unitPath === unitPath + ); +} + +/** A record written by the OTHER backend. Presenting it as ours would let + * `remove` delete a registration the running copy did not create. */ +function hasForeignBackendRecord( + file: string, + backend: ServiceBackend, +): boolean { + const record = readRecord(file); + return record !== undefined && recordBackend(record) !== backend; +} + +function unsupportedPlatform(platform: NodeJS.Platform): ProxyServiceResult { + return { + ok: false, + action: "unsupported", + state: "unknown", + message: `persistent proxy service is not supported on ${platform} (Windows Task Scheduler and Linux systemd user units are)`, + }; +} + +function describeFailure( + action: string, + result: TaskRunnerResult, +): ProxyServiceResult { + const detail = ( + result.stderr || + result.stdout || + `exit code ${result.exitCode}` + ).trim(); + return { ok: false, action: "error", message: `${action} failed: ${detail}` }; +} + +export async function proxyServiceStatus( + config: ProxyServiceConfig = {}, +): Promise { + const c = resolveConfig(config); + if (c.platform === "linux") return statusSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const result = await invoke(c.runner, planTaskQuery(c.taskName)); + if (taskMissing(result)) + return { + ok: true, + action: "status", + state: "missing", + message: "scheduled task is not registered", + }; + if (result.exitCode !== 0) + return describeFailure("query scheduled task", result); + if (!taskExists(result)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML", + }; + if (!hasOwnedTask(serviceRecordPath(c.stateDirectory), c.taskName)) { + return { + ok: true, + action: "status", + state: "unknown", + message: "scheduled task name is occupied by an unowned task", + }; + } + return { + ok: true, + action: "status", + state: taskDisabled(result) ? "disabled" : "ready", + message: taskDisabled(result) + ? "scheduled task is registered but disabled" + : "scheduled task is registered", + output: result.stdout, + }; +} + +export async function installProxyService( + config: ProxyServiceConfig = {}, +): Promise { + const c = resolveConfig(config); + if (c.platform === "linux") return installSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const file = serviceRecordPath(c.stateDirectory); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (query.exitCode !== 0 && !taskMissing(query)) + return describeFailure("query scheduled task", query); + if (query.exitCode === 0 && !taskExists(query)) { + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + } + if (query.exitCode === 0 && taskExists(query)) { + const existing = readRecord(file); + if (existing?.taskName !== c.taskName) { + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + } + if ( + existing.entryPath === c.entryPath && + existing.port === c.port && + existing.host === c.host && + existing.registrationVersion === REGISTRATION_VERSION + ) { + return { + ok: true, + action: "already-installed", + state: taskDisabled(query) ? "disabled" : "ready", + message: + "scheduled task is already registered with the current bili entry", + }; + } + } + const xmlPath = path.join( + c.stateDirectory, + `${safeTaskFileName(c.taskName)}.task.xml`, + ); + // The task action is a .vbs run through wscript.exe, not node.exe directly: + // a console-subsystem binary started by the scheduler in the interactive + // session allocates a conhost window that cannot suppress. The + // launcher PERSISTS (the task references it at every logon) — only the XML + // transport file is temporary. + const launcherPath = taskLauncherPath(c); + let result: TaskRunnerResult; + try { + fs.mkdirSync(c.stateDirectory, { recursive: true }); + fs.writeFileSync( + launcherPath, + Buffer.from(`\ufeff${renderTaskLauncherVbs(c)}`, "utf16le"), + ); + // Task Scheduler requires a UTF-16 document to carry the FF FE byte-order + // mark; Node's "utf16le" encoder writes none, and without it schtasks + // fails with "任务 XML 格式错误 (1,2)::错误: 一个根元素". + const xml = Buffer.from( + `\ufeff${renderTaskXml({ ...c, launcherPath })}`, + "utf16le", + ); + fs.writeFileSync(xmlPath, xml); + result = await invoke(c.runner, planTaskRegisterXml(xmlPath, c.taskName)); + } catch (err) { + return { + ok: false, + action: "error", + state: "unknown", + message: `could not register the scheduled task from its hidden XML document: ${err instanceof Error ? err.message : String(err)}`, + }; + } finally { + fs.rmSync(xmlPath, { force: true }); + } + if (result.exitCode !== 0) + return describeFailure("register scheduled task", result); + writeRecord(file, { + taskName: c.taskName, + entryPath: c.entryPath, + port: c.port, + host: c.host, + installedAt: new Date().toISOString(), + backend: "schtasks", + registrationVersion: REGISTRATION_VERSION, + }); + const verified = await invoke(c.runner, planTaskQuery(c.taskName)); + if (verified.exitCode !== 0 || !taskExists(verified)) { + await invoke(c.runner, planTaskDelete(c.taskName)); + removeRecord(file); + return { + ok: false, + action: "error", + state: "unknown", + message: + "registration command succeeded but scheduled task could not be verified; registration was rolled back", + }; + } + const started = await invoke(c.runner, planTaskRun(c.taskName)); + if (started.exitCode !== 0) { + await invoke(c.runner, planTaskDelete(c.taskName)); + removeRecord(file); + return { + ok: false, + action: "error", + state: "unknown", + message: `scheduled task registered but immediate start failed; registration was rolled back: ${(started.stderr || started.stdout || `exit code ${started.exitCode}`).trim()}`, + }; + } + return { + ok: true, + action: "installed", + state: taskDisabled(verified) ? "disabled" : "ready", + message: + "registered per-user at-logon Task Scheduler task and requested an immediate start", + }; +} + +function readProxyPidOnPort(port: number): number | undefined { + const info = readProxyInstanceFile(); + if (!isProxyInstanceFile(info)) return undefined; + if (info.port !== port || info.pid <= 0) return undefined; + return isPidAlive(info.pid) ? info.pid : undefined; +} + +/** Best-effort stop of a proxy that the scheduler can no longer reach. + * + * `schtasks /End` terminates the task's direct child (our wscript launcher) but + * the node it spawned can survive as a reparented orphan still holding the + * port — uninstall would then report success while traffic keeps being + * compressed by a process with no task handle left. The proxy publishes its own + * pid in the instance file, so reap that pid when it is still alive and is the + * one owning the port we registered. Never throws: a failure here must not turn + * a successful uninstall into an error. */ +function reapOrphanProxy(port: number): boolean { + let killed = false; + const pid = readProxyPidOnPort(port); + if (pid !== undefined) { + try { + process.kill(pid); + killed = true; + } catch { + // The process exited between the liveness check and the signal, or we + // lack permission; either way removal proceeds without it. + } + } + return killed; +} + +export async function removeProxyService( + config: ProxyServiceConfig = {}, +): Promise { + const c = resolveConfig(config); + if (c.platform === "linux") return removeSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const file = serviceRecordPath(c.stateDirectory); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (query.exitCode !== 0 && !taskMissing(query)) + return describeFailure("query scheduled task", query); + if (query.exitCode === 0 && !taskExists(query)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + if ( + query.exitCode === 0 && + taskExists(query) && + !hasOwnedTask(file, c.taskName) + ) { + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + } + // Stop the live instance BEFORE deleting the task: the task is the only + // handle on that process, so removing it first would orphan a running proxy + // that keeps listening (and keeps compressing traffic) with no way to stop it + // except by hand. A "not running" answer is the normal already-stopped case. + const end = await invoke(c.runner, planTaskEnd(c.taskName)); + if ( + end.exitCode !== 0 && + !/not running|not currently running/i.test(`${end.stdout}\n${end.stderr}`) + ) + return describeFailure("stop scheduled task instance", end); + const result = await invoke(c.runner, planTaskDelete(c.taskName)); + if (result.exitCode !== 0 && !taskMissing(result)) + return describeFailure("remove scheduled task", result); + // /End killed our launcher but the node it spawned may have survived as an + // orphan still holding the port; reap it so "removed" means removed. + reapOrphanProxy(c.port); + // The hidden launcher is only referenced by the task we just deleted; a + // leftover .vbs would otherwise survive uninstall and keep pointing at a + // dist/ tree the user may have removed. + fs.rmSync(taskLauncherPath(c), { force: true }); + removeRecord(file); + return { + ok: true, + action: result.exitCode === 0 ? "removed" : "already-absent", + state: "missing", + message: + result.exitCode === 0 + ? "scheduled task removed" + : "scheduled task was already absent", + }; +} + +export async function disableProxyService( + config: ProxyServiceConfig = {}, +): Promise { + const c = resolveConfig(config); + if (c.platform === "linux") return disableSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const file = serviceRecordPath(c.stateDirectory); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (taskMissing(query)) + return { + ok: false, + action: "error", + state: "missing", + message: "scheduled task is not registered; install it first", + }; + if (query.exitCode !== 0) + return describeFailure("query scheduled task", query); + if (!taskExists(query)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + if (!hasOwnedTask(file, c.taskName)) + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + const result = await invoke(c.runner, planTaskDisable(c.taskName)); + if ( + result.exitCode !== 0 && + !/already disabled/i.test(`${result.stdout}\n${result.stderr}`) + ) + return describeFailure("disable scheduled task", result); + return { + ok: true, + action: "disabled", + state: "disabled", + message: "scheduled task disabled", + }; +} + +export async function restartProxyService( + config: ProxyServiceConfig = {}, +): Promise { + const c = resolveConfig(config); + if (c.platform === "linux") return restartSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (taskMissing(query)) + return { + ok: false, + action: "error", + state: "missing", + message: "scheduled task is not registered; install it first", + }; + if (query.exitCode !== 0) + return describeFailure("query scheduled task", query); + if (!taskExists(query)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + if (!hasOwnedTask(serviceRecordPath(c.stateDirectory), c.taskName)) + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + const end = await invoke(c.runner, planTaskEnd(c.taskName)); + if ( + end.exitCode !== 0 && + !/not running|not currently running/i.test(`${end.stdout}\n${end.stderr}`) + ) + return describeFailure("stop scheduled task instance", end); + const run = await invoke(c.runner, planTaskRun(c.taskName)); + if (run.exitCode !== 0) return describeFailure("start scheduled task", run); + return { + ok: true, + action: "restarted", + state: "ready", + message: "scheduled task restart requested", + }; +} + +export async function enableProxyService( + config: ProxyServiceConfig = {}, +): Promise { + const c = resolveConfig(config); + if (c.platform === "linux") return enableSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const file = serviceRecordPath(c.stateDirectory); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (taskMissing(query)) + return { + ok: false, + action: "error", + state: "missing", + message: "scheduled task is not registered; install it first", + }; + if (query.exitCode !== 0) + return describeFailure("query scheduled task", query); + if (!taskExists(query)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + if (!hasOwnedTask(file, c.taskName)) + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + const result = await invoke(c.runner, planTaskEnable(c.taskName)); + if (result.exitCode !== 0) + return describeFailure("enable scheduled task", result); + return { + ok: true, + action: "enabled", + state: "ready", + message: "scheduled task enabled", + }; +} + +// --------------------------------------------------------------------------- +// Linux backend: per-user systemd unit (~/.config/systemd/user/bili-proxy.service). +// Same ownership discipline as the Windows half — the record file decides whose +// registration this is, and every mutating step verifies itself and rolls back +// on failure, so a half-written unit never survives an install that errored. +// --------------------------------------------------------------------------- + +type ResolvedConfig = ReturnType; + +function systemdResult( + result: TaskRunnerResult, + action: string, +): ProxyServiceResult { + return describeFailure(action, result); +} + +/** Bus reachability preflight shared by every mutating systemd path. Returns a + * failure result when `systemctl --user` cannot talk to a user manager, else + * undefined. Writing a unit into a machine whose user manager will never load + * it is the failure mode this prevents. */ +async function requireSystemdBus( + c: ResolvedConfig, +): Promise { + const probe = await invoke( + c.runner, + planSystemdIsEnabled({ unitName: c.taskName, unitPath: c.unitPath }), + ); + if (systemdUserBusUnavailable(probe)) + return { + ok: false, + action: "error", + state: "unknown", + message: + "systemctl --user cannot reach a user manager (no systemd user bus in this session) — run `loginctl enable-linger $USER` on a systemd host, or start the proxy with `bili start` instead", + }; + return undefined; +} + +async function statusSystemd(c: ResolvedConfig): Promise { + const probe = await invoke( + c.runner, + planSystemdIsEnabled({ unitName: c.taskName }), + ); + if (systemdUserBusUnavailable(probe)) + return { + ok: false, + action: "unsupported", + state: "unknown", + message: + "systemctl --user cannot reach a user manager (no systemd user bus in this session)", + }; + const unitName = c.taskName; + const enabled = await querySystemdEnabled(c); + if (enabled === undefined) + return { + ok: true, + action: "status", + state: "missing", + message: "systemd user unit is not registered", + }; + if (!hasOwnedUnit(serviceRecordPath(c.stateDirectory), c.unitPath)) + return { + ok: true, + action: "status", + state: "unknown", + message: "systemd user unit is not owned by this bili copy", + }; + const active = await invoke(c.runner, planSystemdIsActive({ unitName })); + return { + ok: true, + action: "status", + state: enabled + ? systemdUnitActive(active) + ? "ready" + : "disabled" + : "disabled", + message: enabled + ? systemdUnitActive(active) + ? "systemd user unit is enabled and active" + : "systemd user unit is enabled but not running" + : "systemd user unit is registered but disabled", + output: active.stdout, + }; +} + +/** Renders the unit, wires it into systemd and starts it immediately. */ +async function installSystemd(c: ResolvedConfig): Promise { + const bus = await requireSystemdBus(c); + if (bus !== undefined) return bus; + const file = serviceRecordPath(c.stateDirectory); + if (hasForeignBackendRecord(file, "systemd")) + return { + ok: false, + action: "error", + state: "unknown", + message: + "a Task Scheduler registration is recorded for this copy; remove it with `bili service remove` before installing the systemd unit", + }; + const existing = await querySystemdEnabled(c); + // Ownership is decided against what systemd ACTUALLY knows, not against the + // record alone: a unit file left behind by another copy (or by a hand edit) + // while our record is missing must still be seen as foreign, or install + // would silently overwrite someone else's unit. + const unitOnDisk = fs.existsSync(c.unitPath); + if ( + (existing !== undefined || unitOnDisk) && + !hasOwnedUnit(file, c.unitPath) + ) { + return { + ok: false, + action: "error", + state: "unknown", + message: `systemd user unit ${c.taskName} already exists and is not owned by this bili copy; left untouched`, + }; + } + const previous = readRecord(file); + const record = readRecord(file); + if ( + existing !== undefined && + record !== undefined && + recordBackend(record) === "systemd" && + record.entryPath === c.entryPath && + record.port === c.port && + record.host === c.host && + record.registrationVersion === REGISTRATION_VERSION + ) { + return { + ok: true, + action: "already-installed", + state: "ready", + message: + "systemd user unit is already registered with the current bili entry", + }; + } + return writeAndEnableSystemd(c, file, previous); +} + +/** Write the unit, reload systemd, enable-and-start it, then verify it is + * actually active. Every failure path restores the previous unit text (or + * deletes the file we created) and the previous record, so an install that + * reports an error leaves the machine exactly as it found it. */ +async function writeAndEnableSystemd( + c: ResolvedConfig, + file: string, + previous: ServiceRecord | undefined, +): Promise { + let priorText: string | undefined; + try { + priorText = fs.readFileSync(c.unitPath, "utf8"); + } catch {} + try { + fs.mkdirSync(path.dirname(c.unitPath), { recursive: true }); + fs.writeFileSync( + c.unitPath, + renderSystemdUnit({ + nodePath: c.nodePath, + entryPath: c.entryPath, + port: c.port, + host: c.host, + unitPath: c.unitPath, + }), + ); + } catch (error) { + return { + ok: false, + action: "error", + state: "unknown", + message: `could not write ${c.unitPath}: ${error instanceof Error ? error.message : String(error)}`, + }; + } + const reload = await invoke(c.runner, planDaemonReload()); + if (reload.exitCode !== 0) { + restoreUnit(c.unitPath, priorText); + return systemdResult(reload, "reload systemd user manager"); + } + const enable = await invoke( + c.runner, + planSystemdEnableNow({ unitName: c.taskName }), + ); + if (enable.exitCode !== 0) { + restoreUnit(c.unitPath, priorText); + await invoke(c.runner, planDaemonReload()); + return systemdResult(enable, "enable systemd user unit"); + } + writeRecord(file, { + taskName: c.taskName, + entryPath: c.entryPath, + port: c.port, + host: c.host, + installedAt: new Date().toISOString(), + backend: "systemd", + unitPath: c.unitPath, + registrationVersion: REGISTRATION_VERSION, + }); + const verifiedActive = await invoke( + c.runner, + planSystemdIsActive({ unitName: c.taskName }), + ); + if (!systemdUnitActive(verifiedActive)) { + await invoke(c.runner, planSystemdDisable({ unitName: c.taskName })); + restoreUnit(c.unitPath, priorText); + await invoke(c.runner, planDaemonReload()); + if (previous !== undefined) writeRecord(file, previous); + else removeRecord(file); + return { + ok: false, + action: "error", + state: "unknown", + message: `systemd user unit enabled but did not become active; registration was rolled back (${(verifiedActive.stderr || verifiedActive.stdout || `exit code ${verifiedActive.exitCode}`).trim()})`, + }; + } + return { + ok: true, + action: "installed", + state: "ready", + message: + "wrote per-user systemd unit, enabled it at logon and started it immediately", + }; +} + +/** Put back what was on disk before us, or remove the file we created. */ +function restoreUnit(unitPath: string, priorText: string | undefined): void { + try { + if (priorText === undefined) fs.unlinkSync(unitPath); + else fs.writeFileSync(unitPath, priorText); + } catch {} +} + +/** Ask systemd whether the unit is enabled. `undefined` means systemd does not + * know this unit at all — distinct from "known but disabled", so callers can + * tell "nothing installed" from "installed, turned off". */ +async function querySystemdEnabled( + c: ResolvedConfig, +): Promise { + const result = await invoke( + c.runner, + planSystemdIsEnabled({ unitName: c.taskName }), + ); + if (systemdUnitMissing(result)) return undefined; + return systemdUnitEnabled(result); +} + +async function removeSystemd(c: ResolvedConfig): Promise { + const file = serviceRecordPath(c.stateDirectory); + if (hasForeignBackendRecord(file, "systemd")) + return { + ok: false, + action: "error", + state: "unknown", + message: + "a Task Scheduler registration is recorded for this copy, not a systemd unit; left untouched", + }; + if (!hasOwnedUnit(file, c.unitPath)) { + return { + ok: true, + action: "already-absent", + state: "missing", + message: "no systemd user unit is registered for this bili copy", + }; + } + const disable = await invoke( + c.runner, + planSystemdDisable({ unitName: c.taskName }), + ); + if (disable.exitCode !== 0 && !systemdUnitMissing(disable)) + return systemdResult(disable, "disable systemd user unit"); + const stop = await invoke( + c.runner, + planSystemdStop({ unitName: c.taskName }), + ); + if (stop.exitCode !== 0 && !systemdUnitMissing(stop)) + return systemdResult(stop, "stop systemd user unit"); + try { + fs.unlinkSync(c.unitPath); + } catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) + return { + ok: false, + action: "error", + state: "unknown", + message: `could not delete ${c.unitPath}: ${error instanceof Error ? error.message : String(error)}`, + }; + } + await invoke(c.runner, planDaemonReload()); + removeRecord(file); + return { + ok: true, + action: "removed", + state: "missing", + message: "systemd user unit disabled, stopped and deleted", + }; +} + +async function disableSystemd(c: ResolvedConfig): Promise { + if ((await querySystemdEnabled(c)) === undefined) + return { + ok: false, + action: "error", + state: "missing", + message: + "no systemd user unit is registered for this bili copy; install it first", + }; + const result = await invoke( + c.runner, + planSystemdDisable({ unitName: c.taskName }), + ); + if ( + result.exitCode !== 0 && + !/not enabled|already disabled/i.test(`${result.stdout}\n${result.stderr}`) + ) + return systemdResult(result, "disable systemd user unit"); + const stop = await invoke( + c.runner, + planSystemdStop({ unitName: c.taskName }), + ); + if ( + stop.exitCode !== 0 && + !systemdUnitMissing(stop) && + !/not running/i.test(`${stop.stdout}\n${stop.stderr}`) + ) + return systemdResult(stop, "stop systemd user unit"); + return { + ok: true, + action: "disabled", + state: "disabled", + message: "systemd user unit disabled and stopped", + }; +} + +async function enableSystemd(c: ResolvedConfig): Promise { + if ((await querySystemdEnabled(c)) === undefined) + return { + ok: false, + action: "error", + state: "missing", + message: + "no systemd user unit is registered for this bili copy; install it first", + }; + const result = await invoke( + c.runner, + planSystemdEnableNow({ unitName: c.taskName }), + ); + if (result.exitCode !== 0) + return systemdResult(result, "enable systemd user unit"); + return { + ok: true, + action: "enabled", + state: "ready", + message: "systemd user unit enabled and started", + }; +} + +async function restartSystemd(c: ResolvedConfig): Promise { + if ((await querySystemdEnabled(c)) === undefined) + return { + ok: false, + action: "error", + state: "missing", + message: + "no systemd user unit is registered for this bili copy; install it first", + }; + const stop = await invoke( + c.runner, + planSystemdStop({ unitName: c.taskName }), + ); + if ( + stop.exitCode !== 0 && + !/not running/i.test(`${stop.stdout}\n${stop.stderr}`) && + !systemdUnitMissing(stop) + ) + return systemdResult(stop, "stop systemd user unit"); + const start = await invoke( + c.runner, + planSystemdStart({ unitName: c.taskName }), + ); + if (start.exitCode !== 0) + return systemdResult(start, "start systemd user unit"); + return { + ok: true, + action: "restarted", + state: "ready", + message: "systemd user unit restart requested", + }; +} diff --git a/src/proxy-service/systemd.ts b/src/proxy-service/systemd.ts new file mode 100644 index 0000000000..908c815b3d --- /dev/null +++ b/src/proxy-service/systemd.ts @@ -0,0 +1,218 @@ +// #ticket-linux-service: per-user systemd backend for the persistent proxy +// service (the Linux twin of task-scheduler.ts's per-user ONLOGON task). +// +// Shape mirrors the Windows backend deliberately: a PURE planner emitting +// absolute `systemctl` argv, so every branch is testable without a live bus, +// and the caller (service.ts) keeps ownership checks, rollback and status +// reporting in ONE place. Unit lives in the XDG user unit dir +// (~/.config/systemd/user) — no root, no /etc, and the same per-user +// "start at logon" semantics as the Task Scheduler task. +// +// NOT called `systemd` — the file is imported by src/proxy-service/service.ts +// and kept dependency-free (node:path only), like its Windows sibling. + +import path from "node:path"; + +/** Unit basename. Fixed, like BILI_TASK_NAME: one service per machine. */ +export const BILI_SYSTEMD_UNIT = "bili-proxy.service"; + +export interface SystemdUnitOptions { + nodePath: string; + entryPath: string; + port: number; + host?: string; + /** Absolute path of the unit file. */ + unitPath: string; +} + +function checkedOptions( + options: SystemdUnitOptions, +): Required { + if ( + !Number.isInteger(options.port) || + options.port < 1 || + options.port > 65535 + ) { + throw new RangeError( + "proxy service port must be an integer from 1 to 65535", + ); + } + if ( + !path.isAbsolute(options.nodePath) || + !path.isAbsolute(options.entryPath) || + !path.isAbsolute(options.unitPath) + ) { + throw new TypeError( + "proxy service executable, entry and unit paths must be absolute", + ); + } + return { + nodePath: options.nodePath, + entryPath: options.entryPath, + port: options.port, + host: options.host ?? "127.0.0.1", + unitPath: options.unitPath, + }; +} + +/** systemd ExecStart quoting: each argv element is quoted, with `"` and `\` + * backslash-escaped (systemd.syntax(7): double quotes keep a value as ONE + * argument; the shell only sees the unquoted result). */ +function quoteArg(value: string): string { + return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; +} + +/** The unit file bili owns. Restart=on-failure keeps the proxy alive across a + * crash without a supervisor of its own; --no-auto-update matches the Windows + * task (an auto-updating service would restart itself under systemd's feet). */ +export function renderSystemdUnit(options: SystemdUnitOptions): string { + const o = checkedOptions(options); + const exec = [ + quoteArg(o.nodePath), + quoteArg(o.entryPath), + "start", + "--host", + quoteArg(o.host), + "--port", + String(o.port), + "--no-auto-update", + ].join(" "); + return [ + "[Unit]", + "Description=Billion Context proxy (bili)", + "Documentation=https://github.com/ranxianglei/billion-context", + "After=network-online.target", + "", + "[Service]", + "Type=simple", + `ExecStart=${exec}`, + "Restart=on-failure", + "RestartSec=5", + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"); +} + +export interface SystemdCommand { + file: string; + args: string[]; +} + +export interface SystemdQueryOptions { + unitName?: string; + unitPath?: string; +} + +function unitNameOf(options: SystemdQueryOptions): string { + return options.unitName ?? BILI_SYSTEMD_UNIT; +} + +export function planSystemctl( + args: string[], + options: SystemdQueryOptions = {}, +): SystemdCommand { + return { + file: "systemctl", + args: ["--user", ...args, unitNameOf(options)], + }; +} + +export function planDaemonReload(): SystemdCommand { + return { file: "systemctl", args: ["--user", "daemon-reload"] }; +} + +export function planSystemdEnable( + options: SystemdQueryOptions = {}, +): SystemdCommand { + return planSystemctl(["enable"], options); +} + +export function planSystemdStart( + options: SystemdQueryOptions = {}, +): SystemdCommand { + return planSystemctl(["start"], options); +} + +export function planSystemdStop( + options: SystemdQueryOptions = {}, +): SystemdCommand { + return planSystemctl(["stop"], options); +} + +export function planSystemdDisable( + options: SystemdQueryOptions = {}, +): SystemdCommand { + return planSystemctl(["disable"], options); +} + +export function planSystemdEnableNow( + options: SystemdQueryOptions = {}, +): SystemdCommand { + return planSystemctl(["enable", "--now"], options); +} + +/** `systemctl --user is-enabled `: exit 0 with "enabled"/"enabled-runtime" + * ... on stdout when the [Install] section is wired up. */ +export function planSystemdIsEnabled( + options: SystemdQueryOptions = {}, +): SystemdCommand { + return planSystemctl(["is-enabled"], options); +} + +/** `systemctl --user is-active `: exit 0 with "active" when running. */ +export function planSystemdIsActive( + options: SystemdQueryOptions = {}, +): SystemdCommand { + return planSystemctl(["is-active"], options); +} + +/** True when `systemctl --user` can actually reach a user bus. A bare SSH + * session or a container often has systemd installed but no user manager for + * this login, where every systemctl --user call fails with + * "Failed to connect to bus"; the caller degrades to a clear message instead + * of writing a unit nothing will ever load. */ +export function systemdUserBusUnavailable(result: { + exitCode: number; + stdout: string; + stderr: string; +}): boolean { + if (result.exitCode === 0) return false; + return /failed to connect to bus|no medium found|systemd.*not been booted|connection refused/i.test( + `${result.stdout}\n${result.stderr}`, + ); +} + +/** `systemctl is-enabled` verdicts that mean the unit is NOT wired to start. */ +export function systemdUnitEnabled(result: { + exitCode: number; + stdout: string; + stderr: string; +}): boolean { + if (result.exitCode !== 0) return false; + return /^\s*enabled(-runtime)?\s*$/m.test(result.stdout); +} + +export function systemdUnitActive(result: { + exitCode: number; + stdout: string; + stderr: string; +}): boolean { + if (result.exitCode !== 0) return false; + return /^\s*active\s*$/m.test(result.stdout); +} + +/** Exit-code/liveness text from `systemctl` that means "no such unit" — the + * Linux twin of task-scheduler's taskMissing. */ +export function systemdUnitMissing(result: { + exitCode: number; + stdout: string; + stderr: string; +}): boolean { + const text = `${result.stdout}\n${result.stderr}`; + if (/^\s*(inactive|unknown|not-found)\s*$/m.test(result.stdout)) return true; + return /could not be found|not loaded|no such unit|does not exist/i.test( + text, + ); +} diff --git a/src/proxy-service/task-scheduler.ts b/src/proxy-service/task-scheduler.ts new file mode 100644 index 0000000000..672a3e662e --- /dev/null +++ b/src/proxy-service/task-scheduler.ts @@ -0,0 +1,226 @@ +import path from "node:path"; + +export const BILI_TASK_NAME = "Billion Context Proxy"; + +export interface TaskCommand { + file: string; + args: string[]; +} + +export interface ProxyTaskOptions { + taskName?: string; + nodePath: string; + entryPath: string; + port: number; + host?: string; + /** Absolute path of the generated .vbs launcher the task executes through + * wscript.exe. Required for the hidden registration; `planTaskRegister` + * (the flag form) ignores it. */ + launcherPath?: string; +} + +function checkedOptions(options: ProxyTaskOptions): Required { + if ( + !Number.isInteger(options.port) || + options.port < 1 || + options.port > 65535 + ) { + throw new RangeError( + "proxy service port must be an integer from 1 to 65535", + ); + } + if ( + !path.isAbsolute(options.nodePath) || + !path.isAbsolute(options.entryPath) + ) { + throw new TypeError( + "proxy service executable and entry paths must be absolute", + ); + } + return { + taskName: options.taskName ?? BILI_TASK_NAME, + nodePath: options.nodePath, + entryPath: options.entryPath, + port: options.port, + host: options.host ?? "127.0.0.1", + launcherPath: options.launcherPath ?? "", + }; +} + +/** Build a per-user, at-logon Task Scheduler registration. Paths remain + * separate argv values for the runner; only schtasks' /TR payload is composed + * into a Windows command line, with each executable/path quoted. + * + * Prefer planTaskRegisterXml: this flag form cannot express , and an + * unhidden at-logon task runs the proxy WITH a console window in the user's + * session (#silent-backend). Kept for runners/tests that assert the old shape. */ +export function planTaskRegister(options: ProxyTaskOptions): TaskCommand { + const o = checkedOptions(options); + const run = `"${o.nodePath}" "${o.entryPath}" start --host "${o.host}" --port ${o.port} --no-auto-update`; + return { + file: "schtasks.exe", + args: [ + "/Create", + "/TN", + o.taskName, + "/SC", + "ONLOGON", + "/RL", + "LIMITED", + "/TR", + run, + "/F", + ], + }; +} + +function xmlEscape(value: string): string { + return value + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +/** The registration document for the at-logon proxy task. + * + * true is the load-bearing setting: without it Task Scheduler + * launches the proxy in the interactive session with a console window, and the + * child's own windowsHide cannot suppress a console the SCHEDULER created. + * InteractiveToken keeps the run per-user and + * non-elevated (equivalent to the flag form's ONLOGON + /RL LIMITED). + * MultipleInstancesPolicy=IgnoreNew makes a duplicate logon a no-op instead of + * a second proxy racing for the same port. */ +export function renderTaskXml(options: ProxyTaskOptions): string { + const o = checkedOptions(options); + if (o.launcherPath.length === 0) + throw new TypeError( + "hidden task registration requires an absolute launcher path (the generated .vbs the task runs through wscript.exe)", + ); + const author = process.env.USERNAME ?? process.env.USER ?? ""; + return [ + '', + '', + " ", + ` ${xmlEscape(author)}`, + " Billion Context compression proxy (per-user, at logon).", + " ", + " ", + " ", + " true", + " ", + " ", + " ", + ' ', + ` ${xmlEscape(author)}`, + " InteractiveToken", + " LeastPrivilege", + " ", + " ", + " ", + " IgnoreNew", + " false", + " false", + " true", + " true", + " false", + " ", + " false", + " false", + " ", + " true", + " true", + " true", + " false", + " false", + " PT0S", + " 7", + " ", + ' ', + " ", + ` wscript.exe`, + ` ${xmlEscape(`//B //Nologo "${o.launcherPath}"`)}`, + " ", + " ", + "", + "", + ].join("\r\n"); +} + +/** Windows Script Host launcher used as the task action. + * + * A console-subsystem binary (node.exe) started by the Task Scheduler in the + * interactive session allocates a conhost window, and does NOT + * suppress it: only keeps the task out of the Task Scheduler UI. WSH's + * Run(cmd, 0, ...) launches with hidden window style, and wscript.exe is a + * GUI-subsystem binary, so no console is ever created for this chain. + * + * The third argument is True (WAIT) on purpose. With False, wscript exits + * immediately and node is REPARENTED away from the task, so `schtasks /End` can + * no longer reach it — uninstall then leaves an orphan proxy holding the port + * forever. Waiting keeps wscript alive as the task's own process with node as + * its child, so the whole tree stays inside the task's job object and `/End` + * terminates it (verified: node's window stays 0 in both modes, but only WAIT + * keeps the process reachable). */ +export function renderTaskLauncherVbs(options: ProxyTaskOptions): string { + const o = checkedOptions(options); + const command = `"${o.nodePath}" "${o.entryPath}" start --host "${o.host}" --port ${o.port} --no-auto-update`; + return [ + "' bili: launch the compression proxy with no console window.", + "Dim sh, cmd", + `cmd = "${command.replace(/"/g, '""')}"`, + 'Set sh = CreateObject("WScript.Shell")', + "' 0 = hidden window, True = wait so the task keeps owning the proxy", + "sh.Run cmd, 0, True", + "", + ].join("\r\n"); +} + +/** Register from the hidden document: schtasks reads the XML at a file path. */ +export function planTaskRegisterXml( + xmlPath: string, + taskName = BILI_TASK_NAME, +): TaskCommand { + return { + file: "schtasks.exe", + args: ["/Create", "/TN", taskName, "/XML", xmlPath, "/F"], + }; +} + +export function planTaskQuery(taskName = BILI_TASK_NAME): TaskCommand { + return { file: "schtasks.exe", args: ["/Query", "/TN", taskName, "/XML"] }; +} + +export function planTaskRun(taskName = BILI_TASK_NAME): TaskCommand { + return { file: "schtasks.exe", args: ["/Run", "/TN", taskName] }; +} + +export function planTaskEnd(taskName = BILI_TASK_NAME): TaskCommand { + return { file: "schtasks.exe", args: ["/End", "/TN", taskName] }; +} + +export function planTaskDisable(taskName = BILI_TASK_NAME): TaskCommand { + return { + file: "schtasks.exe", + args: ["/Change", "/TN", taskName, "/DISABLE"], + }; +} + +export function planTaskEnable(taskName = BILI_TASK_NAME): TaskCommand { + return { + file: "schtasks.exe", + args: ["/Change", "/TN", taskName, "/ENABLE"], + }; +} + +export function planTaskDelete(taskName = BILI_TASK_NAME): TaskCommand { + return { file: "schtasks.exe", args: ["/Delete", "/TN", taskName, "/F"] }; +} + +export interface TaskRunnerResult { + exitCode: number; + stdout: string; + stderr: string; +} + +export type TaskRunner = (command: TaskCommand) => Promise; diff --git a/tests/codex-cc-switch.test.ts b/tests/codex-cc-switch.test.ts new file mode 100644 index 0000000000..5841fd4b46 --- /dev/null +++ b/tests/codex-cc-switch.test.ts @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + detectCcSwitchFromText, + isProxyManagedCredential, +} from "../src/codex-integration/cc-switch.ts"; +import { credentialFingerprint } from "../src/cache-ledger.ts"; + +test("CC Switch Direct and Routing fixtures are detected without claiming compatibility", () => { + const direct = detectCcSwitchFromText('{"codex":{"mode":"direct"}}'); + assert.equal(direct.discovered, true); + assert.equal(direct.mode, "direct"); + assert.equal(direct.compatibility, "config-route-only"); + assert.match(direct.detail, /provider-database synchronization is not integrated/); + const routing = detectCcSwitchFromText(undefined, '{"proxyMode":"routing"}'); + assert.equal(routing.mode, "routing"); + assert.equal(routing.compatibility, "unsupported"); + const unknown = detectCcSwitchFromText("{}", undefined); + assert.equal(unknown.discovered, true); + assert.equal(unknown.mode, "unknown"); + assert.equal(detectCcSwitchFromText().discovered, false); +}); + +test("CC Switch live-state apps.codex.mode schema is recognized", () => { + const result = detectCcSwitchFromText(undefined, '{"version":1,"apps":{"codex":{"mode":"direct"}}}'); + assert.equal(result.discovered, true); + assert.equal(result.mode, "direct"); + assert.equal(result.compatibility, "config-route-only"); +}); + + +test("PROXY_MANAGED is not persisted as a credential fingerprint", () => { + assert.equal(isProxyManagedCredential("Bearer PROXY_MANAGED"), true); + assert.equal( + credentialFingerprint({ authorization: "Bearer PROXY_MANAGED" }), + undefined, + ); + assert.equal( + credentialFingerprint({ + authorization: "Bearer sk-live-example", + })?.startsWith("sha256:"), + true, + ); +}); diff --git a/tests/codex-chatgpt-capability.test.ts b/tests/codex-chatgpt-capability.test.ts new file mode 100644 index 0000000000..afa3fa36de --- /dev/null +++ b/tests/codex-chatgpt-capability.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import test from "node:test"; +import { chatGptDesktopCapability } from "../src/codex-integration/chatgpt-capability.ts"; + +test("ChatGPT subscription and Desktop remain explicitly unsupported without credential access", () => { + assert.deepEqual(chatGptDesktopCapability, { + state: "待完成/可实现", + credentials: "not-read-not-persisted", + officialLoginChannels: "preserved", + desktopMcp: "separate-from-model-routing", + }); + const source = fs.readFileSync( + new URL("../src/codex-integration/chatgpt-capability.ts", import.meta.url), + "utf8", + ); + assert.doesNotMatch(source, /readFileSync|writeFileSync/); +}); diff --git a/tests/codex-hooks-skill.test.ts b/tests/codex-hooks-skill.test.ts new file mode 100644 index 0000000000..3970202591 --- /dev/null +++ b/tests/codex-hooks-skill.test.ts @@ -0,0 +1,378 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { + assertCodexConfigLoads, + codexHookTable, + codexHooksEnabledNote, + codexHooksFeature, + findBiliCodexHook, + isBiliCodexHookCommand, + planCodexHook, + readCodexHookCommands, + stripCodexHook, +} from "../src/codex-integration/hooks.ts"; +import { + CODEX_SKILL_MARKDOWN, + codexSkillDir, + codexSkillFile, + codexSkillStatus, + installCodexSkill, + readSkillName, + removeCodexSkill, +} from "../src/codex-integration/skill.ts"; +import { + insertTableRaw, + tableRegions, +} from "../src/codex-integration/toml-field.ts"; + +const hookCommand = 'node "C:/bili/dist/codex/bootstrap-hook.js"'; + +function tempHome(): { env: NodeJS.ProcessEnv; dir: string } { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-skill-")); + return { env: { ...process.env, CODEX_HOME: dir }, dir }; +} + +test("hook command matching recognizes our script across install roots", () => { + assert.equal(isBiliCodexHookCommand(hookCommand), true); + assert.equal( + isBiliCodexHookCommand( + 'node "C:/Users/x/AppData/Roaming/npm/node_modules/billion-context/dist/codex/bootstrap-hook.js"', + ), + true, + ); + assert.equal( + isBiliCodexHookCommand("lean-ctx.exe hook codex-session-start"), + false, + ); + assert.equal( + isBiliCodexHookCommand('node "C:/other/dist/claude-native-bootstrap.js"'), + false, + ); +}); + +test("hook install keeps user tables byte-for-byte and is idempotent", () => { + const original = 'model = "gpt-5"\n\n[features]\nhooks = true\n'; + const first = planCodexHook(original, hookCommand); + assert.equal(first.action, "install"); + assert.match(first.text, /\[\[hooks\.SessionStart\]\]/); + assert.match(first.text, /\[features\]\nhooks = true/); + assert.equal(findBiliCodexHook(first.text), hookCommand); + assert.equal(codexHooksEnabledNote(first.text), ""); + + const again = planCodexHook(first.text, hookCommand); + assert.equal(again.action, "keep"); + assert.equal(again.text, first.text); + + const moved = planCodexHook( + first.text, + 'node "D:/new/dist/codex/bootstrap-hook.js"', + ); + assert.equal(moved.action, "refresh"); + assert.equal( + findBiliCodexHook(moved.text), + 'node "D:/new/dist/codex/bootstrap-hook.js"', + ); +}); + +test("a foreign SessionStart entry is preserved and ours is appended", () => { + // `[[hooks.SessionStart]]` is an array: a foreign entry is a SIBLING, so + // bili adds its own instead of giving up. This is the real-machine case + // (lean-ctx already owns a SessionStart entry). + const foreign = `model = "gpt-5"\n\n[[hooks.SessionStart]]\nmatcher = "startup|resume|clear"\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\n`; + const plan = planCodexHook(foreign, hookCommand); + assert.equal(plan.action, "install"); + assert.match(plan.text, /lean-ctx\.exe hook codex-session-start/); + assert.equal(findBiliCodexHook(plan.text), hookCommand); + // Both entries survive as SEPARATE array-of-tables entries. + assert.equal(plan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 2); + assert.equal(assertCodexConfigLoads(plan.text), undefined); + + // Re-running is a no-op, and removal takes back only ours. + const again = planCodexHook(plan.text, hookCommand); + assert.equal(again.action, "keep"); + const stripped = stripCodexHook(plan.text); + assert.equal(stripped.removed, true); + assert.match(stripped.text, /lean-ctx\.exe hook codex-session-start/); + assert.doesNotMatch(stripped.text, /bootstrap-hook\.js/); +}); + +test("our entry is always the nested MatcherGroup shape Codex registers", () => { + // THE regression the user hit. Codex deserializes each entry as a + // `MatcherGroup` = `{ matcher?, hooks = [ {type, command, timeout} ] }`. + // Handler fields set DIRECTLY on the entry are unknown keys, so serde drops + // them silently: the config loads, `codex mcp list` succeeds, and the hook + // never registers. Only Codex's app-server `hooks/list` RPC sees this, so a + // load probe can never cover it — this shape assertion is the guard. + const rendered = codexHookTable(hookCommand); + assert.match( + rendered, + /^\[\[hooks\.SessionStart\]\]\nhooks = \[\{ type = "command", command = .*, timeout = 15 \}\]\n$/, + ); + // The flat shape must never be emitted. + assert.doesNotMatch(rendered, /^type = "command"$/m); + + // And the guard must reject the flat shape when it is OURS... + const flatOurs = `[[hooks.SessionStart]]\ntype = "command"\ncommand = ${JSON.stringify(hookCommand)}\ntimeout = 15\n`; + const reason = assertCodexConfigLoads(flatOurs); + assert.notEqual(reason, undefined); + assert.match(String(reason), /must nest its handler/); + + // ...while a FOREIGN flat entry is not bili's to police: it must not block + // installing our own correct entry (that would strand exactly the users who + // already run another hook tool). + const foreignFlat = `model = "gpt-5"\n\n[[hooks.SessionStart]]\ntype = "command"\ncommand = "lean-ctx.exe hook codex-session-start"\ntimeout = 10\n`; + assert.equal(assertCodexConfigLoads(foreignFlat), undefined); + const plan = planCodexHook(foreignFlat, hookCommand); + assert.equal(plan.action, "install"); + assert.equal(assertCodexConfigLoads(plan.text), undefined); +}); + +test("an existing flat bili entry is upgraded in place, not left invisible", () => { + // Self-heal: bili's own older output carried the flat shape. Detecting it as + // "owned" and merely rewriting the command string would leave it silently + // ignored forever, so the whole entry must be replaced. + const flatOurs = `model = "gpt-5"\n\n[[hooks.SessionStart]]\ntype = "command"\ncommand = ${JSON.stringify(hookCommand)}\ntimeout = 15\n`; + const plan = planCodexHook(flatOurs, hookCommand); + assert.equal(plan.action, "refresh"); + assert.match(plan.note, /upgraded to the shape Codex registers/); + assert.equal(assertCodexConfigLoads(plan.text), undefined); + assert.doesNotMatch(plan.text, /^type = "command"$/m); + // Still exactly one entry, still ours, and the user's other tables survive. + assert.equal(plan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 1); + assert.equal(findBiliCodexHook(plan.text), hookCommand); + assert.match(plan.text, /model = "gpt-5"/); +}); + +test("strip removes only our entry and drops the table when it was ours alone", () => { + const original = 'model = "gpt-5"\n'; + const installed = planCodexHook(original, hookCommand).text; + const stripped = stripCodexHook(installed); + assert.equal(stripped.removed, true); + assert.equal(findBiliCodexHook(stripped.text), undefined); + assert.doesNotMatch(stripped.text, /hooks\.SessionStart/); + assert.match(stripped.text, /model = "gpt-5"/); + assert.equal(stripCodexHook(original).removed, false); +}); + +test("strip keeps foreign entries in a shared SessionStart table", () => { + const shared = `model = "gpt-5"\n\n[[hooks.SessionStart]]\nmatcher = "startup|resume|clear"\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\n`; + const withOurs = `${shared.trimEnd()}\n\n${codexHookTable(hookCommand).trimEnd()}\n`; + // Two separate tables: ours is dropped, theirs survives untouched. + const stripped = stripCodexHook(withOurs); + assert.equal(stripped.removed, true); + assert.match(stripped.text, /lean-ctx\.exe hook codex-session-start/); + assert.doesNotMatch(stripped.text, /bootstrap-hook\.js/); +}); + +test("hooks feature note reports a disabled or missing switch", () => { + assert.match(codexHooksEnabledNote('model = "gpt-5"\n'), /hooks = true/); + assert.match( + codexHooksEnabledNote("[features]\nhooks = false\n"), + /disables hooks/, + ); + assert.equal(codexHooksEnabledNote("[features]\nhooks = true\n"), ""); +}); + +test("the feature switch is read on CRLF configs (Windows)", () => { + // Codex keeps CRLF on Windows. An anchored `$` that does not admit the + // trailing `\r` silently missed the switch, so the installer claimed hook + // execution was off on a config that plainly had `hooks = true`. + const crlf = + 'model = "gpt-5"\r\n\r\n[features]\r\nhooks = true\r\n\r\n[[hooks.SessionStart]]\r\nhooks = [{ type = "command", command = "node C:/x/codex/bootstrap-hook.js", timeout = 15 }]\r\n'; + assert.deepEqual(codexHooksFeature(crlf), { value: true, raw: "true" }); + assert.equal(codexHooksEnabledNote(crlf), ""); + assert.equal(findBiliCodexHook(crlf), "node C:/x/codex/bootstrap-hook.js"); + assert.equal(assertCodexConfigLoads(crlf), undefined); + + // And a CRLF config with the switch explicitly off still reports it. + const off = crlf.replace("hooks = true", "hooks = false"); + assert.equal(codexHooksFeature(off)?.value, false); + assert.match(codexHooksEnabledNote(off), /disables hooks/); +}); + +test("an appended entry follows the file's existing line endings", () => { + // The repo convention (src/kimi/toml-edit.ts:21, src/launcher.ts:2466) is to + // never convert a user's file nor mix endings into it. Appending with a bare + // "\n" left a CRLF config with a mixed-ending block. + const crlfBase = + 'model = "gpt-5"\r\n\r\n[features]\r\nhooks = true\r\n\r\n[[hooks.SessionStart]]\r\nmatcher = "startup"\r\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\r\n'; + const crlfPlan = planCodexHook(crlfBase, hookCommand); + assert.equal(crlfPlan.action, "install"); + // No lone LF anywhere in the CRLF file after the append. + assert.equal(/[^\r]\n/.test(crlfPlan.text), false); + assert.equal(crlfPlan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 2); + assert.equal(findBiliCodexHook(crlfPlan.text), hookCommand); + + // An LF file stays LF. + const lfBase = 'model = "gpt-5"\n'; + const lfPlan = planCodexHook(lfBase, hookCommand); + assert.equal(lfPlan.text.includes("\r"), false); +}); + +test("hook table rendering and region detection agree", () => { + // codexHookTable already emits the header; the region finder must see an + // ARRAY-of-tables header, not just a plain one. + const text = codexHookTable(hookCommand); + assert.match(text, /^\[\[hooks\.SessionStart\]\]\n/); + const regions = tableRegions(text, "hooks.SessionStart"); + assert.equal(regions.length, 1); + assert.deepEqual(readCodexHookCommands(regions[0]!), [hookCommand]); +}); + +test("the pre-write guard rejects every shape Codex refuses to load", () => { + // The regression that broke Codex Desktop: a map-valued `hooks`. This exact + // shape is what bili used to write. + const rejected = `[hooks.SessionStart]\nhooks = [{ type = "command", command = ${JSON.stringify(hookCommand)}, timeout = 15 }]\n`; + const reason = assertCodexConfigLoads(rejected); + assert.notEqual(reason, undefined); + assert.match(String(reason), /\[\[hooks\.SessionStart\]\]/); + + // A top-level `hooks = ...` collapses the sequence too. + assert.notEqual(assertCodexConfigLoads("hooks = []\n"), undefined); + + // The flat-sequence shape Codex also refuses (`expected struct HooksToml`). + assert.notEqual( + assertCodexConfigLoads( + `[[hooks]]\nevent = "SessionStart"\ncommand = ${JSON.stringify(hookCommand)}\n`, + ), + undefined, + ); + + // An entry with no command at all — the stub a buggy strip once left behind. + assert.notEqual( + assertCodexConfigLoads('[[hooks.SessionStart]]\ntype = "command"\n'), + undefined, + ); + + // What bili actually writes must pass. + assert.equal(assertCodexConfigLoads(codexHookTable(hookCommand)), undefined); + assert.equal( + assertCodexConfigLoads( + `model = "gpt-5"\n\n[features]\nhooks = true\n\n${codexHookTable(hookCommand)}`, + ), + undefined, + ); +}); + +test("Codex's own hooks.state trust ledger is not mistaken for our stage table", () => { + // Codex records hook approval in `[hooks.state.':::']`, + // a SINGLE-bracket table holding key/value pairs. A guard that treated every + // `hooks`-prefixed header as bili's malformed stage table rejected the whole + // config, so `plugin install codex` skipped the hook face on any config where + // a hook had ever been trusted — with no error, just "hook: skipped". + const trustLedger = `[hooks.state.'C:\\Users\\me\\.codex\\config.toml:session_start:0:0']\ntrusted_hash = "sha256:d89b106f182af9d93c0e2d7611ce5a43b270367c15ec4b3fa8dfeb53768ce2fe"\n`; + assert.equal(assertCodexConfigLoads(trustLedger), undefined); + + // And together with our own entry, which is what a real config looks like. + const withLedger = `${codexHookTable(hookCommand)}\n${trustLedger}`; + assert.equal(assertCodexConfigLoads(withLedger), undefined); + + // The plan still installs into such a file rather than bailing out. + const plan = planCodexHook(trustLedger, hookCommand); + assert.equal(plan.action, "install"); + assert.match(plan.text, /\[\[hooks\.SessionStart\]\]/); + assert.match(plan.text, /hooks\.state/); + assert.equal(assertCodexConfigLoads(plan.text), undefined); +}); + +test("insertTableRaw lands inside the table, before trailing comments", () => { + const text = "[features]\na = 1\n\n# next section follows\n[other]\nb = 2\n"; + const next = insertTableRaw(text, "features", "hooks = true"); + assert.match( + next, + /\[features\]\na = 1\nhooks = true\n\n# next section follows/, + ); + assert.match(next, /\[other\]\nb = 2/); +}); + +test("skill install writes our document and is idempotent", () => { + const { env, dir } = tempHome(); + try { + assert.equal(codexSkillStatus(env), "missing"); + const first = installCodexSkill(env); + assert.equal(first.written, true); + assert.equal(codexSkillStatus(env), "installed"); + assert.equal( + fs.readFileSync(codexSkillFile(env), "utf8"), + CODEX_SKILL_MARKDOWN, + ); + assert.equal(readSkillName(CODEX_SKILL_MARKDOWN), "bili"); + assert.equal(path.dirname(codexSkillFile(env)), codexSkillDir(env)); + + const again = installCodexSkill(env); + assert.equal(again.written, false); + assert.equal(again.note, "ACP skill already installed"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("a foreign same-named skill is never overwritten or deleted", () => { + const { env, dir } = tempHome(); + try { + fs.mkdirSync(codexSkillDir(env), { recursive: true }); + const mine = + "---\nname: bili\ndescription: user's own skill\n---\n\nkeep me\n"; + fs.writeFileSync(codexSkillFile(env), mine); + assert.equal(codexSkillStatus(env), "foreign"); + const install = installCodexSkill(env); + assert.equal(install.written, false); + assert.match(install.note, /left untouched/); + + fs.writeFileSync( + codexSkillFile(env), + "---\nname: someone-else\n---\nbody\n", + ); + assert.equal(codexSkillStatus(env), "foreign"); + const removal = removeCodexSkill(env); + assert.equal(removal.removed, false); + assert.equal( + fs.readFileSync(codexSkillFile(env), "utf8"), + "---\nname: someone-else\n---\nbody\n", + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("an owned-but-edited skill is marked outdated and refreshed", () => { + const { env, dir } = tempHome(); + try { + installCodexSkill(env); + fs.writeFileSync( + codexSkillFile(env), + `${CODEX_SKILL_MARKDOWN}\nlocal note\n`, + ); + assert.equal(codexSkillStatus(env), "outdated"); + const refreshed = installCodexSkill(env); + assert.equal(refreshed.written, true); + assert.equal(codexSkillStatus(env), "installed"); + assert.equal( + fs.readFileSync(codexSkillFile(env), "utf8"), + CODEX_SKILL_MARKDOWN, + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("remove deletes only our skill and leaves a non-empty directory", () => { + const { env, dir } = tempHome(); + try { + installCodexSkill(env); + fs.writeFileSync(path.join(codexSkillDir(env), "notes.md"), "user notes\n"); + const removal = removeCodexSkill(env); + assert.equal(removal.removed, true); + assert.equal(fs.existsSync(codexSkillFile(env)), false); + assert.equal( + fs.existsSync(path.join(codexSkillDir(env), "notes.md")), + true, + ); + assert.equal(codexSkillStatus(env), "missing"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/tests/codex-install-faces.test.ts b/tests/codex-install-faces.test.ts new file mode 100644 index 0000000000..2127abda18 --- /dev/null +++ b/tests/codex-install-faces.test.ts @@ -0,0 +1,145 @@ +import assert from "node:assert"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +function withEnv( + vars: Record, + fn: () => void | Promise, +): Promise { + const saved = new Map(); + for (const [key, value] of Object.entries(vars)) { + saved.set(key, process.env[key]); + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + const restore = (): void => { + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }; + try { + const result = fn(); + if (result instanceof Promise) return result.finally(restore); + restore(); + return Promise.resolve(); + } catch (error) { + restore(); + return Promise.reject(error); + } +} + +// Ticket 08 regression: the Codex install flow must land ALL four faces — +// MCP block, model route, SessionStart hook, ACP skill — and remove must take +// them all back out. The user's report was exactly this gap: the desktop Codex +// saw the MCP plugin but neither a hook nor an ACP skill. +test("plugin install codex writes MCP + route + hook + skill, and remove reverts all four", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-faces-")); + const { pluginInstall, pluginRemove, pluginStatusAll } = await import( + "../src/plugin-install.ts" + ); + try { + await withEnv({ CODEX_HOME: home }, () => { + // `dist/` must exist on disk: the installer refuses to register a + // hook whose script is not built, so simulate a built checkout. + const root = path.dirname( + path.dirname(path.resolve("src/plugin-install.ts")), + ); + const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); + assert.equal( + fs.existsSync(hookScript), + true, + "build before running this test: npm run build", + ); + + const message = pluginInstall("codex"); + assert.match(message, /^codex: installed/); + assert.match(message, /mcp: installed \[mcp_servers\.bili\]/); + assert.match(message, /model route:/); + assert.match(message, /hook: SessionStart hook added/); + assert.match(message, /skill: ACP skill installed/); + + const toml = fs.readFileSync(path.join(home, "config.toml"), "utf8"); + assert.match(toml, /\[mcp_servers\.bili\]\ncommand = /); + // Array-of-tables is required by Codex (`hooks` is a sequence); the + // map form is rejected at load time and breaks the whole host. + assert.match(toml, /\[\[hooks\.SessionStart\]\]\n/); + // ...and the handler must be NESTED in the `hooks = [...]` array. + // Fields set directly on the entry are silently dropped by Codex, so + // this asserts the exact shape its `hooks/list` RPC registers. + assert.match( + toml, + /\[\[hooks\.SessionStart\]\]\nhooks = \[\{ type = "command", command = /, + ); + assert.doesNotMatch(toml, /\[hooks\.SessionStart\]\n/); + assert.doesNotMatch(toml, /\[\[hooks\.SessionStart\]\]\ntype = /); + assert.match(toml, /codex[\\/]bootstrap-hook\.js/); + assert.match( + toml, + /openai_base_url = "http:\/\/127\.0\.0\.1:\d+\/bili\/https:\/\/api\.openai\.com\/v1"/, + ); + + const skillFile = path.join(home, "skills", "bili", "SKILL.md"); + assert.equal(fs.existsSync(skillFile), true); + assert.match(fs.readFileSync(skillFile, "utf8"), /^---\nname: bili\n/); + assert.match(fs.readFileSync(skillFile, "utf8"), /acp_cache/); + + // A rerun is a no-op that still reports every face. + const second = pluginInstall("codex"); + assert.match(second, /^codex: already installed/); + assert.match(second, /hook: SessionStart hook already installed/); + assert.match(second, /skill: ACP skill already installed/); + + // Lane status surfaces the faces separately (doctor reads this). + const lane = pluginStatusAll().find((entry) => entry.agent === "codex"); + assert.ok(lane, "codex lane must be reported"); + assert.match(lane!.status, /mcp installed/); + assert.match(lane!.status, /route installed/); + assert.match(lane!.status, /hook installed/); + assert.match(lane!.status, /skill installed/); + + const removed = pluginRemove("codex"); + assert.match(removed, /^codex: removed/); + assert.match(removed, /hook removed/); + const tomlAfter = fs.readFileSync(path.join(home, "config.toml"), "utf8"); + assert.doesNotMatch(tomlAfter, /mcp_servers\.bili/); + assert.doesNotMatch(tomlAfter, /hooks\.SessionStart/); + assert.doesNotMatch(tomlAfter, /bootstrap-hook\.js/); + assert.doesNotMatch(tomlAfter, /openai_base_url/); + assert.equal(fs.existsSync(skillFile), false); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +// The hook face must never be claimed when it was not written: an unbuilt +// checkout installs the MCP + route faces and SAYS the hook was skipped. +test("plugin install codex reports a skipped hook when dist is not built", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-nohook-")); + const { pluginInstall } = await import("../src/plugin-install.ts"); + try { + await withEnv({ CODEX_HOME: home }, () => { + const root = path.dirname( + path.dirname(path.resolve("src/plugin-install.ts")), + ); + const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); + if (!fs.existsSync(hookScript)) { + const message = pluginInstall("codex"); + assert.match( + message, + /hook: skipped \(dist\/codex\/bootstrap-hook\.js missing\)/, + ); + assert.match(message, /! codex: hook script missing/); + assert.doesNotMatch( + fs.readFileSync(path.join(home, "config.toml"), "utf8"), + /\[hooks\.SessionStart\]/, + ); + } + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); diff --git a/tests/codex-integration-status.test.ts b/tests/codex-integration-status.test.ts new file mode 100644 index 0000000000..fcd3b1743a --- /dev/null +++ b/tests/codex-integration-status.test.ts @@ -0,0 +1,209 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { + codexRouteRecordPath, + writeCodexRouteRecord, +} from "../src/codex-integration/route.ts"; +import { inspectCodexIntegration } from "../src/codex-integration/status.ts"; + +/** Responses where `lastSeenMs` is absent (older proxy build) — the ISO + * `lastSeen` string must still prove freshness, otherwise a user whose + * scheduled service predates the numeric field never reaches `verified`. */ +function isoOnlyFetch(options: { ageMs: number }) { + return async (input: string | URL | Request): Promise => { + const url = String(input); + if (url.endsWith("/__bili/health")) + return Response.json({ ok: true }, { status: 200 }); + if (url.endsWith("/__bili/stats")) + return Response.json({ + sessions: [ + { + codexClient: true, + requests: 2, + lastSeen: new Date(Date.now() - options.ageMs).toISOString(), + lastSeenMs: null, + }, + ], + }); + return new Response("not found", { status: 404 }); + }; +} + +test("an ISO-only lastSeen still proves a fresh Codex request", async () => { + const route = "http://127.0.0.1:18787/bili/https://api.kourichat.com/v1"; + const config = `model_provider = "custom"\n\n[model_providers.custom]\nbase_url = "${route}"\n`; + const fresh = await inspectCodexIntegration({ + origin: "http://127.0.0.1:18787", + codexConfigText: config, + fetchImpl: isoOnlyFetch({ ageMs: 20_000 }), + }); + assert.equal(fresh.state, "verified"); + // Beyond the evidence window a session is history, not current proof. + const stale = await inspectCodexIntegration({ + origin: "http://127.0.0.1:18787", + codexConfigText: config, + fetchImpl: isoOnlyFetch({ ageMs: 25 * 60 * 60_000 }), + }); + assert.notEqual(stale.state, "verified"); +}); + +/** Codex evidence must survive a user idling for a while, but a session served + * from bili's own loopback test upstreams, or one whose hint names another + * client, must never count. */ +test("loopback-fixture sessions and foreign clients are not Codex evidence", async () => { + const origin = "http://127.0.0.1:18787"; + const route = `${origin}/bili/https://api.kourichat.com/v1`; + const config = `model_provider = "custom"\n\n[model_providers.custom]\nbase_url = "${route}"\n`; + const withSession = + (session: Record) => + async (input: string | URL | Request): Promise => { + const url = String(input); + if (url.endsWith("/__bili/health")) + return Response.json({ ok: true }, { status: 200 }); + if (url.endsWith("/__bili/stats")) + return Response.json({ + sessions: [ + { requests: 1, lastSeenMs: Date.now() - 1000, ...session }, + ], + }); + return new Response("not found", { status: 404 }); + }; + + // A fake-E2E session (loopback upstream) plus an idle hour: still only configured. + const fixture = await inspectCodexIntegration({ + origin, + codexConfigText: config, + fetchImpl: withSession({ + codexClient: true, + protocol: "responses", + upstream: `http://127.0.0.1:4805`, + }), + }); + assert.equal(fixture.state, "configured"); + + // A Responses-protocol session with no client hint is Codex's. + const hintless = await inspectCodexIntegration({ + origin, + codexConfigText: config, + fetchImpl: withSession({ + protocol: "responses", + upstream: "https://api.kourichat.com", + }), + }); + assert.equal(hintless.state, "verified"); + + // A hint naming another client vetoes an otherwise Codex-shaped session. + const foreign = await inspectCodexIntegration({ + origin, + codexConfigText: config, + fetchImpl: withSession({ + codexClient: true, + protocol: "responses", + clientHint: "curl/8.0", + upstream: "https://api.kourichat.com", + }), + }); + assert.equal(foreign.state, "configured"); +}); + +function fakeFetch(options: { + healthy: boolean; + codexObserved?: boolean; + codexAgeMs?: number; +}) { + return async (input: string | URL | Request): Promise => { + const url = String(input); + if (url.endsWith("/__bili/health")) + return Response.json( + { ok: options.healthy }, + { status: options.healthy ? 200 : 503 }, + ); + if (url.endsWith("/__bili/stats")) + return Response.json({ + sessions: options.codexObserved + ? [ + { + codexClient: true, + requests: 1, + lastSeenMs: Date.now() - (options.codexAgeMs ?? 0), + }, + ] + : [], + }); + return new Response("not found", { status: 404 }); + }; +} + +test("Codex integration distinguishes proxy-ready, configured, verified, bypassed and unknown", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-status-")); + const file = path.join(home, "config.toml"); + const env = { ...process.env, CODEX_HOME: home }; + const origin = "http://127.0.0.1:18787"; + try { + const ready = await inspectCodexIntegration({ + env, + origin, + codexConfigText: "", + fetchImpl: fakeFetch({ healthy: true }), + }); + assert.equal(ready.state, "proxy-ready"); + const route = `${origin}/bili/https://api.openai.com/v1`; + const config = `openai_base_url = "${route}"\n`; + fs.writeFileSync(file, config); + writeCodexRouteRecord(codexRouteRecordPath(file), { + schemaVersion: 1, + writtenValue: route, + previousValue: null, + upstream: "https://api.openai.com/v1", + }); + const configured = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: fakeFetch({ healthy: true }), + }); + assert.equal(configured.state, "configured"); + const verified = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: fakeFetch({ healthy: true, codexObserved: true }), + }); + assert.equal(verified.state, "verified"); + const stale = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: fakeFetch({ + healthy: true, + codexObserved: true, + codexAgeMs: 25 * 60 * 60_000, + }), + }); + assert.equal( + stale.state, + "configured", + "old Codex sessions are not current route proof", + ); + + const bypassed = await inspectCodexIntegration({ + env, + origin, + codexConfigText: 'openai_base_url = "https://relay.example/v1"\n', + fetchImpl: fakeFetch({ healthy: true }), + }); + assert.equal(bypassed.state, "bypassed"); + const unknown = await inspectCodexIntegration({ + env, + origin, + codexConfigText: "", + fetchImpl: fakeFetch({ healthy: false }), + }); + assert.equal(unknown.state, "unknown"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); diff --git a/tests/codex-route.test.ts b/tests/codex-route.test.ts new file mode 100644 index 0000000000..4aa557e8b7 --- /dev/null +++ b/tests/codex-route.test.ts @@ -0,0 +1,155 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + codexRouteValue, + planCodexRoute, + readCodexRoute, + restoreCodexRoute, + type CodexRouteRecord, +} from "../src/codex-integration/route.ts"; +import { + findTableScalar, + findTopLevelScalar, + removeTopLevelScalar, + setTableScalar, + setTopLevelScalar, +} from "../src/codex-integration/toml-field.ts"; + +const origin = "http://127.0.0.1:18787"; + +test("top-level scalar edits preserve tables and unrelated text", () => { + const original = + '# user\nmodel = "gpt-test"\n\n[sandbox]\nmode = "workspace-write"\n'; + const inserted = setTopLevelScalar( + original, + "openai_base_url", + "http://127.0.0.1:18787/bili/https://api.openai.com/v1", + ); + assert.equal( + findTopLevelScalar(inserted, "openai_base_url")?.value, + "http://127.0.0.1:18787/bili/https://api.openai.com/v1", + ); + assert.match(inserted, /\[sandbox\]\nmode = "workspace-write"/); + assert.equal(removeTopLevelScalar(inserted, "openai_base_url"), original); + assert.equal( + findTopLevelScalar( + '[model_providers.openai]\nopenai_base_url = "nested"\n', + "openai_base_url", + ), + undefined, + ); +}); + +test("route planner owns only a sidecar-recorded value and detects provider shadowing", () => { + const empty = 'model = "gpt-test"\n[sandbox]\nmode = "workspace-write"\n'; + const first = planCodexRoute(empty, { origin }); + assert.equal(first.action, "install"); + assert.equal( + first.value, + codexRouteValue(origin, "https://api.openai.com/v1"), + ); + assert.equal( + planCodexRoute(first.text, { origin }).action, + "conflict", + "a loopback-looking URL without ownership evidence is foreign", + ); + assert.equal( + planCodexRoute(first.text, { origin, ownedValue: first.value }).action, + "keep", + ); + const moved = planCodexRoute(first.text, { + origin: "http://127.0.0.1:18788", + ownedValue: first.value, + }); + assert.equal(moved.action, "refresh"); + assert.equal( + planCodexRoute('openai_base_url = "https://relay.example/v1"\n', { origin }) + .action, + "conflict", + ); + const shadowed = planCodexRoute( + 'model_provider = "relay"\n[model_providers.relay]\nbase_url = "https://relay.example/v1"\n', + { origin }, + ); + assert.equal(shadowed.conflict?.kind, "shadowed-by-provider"); + assert.equal(readCodexRoute(first.text).routed, false); + assert.equal(readCodexRoute(first.text, first.value).routed, true); +}); + +test("uninstall restores only the exact route value from the ownership record", () => { + const original = 'model = "gpt-test"\n[sandbox]\nmode = "workspace-write"\n'; + const plan = planCodexRoute(original, { origin }); + const record: CodexRouteRecord = { + schemaVersion: 1, + writtenValue: plan.value!, + previousValue: null, + upstream: "https://api.openai.com/v1", + }; + assert.deepEqual(restoreCodexRoute(plan.text, record), { + text: original, + restored: true, + stillOwned: true, + }); + const userEdited = plan.text.replace(plan.value!, "https://user.example/v1"); + assert.deepEqual(restoreCodexRoute(userEdited, record), { + text: userEdited, + restored: false, + stillOwned: false, + }); +}); + +test("CC Switch Direct routes only its active provider base_url with reversible ownership", () => { + const original = [ + 'model_provider = "custom"', + 'openai_base_url = "https://root.example/v1"', + "", + "[model_providers.custom]", + 'base_url = "https://api.kourichat.com/v1" # CC Switch Direct', + 'model = "test-model"', + "", + "[sandbox]", + 'mode = "workspace-write"', + "", + ].join("\n"); + const unsupported = planCodexRoute(original, { origin }); + assert.equal(unsupported.action, "conflict"); + const installed = planCodexRoute(original, { origin, ccSwitchMode: "direct" }); + assert.equal(installed.action, "install"); + assert.deepEqual(installed.target, { kind: "provider", provider: "custom" }); + assert.equal( + findTableScalar(installed.text, "model_providers.custom", "base_url")?.value, + codexRouteValue(origin, "https://api.kourichat.com/v1"), + ); + assert.match(installed.text, /openai_base_url = "https:\/\/root\.example\/v1"/); + assert.match(installed.text, /base_url = .* # CC Switch Direct/); + const record: CodexRouteRecord = { + schemaVersion: 1, + writtenValue: installed.value!, + previousValue: "https://api.kourichat.com/v1", + upstream: "https://api.kourichat.com/v1", + target: installed.target, + }; + assert.equal(readCodexRoute(installed.text, record).routed, true); + assert.equal( + planCodexRoute(installed.text, { origin, ccSwitchMode: "direct", ownedRecord: record }).action, + "keep", + ); + assert.equal( + planCodexRoute(original, { origin, ccSwitchMode: "routing" }).action, + "conflict", + ); + assert.deepEqual(restoreCodexRoute(installed.text, record), { + text: original, + restored: true, + stillOwned: true, + }); + const changedBySwitch = original.replace( + 'base_url = "https://api.kourichat.com/v1" # CC Switch Direct', + 'base_url = "https://other-provider.example/v1" # CC Switch Direct', + ); + assert.equal( + planCodexRoute(changedBySwitch, { origin, ccSwitchMode: "direct", ownedRecord: record }).action, + "conflict", + "a CC Switch rewrite after install must not be fought or adopted as a new backup", + ); +}); diff --git a/tests/proxy-service.test.ts b/tests/proxy-service.test.ts new file mode 100644 index 0000000000..9a6b551b7b --- /dev/null +++ b/tests/proxy-service.test.ts @@ -0,0 +1,693 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { + BILI_TASK_NAME, + planTaskDelete, + planTaskDisable, + planTaskEnable, + planTaskEnd, + planTaskQuery, + planTaskRegister, + planTaskRegisterXml, + planTaskRun, + renderTaskLauncherVbs, + renderTaskXml, + type TaskRunner, +} from "../src/proxy-service/task-scheduler.ts"; +import { + disableProxyService, + enableProxyService, + installProxyService, + proxyServiceStatus, + removeProxyService, + restartProxyService, + type TaskCommand, + type TaskRunnerResult, +} from "../src/proxy-service/index.ts"; +import { + planDaemonReload, + planSystemdEnableNow, + planSystemdIsActive, + planSystemdIsEnabled, + renderSystemdUnit, +} from "../src/proxy-service/systemd.ts"; +import { parseArgs } from "../src/cli.ts"; + +const result = ( + exitCode: number, + stdout = "", + stderr = "", +): TaskRunnerResult => ({ exitCode, stdout, stderr }); +const taskRow = + 'true'; + +test("Task Scheduler command plans are per-user logon and safely quoted", () => { + const planned = planTaskRegister({ + nodePath: "C:\\Program Files\\nodejs\\node.exe", + entryPath: + "C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js", + port: 18787, + host: "127.0.0.1", + }); + assert.equal(planned.file, "schtasks.exe"); + assert.deepEqual(planned.args.slice(0, 2), ["/Create", "/TN"]); + assert.ok(planned.args.includes("ONLOGON")); + assert.ok(planned.args.includes("LIMITED")); + const taskRun = planned.args[planned.args.indexOf("/TR") + 1]!; + assert.ok(taskRun.includes('"C:\\Program Files\\nodejs\\node.exe"')); + assert.ok( + taskRun.includes( + '"C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js"', + ), + ); + assert.ok(taskRun.includes("--port 18787")); + assert.equal( + planTaskQuery().args.join(" "), + `/Query /TN ${BILI_TASK_NAME} /XML`, + ); + assert.deepEqual(planTaskRun().args.slice(0, 2), ["/Run", "/TN"]); + assert.deepEqual(planTaskEnd().args.slice(0, 2), ["/End", "/TN"]); + assert.ok(planTaskDisable().args.includes("/DISABLE")); + assert.ok(planTaskEnable().args.includes("/ENABLE")); + assert.ok(planTaskDelete().args.includes("/F")); + assert.throws( + () => + planTaskRegister({ + nodePath: "node.exe", + entryPath: "C:\\bili.js", + port: 8787, + }), + /absolute/, + ); + assert.throws( + () => + planTaskRegister({ + nodePath: "C:\\node.exe", + entryPath: "C:\\bili.js", + port: 65536, + }), + /port/, + ); +}); + +// The proxy must never put a console window in the user's session: an unhidden +// at-logon task makes Task Scheduler create one and no child-side windowsHide +// can suppress it. These assertions pin the setting that prevents the window. +test("the registered task document is hidden and registers from XML", () => { + const planned = planTaskRegisterXml( + "C:\\Users\\Alice\\AppData\\Local\\bili\\task.xml", + ); + assert.equal(planned.file, "schtasks.exe"); + assert.deepEqual(planned.args.slice(0, 2), ["/Create", "/TN"]); + assert.ok(planned.args.includes("/XML")); + assert.equal( + planned.args[planned.args.indexOf("/XML") + 1], + "C:\\Users\\Alice\\AppData\\Local\\bili\\task.xml", + ); + + const xml = renderTaskXml({ + nodePath: "C:\\Program Files\\nodejs\\node.exe", + entryPath: "C:\\bili & sons\\dist\\index.js", + port: 18787, + host: "127.0.0.1", + launcherPath: "C:\\bili & sons\\launch.vbs", + }); + assert.ok(xml.includes("true"), "task must be hidden"); + assert.ok( + xml.includes("InteractiveToken"), + "must stay per-user and non-elevated", + ); + assert.ok(xml.includes("LeastPrivilege")); + assert.ok( + xml.includes( + "IgnoreNew", + ), + "a second logon must not race for the port", + ); + // alone does NOT stop the console window: the scheduler launches a + // console-subsystem node.exe in the interactive session. The action must go + // through wscript.exe running a hidden-mode .vbs, or a window appears. + assert.ok( + xml.includes("wscript.exe"), + "action must launch through the GUI-subsystem script host", + ); + assert.ok( + xml.includes("launch.vbs"), + "action must reference the generated launcher", + ); + assert.ok( + !xml.includes("C:\\Program Files\\nodejs\\node.exe"), + "node must never be the task action directly", + ); + // The launcher path is the only bili path in the task document; the entry + // path lives inside the .vbs. Ampersands must still be escaped. + assert.ok( + xml.includes("""), + "the quoted launcher argument must be XML-escaped", + ); + assert.ok( + xml.includes("launch.vbs""), + "escaping must not swallow the launcher path", + ); + assert.ok( + !xml.includes("& sons"), + "a raw ampersand must never survive into the document", + ); +}); + +test("the generated launcher runs the proxy in hidden mode through WSH", () => { + const vbs = renderTaskLauncherVbs({ + nodePath: "C:\\Program Files\\nodejs\\node.exe", + entryPath: "C:\\bili & sons\\dist\\index.js", + port: 18787, + host: "127.0.0.1", + }); + // VBScript escapes a literal quote by DOUBLING it, so the emitted source + // carries "" around each path while the value WSH sees is a single quote. + assert.ok( + vbs.includes( + 'cmd = """C:\\Program Files\\nodejs\\node.exe"" ""C:\\bili & sons\\dist\\index.js"" start', + ), + "must invoke the proxy with doubled-quote escaping", + ); + assert.ok(vbs.includes("--port 18787")); + assert.ok(vbs.includes("--no-auto-update")); + assert.ok( + /\.Run cmd, 0, True/.test(vbs), + "window style 0 = hidden, and True = wait so the task keeps owning the proxy", + ); + assert.ok( + !/\.Run cmd, 0, False/.test(vbs), + "False reparents node away from the task and orphans it on uninstall", + ); + assert.ok( + vbs.includes('CreateObject("WScript.Shell")'), + "must use the script host shell object", + ); +}); + +test("the launcher quoting survives a path containing quotes", () => { + const vbs = renderTaskLauncherVbs({ + nodePath: 'C:\\odd "quoted" dir\\node.exe', + entryPath: "C:\\plain\\index.js", + port: 1, + host: "127.0.0.1", + }); + assert.ok( + vbs.includes('""quoted""'), + "an embedded quote must be doubled so it stays inside the VBS string literal", + ); + assert.ok( + vbs.includes('cmd = """C:\\odd ""quoted"" dir\\node.exe""'), + "the whole path must remain one quoted token for WSH", + ); +}); + +test("service operations verify install, remain idempotent, and expose failures", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "bili-service-")); + const commands: TaskCommand[] = []; + let exists = false; + let disabled = false; + let failCreate = false; + const runner = async (command: TaskCommand): Promise => { + commands.push(command); + if (command.args[0] === "/Query") + return exists + ? result( + 0, + taskRow.replace( + "true", + disabled ? "false" : "true", + ), + ) + : result(1, "", "ERROR: The system cannot find the file specified."); + if (command.args[0] === "/Create") { + if (failCreate) return result(1, "", "Access is denied."); + exists = true; + return result(0, "SUCCESS: The scheduled task was created."); + } + if (command.args[0] === "/Delete") { + const previous = exists; + exists = false; + return previous + ? result(0, "SUCCESS") + : result(1, "", "ERROR: The system cannot find the file specified."); + } + if (command.args[0] === "/Change" && command.args.includes("/DISABLE")) { + disabled = true; + return result(0, "SUCCESS"); + } + if (command.args[0] === "/Change" && command.args.includes("/ENABLE")) { + disabled = false; + return result(0, "SUCCESS"); + } + return result(0, "SUCCESS"); + }; + const config = { + platform: "win32" as NodeJS.Platform, + nodePath: "C:\\node.exe", + entryPath: "C:\\bili\\dist\\index.js", + port: 18787, + stateDirectory: directory, + runner, + }; + try { + assert.equal((await proxyServiceStatus(config)).state, "missing"); + failCreate = true; + const refused = await installProxyService(config); + assert.equal(refused.ok, false); + assert.match(refused.message, /Access is denied/); + assert.equal( + fs.existsSync(path.join(directory, "proxy-service.json")), + false, + ); + failCreate = false; + const installed = await installProxyService(config); + assert.equal(installed.action, "installed"); + assert.equal(installed.state, "ready"); + assert.equal( + (await installProxyService(config)).action, + "already-installed", + ); + assert.equal((await disableProxyService(config)).state, "disabled"); + assert.equal((await proxyServiceStatus(config)).state, "disabled"); + assert.equal((await enableProxyService(config)).state, "ready"); + assert.equal((await restartProxyService(config)).action, "restarted"); + assert.equal((await removeProxyService(config)).action, "removed"); + assert.equal((await removeProxyService(config)).action, "already-absent"); + assert.ok(commands.some((c) => c.args[0] === "/Run")); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +test("install writes a persistent hidden launcher and remove deletes it", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "bili-launcher-")); + const commands: TaskCommand[] = []; + let exists = false; + const runner: TaskRunner = async (command) => { + commands.push(command); + if (command.args[0] === "/Query") + return exists + ? result(0, taskRow) + : result(1, "", "ERROR: The system cannot find the file specified."); + if (command.args[0] === "/Create") { + exists = true; + return result(0, "SUCCESS: The scheduled task was created."); + } + if (command.args[0] === "/Delete") { + const previous = exists; + exists = false; + return previous + ? result(0, "SUCCESS") + : result(1, "", "ERROR: The system cannot find the file specified."); + } + return result(0); + }; + const config = { + platform: "win32" as NodeJS.Platform, + nodePath: process.execPath, + entryPath: path.join(directory, "dist", "index.js"), + stateDirectory: directory, + runner, + }; + const launcher = path.join(directory, "Billion-Context-Proxy.launch.vbs"); + try { + const installed = await installProxyService(config); + assert.equal(installed.action, "installed"); + // The task references this file at every logon, so it must persist past + // the install command (unlike the temporary XML transport). + assert.ok(fs.existsSync(launcher), "launcher must persist after install"); + // Written UTF-16LE with a BOM for WSH; read it back the same way. + const vbs = fs.readFileSync(launcher, "utf16le"); + assert.ok(vbs.includes("sh.Run cmd, 0, True")); + // /Query also carries a bare /XML flag, so target the /Create command. + const xmlWrite = commands.find( + (c) => c.args[0] === "/Create" && c.args.includes("/XML"), + ); + assert.ok(xmlWrite !== undefined, "registration must go through /XML"); + const xmlPath = xmlWrite.args[xmlWrite.args.indexOf("/XML") + 1] ?? ""; + assert.notEqual(xmlPath, "", "the XML path must be present"); + assert.equal( + fs.existsSync(xmlPath), + false, + "the XML transport file must be cleaned up", + ); + + await removeProxyService(config); + assert.equal( + fs.existsSync(launcher), + false, + "uninstall must not leave a launcher pointing at a removed dist tree", + ); + // The task is the only handle on the running proxy, so it must be stopped + // before the task is deleted. + const endIndex = commands.findIndex((c) => c.args[0] === "/End"); + const deleteIndex = commands.findIndex((c) => c.args[0] === "/Delete"); + assert.notEqual(endIndex, -1, "uninstall must stop the running instance"); + assert.notEqual(deleteIndex, -1, "uninstall must delete the task"); + assert.ok( + endIndex < deleteIndex, + "the instance must be stopped before the task handle is removed", + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +test("service reports unsupported platforms without touching them", async () => { + // Windows (schtasks) and Linux (systemd user unit) are the two serviced + // platforms; everything else must refuse rather than silently do nothing. + const result = await installProxyService({ platform: "darwin" }); + assert.equal(result.action, "unsupported"); + assert.equal(result.ok, false); + assert.match(result.message, /darwin/); +}); + +test("CLI parses service lifecycle actions", () => { + for (const action of [ + "install", + "status", + "restart", + "enable", + "disable", + "remove", + ] as const) { + const parsed = parseArgs(["service", action]); + assert.equal(parsed.command, "service"); + assert.equal(parsed.serviceAction, action); + } +}); + +test("service leaves an unowned task with the bili name untouched", async () => { + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "bili-service-collision-"), + ); + const commands: TaskCommand[] = []; + const runner = async (command: TaskCommand): Promise => { + commands.push(command); + if (command.args[0] === "/Query") return result(0, taskRow); + return result(0, "SUCCESS"); + }; + const config = { + platform: "win32" as NodeJS.Platform, + nodePath: "C:\\node.exe", + entryPath: "C:\\bili\\dist\\index.js", + port: 18787, + stateDirectory: directory, + runner, + }; + try { + assert.equal((await proxyServiceStatus(config)).state, "unknown"); + assert.equal((await installProxyService(config)).ok, false); + assert.equal((await disableProxyService(config)).ok, false); + assert.equal((await enableProxyService(config)).ok, false); + assert.equal((await restartProxyService(config)).ok, false); + assert.equal((await removeProxyService(config)).ok, false); + assert.equal( + commands.filter((command) => + ["/Create", "/Delete", "/Change", "/End"].includes(command.args[0]!), + ).length, + 0, + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +test("localized Task Scheduler missing-task output is treated as absent", async () => { + const runner = async (): Promise => + result(1, "", "错误: 系统找不到指定的文件。"); + const status = await proxyServiceStatus({ platform: "win32", runner }); + assert.equal(status.ok, true); + assert.equal(status.state, "missing"); +}); + +// --------------------------------------------------------------------------- +// Linux backend: per-user systemd unit. A fake `systemctl` keeps the whole +// lifecycle deterministic — no live bus, no root, no host mutation. +// --------------------------------------------------------------------------- + +const UNIT_PATH = "/home/alice/.config/systemd/user/bili-proxy.service"; + +/** Minimal systemctl model: enabled/active flags plus the unit file the + * installer writes, so status/enable/disable/remove can be asserted against + * real state transitions instead of canned strings. `unitPath` must be the + * SAME path the config passes to the service — the fake keys its liveness off + * that file, exactly as systemd keys it off the unit it actually loaded. */ +function fakeSystemctl( + commands: TaskCommand[], + initial?: { enabled?: boolean; active?: boolean; unitPath?: string }, +) { + const unitPath = initial?.unitPath ?? UNIT_PATH; + let enabled = initial?.enabled ?? false; + let active = initial?.active ?? false; + const runner = async (command: TaskCommand): Promise => { + commands.push(command); + if (command.file !== "systemctl") return result(1, "", "unexpected binary"); + const args = command.args.filter((a) => a !== "--user"); + switch (args[0]) { + case "daemon-reload": + return result(0, ""); + case "is-enabled": + if (!fs.existsSync(unitPath)) + return result(1, "", "Unit bili-proxy.service could not be found."); + return result(0, enabled ? "enabled" : "disabled"); + case "is-active": + if (!fs.existsSync(unitPath)) return result(3, "inactive"); + return active ? result(0, "active") : result(3, "inactive"); + case "enable": + enabled = true; + // `enable --now` also starts; a bare `enable` does not. + if (command.args.includes("--now")) active = true; + return result(0, ""); + case "disable": + enabled = false; + active = false; + return result(0, ""); + case "start": + active = true; + return result(0, ""); + case "stop": + active = false; + return result(0, ""); + default: + return result(1, "", `unknown verb ${args[0]}`); + } + }; + return { runner, state: () => ({ enabled, active }) }; +} + +test("systemd unit plans are per-user, quoted and enable at logon", () => { + const planned = planSystemdEnableNow({ unitName: "bili-proxy.service" }); + assert.equal(planned.file, "systemctl"); + assert.deepEqual(planned.args, [ + "--user", + "enable", + "--now", + "bili-proxy.service", + ]); + assert.deepEqual(planDaemonReload().args, ["--user", "daemon-reload"]); + assert.deepEqual(planSystemdIsEnabled({ unitName: "u" }).args, [ + "--user", + "is-enabled", + "u", + ]); + assert.deepEqual(planSystemdIsActive({ unitName: "u" }).args, [ + "--user", + "is-active", + "u", + ]); + + const unit = renderSystemdUnit({ + nodePath: "/usr/bin/node", + entryPath: "/opt/bili path/dist/index.js", + port: 18787, + host: "127.0.0.1", + unitPath: UNIT_PATH, + }); + assert.match(unit, /^\[Unit\]/m); + assert.match(unit, /WantedBy=default\.target/); + assert.match(unit, /Type=simple/); + assert.match(unit, /Restart=on-failure/); + assert.match(unit, /--no-auto-update/); + // The spaced entry path must survive as ONE argv element. + assert.ok( + unit.includes( + 'ExecStart="/usr/bin/node" "/opt/bili path/dist/index.js" start --host "127.0.0.1" --port 18787 --no-auto-update', + ), + ); + assert.throws( + () => + renderSystemdUnit({ + nodePath: "node", + entryPath: "/opt/bili/dist/index.js", + port: 8787, + unitPath: UNIT_PATH, + }), + /absolute/, + ); + assert.throws( + () => + renderSystemdUnit({ + nodePath: "/usr/bin/node", + entryPath: "/opt/bili/dist/index.js", + port: 0, + unitPath: UNIT_PATH, + }), + /RangeError|port/, + ); +}); + +test("quotes are escaped so a path can never inject extra ExecStart arguments", () => { + const unit = renderSystemdUnit({ + nodePath: '/usr/bin/node"', + entryPath: "/opt/b/dist/index.js", + port: 8787, + unitPath: UNIT_PATH, + }); + assert.ok( + unit.includes('ExecStart="/usr/bin/node\\"" "/opt/b/dist/index.js"'), + ); +}); + +test("systemd install writes the unit, enables it, starts it and is idempotent", async () => { + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "bili-systemd-install-"), + ); + const commands: TaskCommand[] = []; + const unitPath = path.join(directory, "bili-proxy.service"); + const fake = fakeSystemctl(commands, { unitPath }); + const config = { + platform: "linux" as NodeJS.Platform, + taskName: "bili-proxy.service", + nodePath: "/usr/bin/node", + entryPath: "/opt/bili/dist/index.js", + port: 18787, + stateDirectory: directory, + unitPath, + runner: fake.runner, + }; + try { + assert.equal((await proxyServiceStatus(config)).state, "missing"); + const installed = await installProxyService(config); + assert.equal(installed.action, "installed"); + assert.equal(installed.state, "ready"); + assert.ok(fs.readFileSync(config.unitPath, "utf8").includes("ExecStart=")); + assert.ok( + commands.some((c) => c.args.join(" ") === "--user daemon-reload"), + ); + assert.ok( + commands.some( + (c) => c.args.join(" ") === "--user enable --now bili-proxy.service", + ), + ); + assert.deepEqual(fake.state(), { enabled: true, active: true }); + assert.equal((await proxyServiceStatus(config)).state, "ready"); + + const again = await installProxyService(config); + assert.equal(again.action, "already-installed"); + + assert.equal((await disableProxyService(config)).state, "disabled"); + assert.deepEqual(fake.state(), { enabled: false, active: false }); + assert.equal((await proxyServiceStatus(config)).state, "disabled"); + + assert.equal((await enableProxyService(config)).state, "ready"); + assert.deepEqual(fake.state(), { enabled: true, active: true }); + + assert.equal((await restartProxyService(config)).action, "restarted"); + assert.equal((await removeProxyService(config)).action, "removed"); + assert.equal(fs.existsSync(config.unitPath), false); + assert.equal((await removeProxyService(config)).action, "already-absent"); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +test("systemd install rolls the unit back when it never becomes active", async () => { + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "bili-systemd-rollback-"), + ); + const commands: TaskCommand[] = []; + const runner = async (command: TaskCommand): Promise => { + commands.push(command); + const args = command.args.filter((a) => a !== "--user"); + if (args[0] === "is-enabled") + return result(1, "", "Unit bili-proxy.service could not be found."); + if (args[0] === "is-active") return result(3, "inactive"); + return result(0, ""); + }; + const config = { + platform: "linux" as NodeJS.Platform, + taskName: "bili-proxy.service", + nodePath: "/usr/bin/node", + entryPath: "/opt/bili/dist/index.js", + port: 18787, + stateDirectory: directory, + unitPath: path.join(directory, "bili-proxy.service"), + runner, + }; + try { + const failed = await installProxyService(config); + assert.equal(failed.ok, false); + assert.match(failed.message, /did not become active/); + // The machine is left as it was: no unit file, no record. + assert.equal(fs.existsSync(config.unitPath), false); + assert.equal( + fs.existsSync(path.join(directory, "proxy-service.json")), + false, + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +test("systemd refuses a host with no user manager and names the fix", async () => { + const runner = async (): Promise => + result(1, "", "Failed to connect to bus: No medium found"); + const installed = await installProxyService({ + platform: "linux", + unitPath: UNIT_PATH, + runner, + }); + assert.equal(installed.ok, false); + assert.match(installed.message, /enable-linger/); +}); + +test("systemd leaves a unit it does not own untouched", async () => { + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "bili-systemd-foreign-"), + ); + const commands: TaskCommand[] = []; + const fake = fakeSystemctl(commands, { enabled: true, active: true }); + fs.writeFileSync(path.join(directory, "bili-proxy.service"), "foreign\n"); + const config = { + platform: "linux" as NodeJS.Platform, + taskName: "bili-proxy.service", + nodePath: "/usr/bin/node", + entryPath: "/opt/bili/dist/index.js", + port: 18787, + stateDirectory: directory, + unitPath: path.join(directory, "bili-proxy.service"), + runner: fake.runner, + }; + try { + const refused = await installProxyService(config); + assert.equal(refused.ok, false); + assert.match(refused.message, /not owned by this bili copy/); + assert.equal(fs.readFileSync(config.unitPath, "utf8"), "foreign\n"); + assert.equal( + commands.filter((c) => + ["disable", "stop", "enable"].includes( + c.args.filter((a) => a !== "--user")[0]!, + ), + ).length, + 0, + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); From 8cb3bf056754fc67ed712bffcf969035cf34ff87 Mon Sep 17 00:00:00 2001 From: Eliver Date: Wed, 14 Oct 2026 20:09:32 +0800 Subject: [PATCH 02/20] feat: codex lane wiring (cli/plugin-install/admin/docs/tests) alongside plugin work --- .gitignore | 2 + CLIENTS.md | 121 +- CLIENTS.zh-CN.md | 39 +- src/cache-ledger.ts | 4066 +++++++++++++++----------- src/cli.ts | 1239 ++++---- src/doctor.ts | 767 +++-- src/plugin-install.ts | 4541 +++++++++++++++++++----------- src/server/admin.ts | 2255 +++++++++------ tests/codex-responses-ws.test.ts | 821 ++++-- tests/doctor.test.ts | 1811 ++++++++---- tsup.config.ts | 204 +- 11 files changed, 9975 insertions(+), 5891 deletions(-) diff --git a/.gitignore b/.gitignore index 7e2336bcda..239a0b30d1 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ dist/ tmp/ tests/.pp-stamp-state-*/ .tmp/ +# Local development specifications and ticket drafts (not published) +.scratch/ diff --git a/CLIENTS.md b/CLIENTS.md index a2c18532bf..7d0eabef8f 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -75,7 +75,7 @@ Two lanes, same plugin (#941): loaded plugin and the proxy never drift apart again (#953); profiles pinned to a local source are left alone. The refresh is best-effort, retries next cycle on failure, and never fails the update or the proxy. - - **Reported: zero proxy traffic for some transports under profile install +- **Reported: zero proxy traffic for some transports under profile install (#1158, under investigation):** sessions served by some of dsh's `llm-pi-ai`-layer transports show NO model request ever reaching the proxy (no `processTurn` logged; bili tools 404 with "no model request has @@ -90,7 +90,7 @@ Two lanes, same plugin (#941): settings overlay rewrites those providers' `baseURL`s to `/bili/` URLs, so the traffic reaches the proxy regardless of which fetch the transport uses or what the attribution state is. - - **Web-profile caveat (#1772, corrected by #2474):** when a profile's +- **Web-profile caveat (#1772, corrected by #2474):** when a profile's bundles include `@deepseek-ai/dsh-web-app`, the running `compaction-basic` instance lives inside an agent preset (`preset-standard.config.plugins`). No patch layer can address that NESTED row by id — dsh's patch engine @@ -109,7 +109,7 @@ Two lanes, same plugin (#941): freezes the roster until re-copied after a dsh preset update. The plugin logs a one-time `[dsh-client]` warning naming this recipe at boot in such profiles; ACP compression is unaffected. - - **Global copy shadows the profile copy at load time (#2891):** dsh resolves +- **Global copy shadows the profile copy at load time (#2891):** dsh resolves the bare `billion-context` name in `dsh.profile.bundles` installation- anchor-first — from its own install tree (the global npm root) before the profile's `node_modules`. So if a machine-global `billion-context` exists @@ -396,30 +396,85 @@ the client's window through the existing launcher/runtime reporting mechanism or set the existing `compress.modelContextLimit`; the proxy's local cache is not evidence of another machine's configuration. Output headroom still applies. -Codex is the one client a plugin install cannot make self-sufficient. The seam -matrix explains why: claude has a `SessionStart` hook + managed settings block, -zcode has a provider store whose `baseURL` can be rewritten — codex has neither. -Its model traffic routes via environment variables only (`HTTPS_PROXY` / -`SSL_CERT_FILE` — this is how `bili codex` works); the default -ChatGPT-login provider has no config-file routing seam, and a managed -`model_providers` block would force `env_key` API-key auth and **drop the -subscription login**. An MCP server cannot inject env into its parent process, -so the plugin can never route codex's own traffic. Three postures: +Codex now has four distinct integration faces. `bili plugin install codex` writes +the `[mcp_servers.bili]` block for ACP tools, adds a bili-owned Codex model route +through `/bili/`, installs a `[[hooks.SessionStart]]` entry +running `dist/codex/bootstrap-hook.js`, and writes the ACP skill to +`~/.codex/skills/bili/SKILL.md`. For ordinary Codex configuration the route is +the top-level `openai_base_url`. When the current +Codex config is positively detected as CC Switch Direct, bili instead routes +the active `[model_providers.].base_url`, which Codex actually uses. It +preserves the native Codex account and provider selection and never writes the +CC Switch database. The route's target, previous value and exact written value +are recorded in a bili sidecar; removal restores only the value that still +exactly matches bili's record, and leaves later user edits intact. A foreign +route or a provider field changed by CC Switch is reported as a conflict and +left untouched. CC Switch may rewrite the field during provider/mode changes; +bili does not run a watcher to compete with those writes. | Posture | What you get | -|---|---| -| `bili codex` (launcher) | Full zero-config: a self-managed lane proxy (#1660 zone, sticky port) + cert-MITM env injected into codex — tools *and* compression | -| `bili plugin install codex` + a running bili + self-exported `HTTPS_PROXY` | Tools + compression for power users who manage their own env | -| `bili plugin install codex` alone | The four tools appear in codex but no conversation is proxied, so there is nothing for them to act on; `tools/list` fails with -32003 (`bili proxy unreachable … — start bili or set BILI_MCP_PROXY`) when nothing is reachable | - -The install writes a single `[mcp_servers.bili]` block into `~/.codex/config.toml` -(command = node, args = dist/mcp.js). #1660 removed the install-time origin bake -(#403: a baked URL went stale after drift/reboot and left the tools pointing at -a dead port); the shell resolves the proxy at session start — env -`BILI_MCP_PROXY` > the live-instance record (any lane's proxy, or a -`bili start` daemon) > the 8787 user-zone default — so a drifted or rebooted -proxy never strands a dead URL, and the shell simply attaches to whatever is -alive. Session binding is headless: the launcher passes +| --- | --- | +| `bili codex` (launcher) | Managed lane proxy and cert-MITM; tools + compression | +| `bili plugin install codex` | Native Codex model route + ACP tools + SessionStart hook + ACP skill | + +**Each face proves only itself.** The MCP block proves TOOLS, never that model +traffic reaches bili. The hook is attach-only (it never spawns a proxy, and +fails open) and reports this session's runtime to an already-running proxy. The +skill only tells the model which ACP tools exist. Only the route face — plus an +observed real request — says anything about compression. `bili plugin status` +and `bili doctor` report all four separately, so a lane missing one of them can +never read as a complete install. + +**Ownership of the hook and skill faces.** `[[hooks.SessionStart]]` is an ARRAY +of tables, so a foreign entry (lean-ctx and friends live there) is a sibling, +not a competitor: bili APPENDS its own entry, keeps every existing one, and +refreshes/removes only the entry whose command names its own script. The same +rule covers the skill: a same-named `SKILL.md` bili does not own is left alone. + +**The shape of bili's entry is load-bearing in two separate ways**, and each +failure mode is different: + +- Codex deserializes `hooks` as a SEQUENCE, so the `[hooks.SessionStart]` + + `hooks = [{…}]` map form makes the whole config unloadable — and an unloadable + config takes the host down (observed on Codex Desktop, surfacing only an + unrelated-looking `AbsolutePathBuf deserialized without a base path in + model_catalog json`). This one is LOUD. +- Each entry is a `MatcherGroup` — `{ matcher?, hooks = [ { type = "command", + command, timeout } ] }`. Handler fields written DIRECTLY on the entry are + unknown keys, so Codex drops them **silently**: the config loads, `codex mcp + list` succeeds, and the hook simply never registers. This one is SILENT, and a + load probe can never detect it — only Codex's own `hooks/list` app-server RPC + can. + +The installer refuses to write any shape known to fail either way, and upgrades +an older flat entry it finds in place. `[features] hooks = true` is Codex's +master switch for hook execution — when it is off, bili writes its entry and +says so rather than editing a switch value the user set. Uninstall deletes only +bili's own entry and file, and keeps the skill directory when the user has other +files in it. + +`bili service install` registers a per-user Windows Task Scheduler logon task +for a persistent proxy. `bili service status|restart|enable|disable|remove` +manage it; unsupported platforms and failed registration are reported explicitly. +When the proxy is down, Codex's configured URL remains loopback and requests +fail at the local endpoint; there is no direct-upstream fallback. `bili doctor` +reports `proxy-ready`, `configured`, `verified`, `bypassed`, or `unknown`. +`verified` requires an observed Codex model request, while a healthy proxy or a +written config alone cannot claim verification. + +CC Switch Direct is supported only at the current Codex config route layer: +when Direct is positively detected, bili can wrap the active provider's +`base_url` with reversible ownership. This is not integration with CC Switch's +provider database or synchronization mechanism. Routing and Aggregation remain +detection-only; discovery does not prove API-level compatibility. No CC Switch +files are modified and bili does not install a competing watcher. ChatGPT subscription/Desktop integration stays +`待完成/可实现`: the implementation does not read, copy, persist, or inject +`auth.json`, cookies, or session tokens; Desktop MCP is separate from model +routing, and official login channels remain intact. + +The MCP shell still resolves its proxy at session start — env `BILI_MCP_PROXY` +> the live-instance record (any lane's proxy, or a `bili start` daemon) > the +8787 user-zone default. Session binding is headless: the launcher passes `BILI_CONVERSATION_ID` at spawn time, and the plugin shell binds the next NEW session otherwise; per-call `conversation_id` overrides work as everywhere (#760). Codex ≥0.160 additionally stamps the real thread id on every @@ -587,7 +642,7 @@ plugin-mode session. **WebSocket coverage (#2073, implemented in #2111).** A WebSocket connection never goes through `globalThis.fetch`, so the native extension also wraps `globalThis.WebSocket` at load time — before pi's first model connection (pi's Node branch reads the global per call; its Bun branch caches a subclass on first call, which is why install-time ordering is safe on both runtimes). Only supported Codex Responses model connections are rewritten — every other WebSocket (devtools, third-party libraries, already-routed URLs) passes through untouched: | Provider / transport | Status | -|---|---| +| --- | --- | | All HTTP providers | ✅ covered — named plugin-mode session | | `openai-codex-responses` (ChatGPT backend-api), `transport: "sse"` | ✅ covered — identical to any HTTP provider | | `openai-codex-responses`, `transport: "auto"` (default) or `"websocket"` / `"websocket-cached"` | ✅ covered (#2111) — the constructor URL is rewritten to `/bili/` (e.g. `wss://chatgpt.com/backend-api/codex/responses` → `ws://127.0.0.1:/bili/https://chatgpt.com/backend-api/codex/responses`). Constructor args, subprotocols and request headers are preserved, so the same `session-id` pi sends on SSE rides the upgrade and the session identity is byte-identical across transports; subagents keep their own ids. `previous_response_id` incremental continuation works over the lane (the proxy expands deltas before the pipeline and re-optimizes them back upstream) | @@ -651,7 +706,7 @@ Post-fix matrix (real-machine verified: pi 0.83.6 + pi-subagents 0.76.0, HTTP transports; WS row documented from #2073, no live cell): | Cell | Pre-fix | Post-fix | -|---|---|---| +| --- | --- | --- | | native × foreground × default config | anonymous `pfa-*` proxy mode; ACP tools only via proxy wire injection | **named child-sid plugin-mode session**; ACP tools registered locally from the first request; compression recorded under the child's own id | | native × background × default config | ambient luck — named plugin mode when the settings packages happened to load | same, now deterministic (`required: ["bili"]` in the child's launch-resolved extensions) | | native × background × agent def `extensions: []` / `denyExtensions` | **silent direct connect** — zero proxy visibility, no compression | deterministic required-path load; named plugin session. (If a runtime capability ceiling hard-denies extensions, pi-subagents 0.76.0 fails the child launch loudly instead — fail-fast, not silent) | @@ -700,7 +755,7 @@ Every client that lets you **edit its model endpoint and carries an API key** (r Verified entry points (community-maintained list — the mechanism is generic): | Client | Where the base URL lives | -|---|---| +| --- | --- | | **Cline / Roo Code / Kilo Code** (VS Code) | provider settings — "OpenAI Compatible" Base URL, or the Anthropic provider's base URL | | **Continue** | `~/.continue/config.yaml` — per-model `apiBase` | | **OpenHands** | `llm.base_url` (config or env) | @@ -765,7 +820,7 @@ is the recommended context manager. Everything below is verified end-to-end on `@opencode/cli` 2.0.3 (V1 lane: 1.14.46 and 1.18.31). | Path | Command | When | -|---|---|---| +| --- | --- | --- | | Launcher (easiest) | `bili opencode` | one command brings up proxy + client; real config untouched | | Native (no launcher) | `bili plugin install opencode` | self-spawning plugin in your real config; start `opencode` as usual | | Pure proxy (fallback) | baseURL `/bili/` prefix | no plugin — wire-level tool injection | @@ -897,8 +952,11 @@ sessions (#920) get an explicit unavailable notice instead (their traffic bypasses this proxy's compression state). Claude Code has no in-process command API: `bili plugin install claude` writes a model-mediated `commands/acp-cache.md` markdown command whose prompt drives the `acp_cache` -MCP tool and pastes the report back verbatim. codex/kimi/hermes expose no -user-typable command seam — ask the model to call its `acp_cache` tool directly. +MCP tool and pastes the report back verbatim. Codex has no user-typable command +seam either, so `bili plugin install codex` writes the ACP skill +(`~/.codex/skills/bili/SKILL.md`) telling the model when to reach for +`acp_cache`/`acp_status`/`decompress`; kimi/hermes ship no skill at all — ask +the model to call its `acp_cache` tool directly. Per-fold P&L verdicts are priced by the optional `compress.priceProfile` (normalized multipliers over the input-token unit); when no level sets it, the request model's models.dev price row applies in absolute $/Mtok (kernel ratio @@ -958,4 +1016,3 @@ returns `[Block … not found]`, new refs restart from m00001). eliminates kernel-version drift between agent and proxy; it does not rely on the plugin API being unable to mutate context (that capability varies by 2.x build). - diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index 72ecb845c0..1c9cb32bc4 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -4,7 +4,6 @@ --- - ## dsh(deepseek-harness) 两条通道,同一个插件(#941): @@ -112,15 +111,29 @@ fork 继承同一面;Antigravity 自带用户插件系统 —— `plugins/ **窗口对齐。** 客户端 plugin/runtime 上报及启动器传递的窗口优先于发布时的 Codex 模型表。没有上报时,本机代理只读其 `CODEX_HOME`(默认 `~/.codex`)下的 `models_cache.json` 和基础 `config.toml`,将 `model_context_window` 限制在匹配模型的 `max_context_window` 内,再应用 `effective_context_window_percent`(Codex 默认 95);后续请求会跟随缓存更新。元数据缺失、不可读或无效时,保留内置表及未知模型 272K 的既有回退。远程代理或其他客户端 profile 应通过现有启动器/runtime 机制传递实际窗口,或设置既有的 `compress.modelContextLimit`;代理本机缓存不能证明另一台机器的配置。输出预留仍正常生效。 -Codex 是唯一一个插件安装无法自给自足的客户端。接缝矩阵可以解释:claude 有 SessionStart hook + 受管 settings 块,zcode 有可改写 `baseURL` 的 provider store —— codex 两者都没有。它的模型流量只能经环境变量路由(`HTTPS_PROXY` / `SSL_CERT_FILE` —— `bili codex` 正是这么做的);默认 ChatGPT-登录 provider 没有可改写的配置缝,managed `model_providers` 块会强制 `env_key` API-key 认证、**废掉订阅登录**;而 MCP 子进程无法向父进程注入 env,所以插件永远路由不了 codex 本体流量。三种姿势: +Codex 现在有四个彼此独立的集成面。`bili plugin install codex` 会写入 `[mcp_servers.bili]` 块以提供 ACP 工具,默认添加由 bili 所有的模型路由(经 `/bili/` 转发原生 Codex CLI 请求),写入一个 `[[hooks.SessionStart]]` 条目运行 `dist/codex/bootstrap-hook.js`,并把 ACP 技能写到 `~/.codex/skills/bili/SKILL.md`。普通 Codex 配置使用顶层 `openai_base_url`;若明确检测到 CC Switch Direct,则改写当前生效的 `[model_providers.].base_url`,保留原生账号与 provider 选择,且不写 CC Switch 数据库。路由目标、原值和 bili 写入的精确值记录在 sidecar;卸载时只还原仍与记录完全一致的字段,后续用户编辑会保留。外部路由冲突或 CC Switch 已重写该字段时会报告冲突并保留现值。CC Switch 切换 provider/模式或同步配置时可能重写路由;bili 不运行 watcher 与之抢写。 + +| 方式 | 能力 | +| --- | --- | +| `bili codex`(启动器) | 受管 lane 代理与证书 MITM;工具 + 压缩 | +| `bili plugin install codex` | 原生 Codex 模型路由 + ACP 工具 + SessionStart hook + ACP 技能 | + +**四个面各证各的。** MCP 块只证明工具可用,绝不证明模型流量经过 bili;hook 只做 attach(从不 spawn 代理,失败即放行)并把本会话 runtime 上报给已在运行的代理;技能只是告诉模型有哪些 ACP 工具及其用法;只有路由面(外加观测到的真实请求)才与压缩有关。`bili plugin status` 与 `bili doctor` 分别报告这四项,缺哪一项都不会被读成完整安装。 + +**Hook 与技能的所有权。** `[[hooks.SessionStart]]` 是**数组表**,所以别人写的条目(lean-ctx 之类就住在这里)是**兄弟条目**而不是竞争者:bili **追加**自己的一条、保留全部已有条目,只刷新/删除命令指向自己脚本的那一条。技能同理:同名但非 bili 所有的 `SKILL.md` 完全不碰。 + +**条目形状有两处硬要求,两种失败模式完全不同:** + +- Codex 把 `hooks` 反序列化为**序列**,写成 `[hooks.SessionStart]` + `hooks = [{…}]` 的 map 形式会让整份配置无法加载,进而拖垮宿主(实测 Codex 桌面端只报一个看似无关的 `AbsolutePathBuf deserialized without a base path in model_catalog json`)。这一种是**响的**。 +- 每个条目是 `MatcherGroup`——`{ matcher?, hooks = [ { type = "command", command, timeout } ] }`。把 `type`/`command`/`timeout` 直接写在条目上,这些键在 `MatcherGroup` 上是未知字段,会被 Codex **静默丢弃**:配置照常加载、`codex mcp list` 照常成功,hook 却根本不会注册。这一种是**哑的**,任何"能不能加载"的探测都发现不了——只有 Codex 自己的 `hooks/list` app-server RPC 能看见。 + +安装器拒绝写入任何一种已知会失败的形状,并会把发现的旧扁平条目**就地升级**。`[features] hooks = true` 是 Codex 的 hook 总开关:没有开启时 bili 会写入 hook 条目并明确提示需要打开,不会替你改写既有的开关值。卸载时 bili 只删自己的条目/文件;技能目录里另有用户文件时目录保留。 + +`bili service install` 会注册 Windows 当前用户的 Task Scheduler 登录任务以持久运行代理。可用 `bili service status|restart|enable|disable|remove` 管理;不支持的平台与注册失败会明确报告。代理关闭时,Codex 配置的 URL 仍是 loopback,请求会在本地端点失败,不会静默回退到上游直连。`bili doctor` 会报告 `proxy-ready`、`configured`、`verified`、`bypassed` 或 `unknown`;只有观测到真实 Codex 模型请求才会标记 `verified`,健康代理或已写配置本身都不能证明已验证。 -| 姿势 | 你能得到什么 | -|---|---| -| `bili codex`(启动器) | 全功能零配置:自管 lane 代理(#1660 端口区,粘性口)+ 注入 codex 的证书 MITM env —— 工具与压缩兼得 | -| `bili plugin install codex` + 在跑的 bili + 自行导出 `HTTPS_PROXY` | 自己管 env 的 power user:工具 + 压缩 | -| 只装 `bili plugin install codex` | codex 里出现四个工具但没有对话被代理、无话可操作;全不可达时 `tools/list` 报 -32003(`bili proxy unreachable … — start bili or set BILI_MCP_PROXY`) | +CC Switch Direct 仅在当前 Codex provider 的 `config.toml` 路由层受支持:这是可撤销的配置写入,不代表 bili 与 CC Switch 的 provider 数据库或同步机制已集成。Routing/Aggregation 仍只检测并报告,不自动改写;发现模式不代表 API 级兼容。bili 不修改 CC Switch 数据库,也不会安装 watcher。ChatGPT 订阅/Desktop 集成仍标为 `待完成/可实现`:实现不会读取、复制、持久化或注入 `auth.json`、cookies 或 session token;Desktop MCP 与模型路由分开,官方登录渠道保持不变。 -安装写入 `~/.codex/config.toml` 单个 `[mcp_servers.bili]` 块(command = node,args = dist/mcp.js)。#1660 去掉了安装时烘焙 origin(#403:烘焙的 URL 在漂移/重启后变成死端口,工具永远指向它);shell 在会话启动时解析代理 —— env `BILI_MCP_PROXY` > 活实例登记(任一 lane 的代理,或 `bili start` 守护)> 8787 用户区默认 —— 漂移或重启后绝不残留死 URL,shell 直接附着到活着的那个。会话绑定是 headless 的:启动器在 spawn 时传 `BILI_CONVERSATION_ID`,插件 shell 否则绑定下一个新会话;逐调用的 `conversation_id` 覆盖与其他客户端一致(#760)。Codex ≥0.160 还在每次 `tools/call` 的 `_meta.threadId` 里盖上真实 thread id;shell 按调用消费(严格校验、绝不写回 spawn 时的全局绑定),优先级高于过期的 `BILI_CONVERSATION_ID` 残留与模型抄写的 `conversation_id`(#2024)。 +MCP shell 仍在会话启动时解析代理 —— env `BILI_MCP_PROXY` > 活实例登记(任一 lane 的代理,或 `bili start` 守护)> 8787 用户区默认。会话绑定是 headless 的:启动器在 spawn 时传 `BILI_CONVERSATION_ID`,插件 shell 否则绑定下一个新会话;逐调用的 `conversation_id` 覆盖与其他客户端一致(#760)。Codex ≥0.160 还在每次 `tools/call` 的 `_meta.threadId` 里盖上真实 thread id;shell 按调用消费(严格校验、绝不写回 spawn 时的全局绑定),优先级高于过期的 `BILI_CONVERSATION_ID` 残留与模型抄写的 `conversation_id`(#2024)。 **Responses 原生链式(一个坑)。** bili 靠重放完整 `input` 来压缩,因此无法跟随 OpenAI 原生的 `previous_response_id` 链式续传:只带增量的续传请求会在上游丢失之前的轮次,却仍返回 200。对 codex 而言今天这不是问题 —— 观察到的构建都发 `store:false` 且从不设置 `previous_response_id`(是观察不是证明;E2E 未覆盖该形态)。若你把走原生链式的 Responses 客户端指向 bili,要么重发完整 input/output 历史,要么设 `ACP_KEEP_RESPONSE_ID=1`;bili 剥掉非空 `previous_response_id` 时现在会记一条 `warn`(#1954)。完整链式支持跟踪在 #1973。见[官方迁移指南](https://developers.openai.com/api/docs/guides/migrate-to-responses)。 @@ -149,7 +162,7 @@ Pi 有完整原生模式(`bili plugin install pi`,README 快速上手方案 1); **WebSocket 覆盖(#2073,#2111 实现)。** WebSocket 连接从不经过 `globalThis.fetch`,所以原生扩展在加载时(首个模型连接之前)同时包装 `globalThis.WebSocket`(pi 的 Node 分支每次调用都读全局,Bun 分支首次调用时缓存子类——两个运行时的安装时序都因此安全)。只重写受支持的 Codex Responses 模型连接——其余 WebSocket(devtools、第三方库、已路由 URL)原样通过: | Provider / 传输 | 状态 | -|---|---| +| --- | --- | | 全部 HTTP provider | ✅ 覆盖 —— 具名 plugin-mode 会话 | | `openai-codex-responses`(ChatGPT backend-api),`transport: "sse"` | ✅ 覆盖 —— 与任何 HTTP provider 无异 | | `openai-codex-responses`,`transport: "auto"`(默认)/ `"websocket"` / `"websocket-cached"` | ✅ 覆盖(#2111)—— 构造器 URL 被重写为 `/bili/`(例:`wss://chatgpt.com/backend-api/codex/responses` → `ws://127.0.0.1:/bili/https://chatgpt.com/backend-api/codex/responses`)。构造器参数、子协议、请求头全部保留,pi 在 SSE 上发的同一个 `session-id` 随升级握手到达,会话标识跨传输字节一致;子代理各用自己的会话 ID。`previous_response_id` 增量续传在该车道可用(代理先展开 delta 再进管线,回上游前再优化回 delta) | @@ -179,7 +192,7 @@ pi-subagents(pi.dev 上的包)为前台/后台子代理运行派生**子会话** 修复后矩阵(pi 0.83.6 + pi-subagents 0.76.0 实机验证,HTTP 传输;WS 行依据 #2073 记录,无实机格): | 格子 | 修复前 | 修复后 | -|---|---|---| +| --- | --- | --- | | native × 前台 × 默认配置 | 匿名 `pfa-*` proxy 模式;ACP 工具仅靠代理 wire 注入 | **具名 child-sid plugin 模式会话**;ACP 工具首个请求起本地注册;压缩记在 child 自己的 id 下 | | native × 后台 × 默认配置 | ambient 运气——settings packages 恰好加载时才是具名 plugin 模式 | 同上,但现在是确定性的(child launch-resolved extensions 里 `required: ["bili"]`) | | native × 后台 × agent 定义 `extensions: []` / `denyExtensions` | **静默直连**——代理零可见性、无压缩 | 确定性必需路径加载;具名 plugin 会话。(若运行时能力上限硬性拒绝扩展,pi-subagents 0.76.0 会让 child 启动大声失败——fail-fast 而非静默) | @@ -201,7 +214,7 @@ pi-subagents(pi.dev 上的包)为前台/后台子代理运行派生**子会话** 已核实的入口(社区维护清单——机制本身是通用的): | 客户端 | baseURL 所在 | -|---|---| +| --- | --- | | **Cline / Roo Code / Kilo Code**(VS Code) | provider 设置 —— "OpenAI Compatible" Base URL,或 Anthropic provider 的 base URL | | **Continue** | `~/.continue/config.yaml` —— 各模型的 `apiBase` | | **OpenHands** | `llm.base_url`(配置或 env) | @@ -247,7 +260,7 @@ bili 只压缩路径匹配已知 wire 协议(`/chat/completions`、`/llm_raw_cha 同一个内置插件同时服务两代 OpenCode:agent 文件同时保留 V1 `server()` 与 V2 `setup()` 导出 —— ≥ 1.18.29 的 1.x 宿主加载 V1 形状,2.x 宿主加载 V2 `setup()`。独立扩展 [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) 仅支持 V1,在 2.x 下**不加载** —— 对 OpenCode 2.x,**billion-context 是推荐的上下文管理方案**。以下均在 `@opencode/cli` 2.0.3 上端到端验证过(V1 泳道:1.14.46 与 1.18.31)。 | 路径 | 命令 | 适用 | -|---|---|---| +| --- | --- | --- | | 启动器(最省事) | `bili opencode` | 一条命令拉起代理 + 客户端;不碰真实配置 | | 原生(免启动器) | `bili plugin install opencode` | 自拉起插件写进真实配置;照常启动 `opencode` | | 纯代理(兜底) | baseURL 加 `/bili/` 前缀 | 无插件 —— wire 级工具注入 | @@ -311,7 +324,7 @@ OpenAI/ChatGPT 凭据。 `/acp` 面板在所有模式下都绑定当前会话,`acp_status` 工具是其宿主内等价手段。在命令编辑器支持新增条目的宿主(2.0.x 稳定版,`editor.add`)上,V2 插件额外注册 `/acp` 斜杠命令 —— 以合成非模型消息渲染,面板优先(与 `acp_status` 工具一致);旧形状上该注册保持惰性。注意 `opencode run` 模式完全不派发斜杠命令(它们会透传给模型)—— 请用 TUI。 -同一接缝还承载 `/acp-cache`(#1146)—— prompt-cache 对账报告的人侧入口(输出与 `acp_cache` 工具一致):pi/omp 原生注册(`/acp-cache [full]` 出逐行清单);opencode V1 渲染为一条被忽略的消息,代理在到达 wire 前从模型上下文剥离;opencode V2 渲染为合成消息(报告最多可见 ~8 KB);dsh(两条泳道)显示默认摘要台账——dsh 的命令 API 不传参数,故无 `full`。旧 opencode-acp 会话(#920)收到显式的不可用提示(其流量绕过本代理的压缩状态)。Claude Code 没有进程内命令 API:`bili plugin install claude` 写一个模型中介的 `commands/acp-cache.md` markdown 命令,其 prompt 驱动 `acp_cache` MCP 工具并把报告逐字贴回。codex/kimi/hermes 没有用户可输入的命令接缝——直接让模型调用它的 `acp_cache` 工具。每次折叠的盈亏判定按可选的 `compress.priceProfile`(以输入 token 单价为基准的归一化倍率)计价;任何层级都未设置时,取请求模型在 models.dev 的价格行按绝对 $/Mtok 计(仅无法解析的模型回退内核比率默认值)——因此 breakeven/PAID BACK 开箱即反映你上游的真实经济账;对带自定义加价的中转站可按 provider 覆盖(CONFIGURATION.zh-CN.md,#1279)。 +同一接缝还承载 `/acp-cache`(#1146)—— prompt-cache 对账报告的人侧入口(输出与 `acp_cache` 工具一致):pi/omp 原生注册(`/acp-cache [full]` 出逐行清单);opencode V1 渲染为一条被忽略的消息,代理在到达 wire 前从模型上下文剥离;opencode V2 渲染为合成消息(报告最多可见 ~8 KB);dsh(两条泳道)显示默认摘要台账——dsh 的命令 API 不传参数,故无 `full`。旧 opencode-acp 会话(#920)收到显式的不可用提示(其流量绕过本代理的压缩状态)。Claude Code 没有进程内命令 API:`bili plugin install claude` 写一个模型中介的 `commands/acp-cache.md` markdown 命令,其 prompt 驱动 `acp_cache` MCP 工具并把报告逐字贴回。codex 同样没有用户可输入的命令接缝,因此 `bili plugin install codex` 会写一个 ACP 技能(`~/.codex/skills/bili/SKILL.md`),告诉模型何时该取用 `acp_cache`/`acp_status`/`decompress`;kimi/hermes 不装技能——直接让模型调用它的 `acp_cache` 工具。每次折叠的盈亏判定按可选的 `compress.priceProfile`(以输入 token 单价为基准的归一化倍率)计价;任何层级都未设置时,取请求模型在 models.dev 的价格行按绝对 $/Mtok 计(仅无法解析的模型回退内核比率默认值)——因此 breakeven/PAID BACK 开箱即反映你上游的真实经济账;对带自定义加价的中转站可按 provider 覆盖(CONFIGURATION.zh-CN.md,#1279)。 同一接缝还承载 `/acp-rule`(#1251/#1399)—— 持久指令功能的人侧入口(输出与 `acp_rule` 工具一致):pi/omp 原生注册,操作集与工具完全一致 —— 裸 `/acp-rule` 逐字列出全部已记录指令,`/acp-rule <文本>` 直接记录一条(等价于模型调用),`/acp-rule remove ` 删除一条,裸 `/acp-rule clear` 清空全部(`clear <文本>` 是记录而非清空——一个手误不该毁掉所有规则)。包裹后的 transcript 消息按内容签名从模型上下文剥离(与缓存报告同机制)—— 已记录的指令本来就每轮经 system prompt 注入。 diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index b89b4299d0..3954105d1f 100644 --- a/src/cache-ledger.ts +++ b/src/cache-ledger.ts @@ -1,24 +1,35 @@ import { createHash, randomUUID } from "node:crypto"; import { - computeFoldEconomics, - decomposeSample, - type CoreMessage, - FOLD_CLAIM_COLD_ROUNDS, - FOLD_CLAIM_WARM_HIT_PCT, - formatCacheReport, - summarizeFoldEconomics, - type CacheReport, - type CacheReportLine, - type CacheTotals, - type CompressionBlock, - type FoldEvent, - type PriceProfile, + computeFoldEconomics, + decomposeSample, + type CoreMessage, + FOLD_CLAIM_COLD_ROUNDS, + FOLD_CLAIM_WARM_HIT_PCT, + formatCacheReport, + summarizeFoldEconomics, + type CacheReport, + type CacheReportLine, + type CacheTotals, + type CompressionBlock, + type FoldEvent, + type PriceProfile, } from "acp-kernel"; import { log as loggerLog } from "./logger.js"; -import { METADATA_CANONICAL_SYS_FP, METADATA_FOLD_COVERAGE, METADATA_LAST_RESPONSES_MODE, METADATA_SYSTEM_FP } from "./fold-reconcile.js"; -import { clearPostRebuildAnchor, markDirty, reanchorNudgeOnUsageDrop, type Session } from "./session.js"; +import { + METADATA_CANONICAL_SYS_FP, + METADATA_FOLD_COVERAGE, + METADATA_LAST_RESPONSES_MODE, + METADATA_SYSTEM_FP, +} from "./fold-reconcile.js"; +import { + clearPostRebuildAnchor, + markDirty, + reanchorNudgeOnUsageDrop, + type Session, +} from "./session.js"; import { normalizeUpstreamOrigin } from "./util.js"; import { toolFail, toolOk, type ProxyToolResult } from "./proxy-tool-result.js"; +import { isProxyManagedCredential } from "./codex-integration/cc-switch.js"; // Render window for handleAcpCache's detail:"full" text view (#1489). The // ledger itself is unbounded — this only bounds how many lines the text @@ -46,274 +57,281 @@ const SIZE_BUCKET_TOK = 20000; const LOST_LOGGED_KEY = "foldCoverageLostLogged"; function median(xs: number[]): number | null { - if (xs.length === 0) return null; - const s = [...xs].sort((x, y) => x - y); - const m = s.length >> 1; - return s.length % 2 === 1 ? s[m] : Math.round((s[m - 1] + s[m]) / 2); + if (xs.length === 0) return null; + const s = [...xs].sort((x, y) => x - y); + const m = s.length >> 1; + return s.length % 2 === 1 ? s[m] : Math.round((s[m - 1] + s[m]) / 2); } interface LedgerFold { - seq: number; - at: number; - S: number; - sigma: number; - /** #2929: samples this fold has claimed under the cold-tail window - * (first claim unconditional, then cold continuations until warm or - * FOLD_CLAIM_COLD_ROUNDS). Sparse: absent on ledgers persisted before - * #2929 — treated as 0 claims, which reproduces the first-claim path. */ - claims?: number; - /** #2929: claim window closed (warm line proved re-cache, or the cold-round - * bound elapsed). Sparse: absent = open. */ - retired?: boolean; - X?: number; - V?: number; - Vp?: number; - T: number; - hPct: number | null; - requestsAfter: number; - k: number | null; - /** #2202: kernel blockId the fold was cut from — links the entry to - * reconcileFoldCoverage's per-block coverage evidence (foldCoverageByBlock) - * so avoided-token accrual can be conditioned on measured wire presence. - * Sparse: absent on ledgers persisted before #2202 (unverifiable → status - * quo booking, byte-identical to pre-#2202 behavior). */ - bid?: string; + seq: number; + at: number; + S: number; + sigma: number; + /** #2929: samples this fold has claimed under the cold-tail window + * (first claim unconditional, then cold continuations until warm or + * FOLD_CLAIM_COLD_ROUNDS). Sparse: absent on ledgers persisted before + * #2929 — treated as 0 claims, which reproduces the first-claim path. */ + claims?: number; + /** #2929: claim window closed (warm line proved re-cache, or the cold-round + * bound elapsed). Sparse: absent = open. */ + retired?: boolean; + X?: number; + V?: number; + Vp?: number; + T: number; + hPct: number | null; + requestsAfter: number; + k: number | null; + /** #2202: kernel blockId the fold was cut from — links the entry to + * reconcileFoldCoverage's per-block coverage evidence (foldCoverageByBlock) + * so avoided-token accrual can be conditioned on measured wire presence. + * Sparse: absent on ledgers persisted before #2202 (unverifiable → status + * quo booking, byte-identical to pre-#2202 behavior). */ + bid?: string; } interface LedgerLine { - seq: number; - at: number; - input: number; - cached: number; - output: number; - hitPct: number | null; - missed: number; - nc: number; - cr: number; - tr: number; - foldSeq: number | null; - model?: string; - /** #1536: wire protocol of this request — part of the target identity. */ - proto?: string; - /** #1536: LLM endpoint origin of this request — part of the target identity. */ - up?: string; - /** #2131: outbound credential fingerprint of this request - * ("sha256:<12 hex>" of authorization/x-api-key/… — the raw key is - * NEVER stored). A URL-granular upstream identity cannot see relay - * key-pool rotation; the fingerprint can. Sparse: omitted when no - * header capture happened on this lane. */ - kp?: string; - /** #1592-family seam detector: 1 iff this sample's unexplained residual - * tripped the mid-history-break suspicion (no fold/switch/restart - * attribution AND a large ttlRepay). Sparse: omitted unless set. */ - seam?: 1; - /** #1592 follow-up: 1 iff this sample settled within 30s of a client - * mid-stream abort in the same session (abort/retry churn correlation). */ - abortedNear?: 1; - /** #2929: which attribution arm detectSeam booked this sample's residual - * into — "ttl" (long-idle byte-stable miss, normal ageing), "side" - * (short-idle byte-stable miss, abnormal provider failure), "rewind" - * (client revert/trim re-bill) or "client" (#3023: the client's own - * resent history broke mid-list — host-side insert/rewrite, e.g. another - * plugin or paste hoisting; the outbound seam is bili's faithful rebuild - * of host churn). Sparse: omitted unless booked. The seam arm sets `seam` - * above instead. Lets the web trajectory chart paint the same bucket - * membership the economics card aggregates. */ - prov?: "ttl" | "side" | "rewind" | "client"; - /** #1535: 1 iff `model` differs from the previous sample's KNOWN model - * (unknown sides never flag); marks the re-billed stable prefix on the - * first request after a model switch. Sparse: omitted unless set. */ - sw?: 1; - /** #1536: 1 iff `proto` differs from the previous sample's KNOWN protocol. */ - pw?: 1; - /** #1536: 1 iff `up` differs from the previous sample's KNOWN origin. */ - uw?: 1; - /** #2131: 1 iff `kp` differs from the previous sample's KNOWN credential - * fingerprint — relay account rotation behind a stable URL. */ - kw?: 1; - /** #2350: system-prompt fingerprint of this request ("sha256:<16 hex>" via - * fold-reconcile's noteSystemPromptFingerprint — raw prompt text is NEVER - * stored). Sparse: omitted when no system was noted on this lane. */ - sp?: string; - /** #2350: 1 iff `sp` differs from the previous sample's KNOWN system-prompt - * fingerprint — the forwarded system bytes changed between requests, - * invalidating every downstream prefix cache entry. Whether that is a host - * rewrite or bili's own mode/projection switch is decided by `pf` below - * (#2867). */ - sf?: 1; - /** #2867: 1 iff `sp` flipped while the CANONICAL incoming fingerprint stayed - * stable — bili's own compression-mode/projection switch (self-heal - * degrade-to-proxy re-hoists mid-history developer items) changed what was - * forwarded, NOT the host. Charged to the `projection` cause, never to - * `prompt`. */ - pf?: 1; - /** #2867: 1 iff the canonical incoming system/developer fingerprint flipped - * WITHOUT the forwarded projection flipping (e.g. a mid-history developer - * edit under plugin mode, which never touches the head developer block) — - * observational only: a host-side change outside the projected system - * surface; no billing bucket of its own. */ - cf?: 1; - /** #2867: compression mode serving this sample on the responses lane — - * context for `pf` events (the before/after pair lives on consecutive - * lines). Sparse: other lanes and pre-#2867 lines omit it. */ - pm?: "plugin" | "proxy"; - /** #1536: 1 on the first KNOWN sample under a NEW daemon boot (#499 restart/refork). */ - rs?: 1; - /** #1536: 1 when the provider reported NO cache tokens — unmeasurable, quarantined out of closure totals. */ - unk?: 1; - /** #1891: 1 iff this sample had NO previous ledger baseline (the session's - * first measurable bill). Nothing was billed before, so nothing could have - * expired: its uncached input is initial content, booked as newContent and - * never a seam candidate. Sparse: omitted unless set. */ - nb?: 1; - /** #1847: the single primary cause this line's stable-prefix residual was charged to (a partition — - * never more than one); omitted when unattributed or unmeasured. */ - cause?: "restart" | "model" | "key" | "prompt" | "projection" | "wire" | "upstream"; - /** #2131: SHA-256 hex of this request's exact outbound body — the per-call - * byte-identity proof; sparse: omitted when no body was captured. */ - bd?: string; - /** #2131: 1 iff the outbound body was byte-identical to the PREVIOUS settled - * request's body (e.g. a transport retry), 0 iff it diverged. Sparse: - * omitted without a comparable predecessor. */ - be?: 0 | 1; - /** #2131: first diverging byte offset when be=0 and both full bodies were - * retained under BODY_FULL_CAP. Sparse. */ - bl?: number; - /** #2131: divergence class of a be=0 pair — "head": change within the first - * 1 KiB (model/tools/sampling-params/system region → host-side parameter - * change, not a history rewrite); "append": the whole shorter payload - * survives ±64 closing-bracket bytes (pure tail growth/trim); "mid": a - * mid-history rewrite; "tail" (#2982): the first divergence sits at/past - * the shorter body's message-array closing bracket — only trailing - * top-level params (host-computed max_tokens/…) or an ephemeral tail note - * that appeared/vanished between requests changed; shared history bytes - * untouched, prefix cache unaffected; "unknown": bodies above BODY_FULL_CAP - * (inequality proven by digest, offset unavailable). Sparse. */ - bs?: "head" | "append" | "mid" | "tail" | "unknown"; + seq: number; + at: number; + input: number; + cached: number; + output: number; + hitPct: number | null; + missed: number; + nc: number; + cr: number; + tr: number; + foldSeq: number | null; + model?: string; + /** #1536: wire protocol of this request — part of the target identity. */ + proto?: string; + /** #1536: LLM endpoint origin of this request — part of the target identity. */ + up?: string; + /** #2131: outbound credential fingerprint of this request + * ("sha256:<12 hex>" of authorization/x-api-key/… — the raw key is + * NEVER stored). A URL-granular upstream identity cannot see relay + * key-pool rotation; the fingerprint can. Sparse: omitted when no + * header capture happened on this lane. */ + kp?: string; + /** #1592-family seam detector: 1 iff this sample's unexplained residual + * tripped the mid-history-break suspicion (no fold/switch/restart + * attribution AND a large ttlRepay). Sparse: omitted unless set. */ + seam?: 1; + /** #1592 follow-up: 1 iff this sample settled within 30s of a client + * mid-stream abort in the same session (abort/retry churn correlation). */ + abortedNear?: 1; + /** #2929: which attribution arm detectSeam booked this sample's residual + * into — "ttl" (long-idle byte-stable miss, normal ageing), "side" + * (short-idle byte-stable miss, abnormal provider failure), "rewind" + * (client revert/trim re-bill) or "client" (#3023: the client's own + * resent history broke mid-list — host-side insert/rewrite, e.g. another + * plugin or paste hoisting; the outbound seam is bili's faithful rebuild + * of host churn). Sparse: omitted unless booked. The seam arm sets `seam` + * above instead. Lets the web trajectory chart paint the same bucket + * membership the economics card aggregates. */ + prov?: "ttl" | "side" | "rewind" | "client"; + /** #1535: 1 iff `model` differs from the previous sample's KNOWN model + * (unknown sides never flag); marks the re-billed stable prefix on the + * first request after a model switch. Sparse: omitted unless set. */ + sw?: 1; + /** #1536: 1 iff `proto` differs from the previous sample's KNOWN protocol. */ + pw?: 1; + /** #1536: 1 iff `up` differs from the previous sample's KNOWN origin. */ + uw?: 1; + /** #2131: 1 iff `kp` differs from the previous sample's KNOWN credential + * fingerprint — relay account rotation behind a stable URL. */ + kw?: 1; + /** #2350: system-prompt fingerprint of this request ("sha256:<16 hex>" via + * fold-reconcile's noteSystemPromptFingerprint — raw prompt text is NEVER + * stored). Sparse: omitted when no system was noted on this lane. */ + sp?: string; + /** #2350: 1 iff `sp` differs from the previous sample's KNOWN system-prompt + * fingerprint — the forwarded system bytes changed between requests, + * invalidating every downstream prefix cache entry. Whether that is a host + * rewrite or bili's own mode/projection switch is decided by `pf` below + * (#2867). */ + sf?: 1; + /** #2867: 1 iff `sp` flipped while the CANONICAL incoming fingerprint stayed + * stable — bili's own compression-mode/projection switch (self-heal + * degrade-to-proxy re-hoists mid-history developer items) changed what was + * forwarded, NOT the host. Charged to the `projection` cause, never to + * `prompt`. */ + pf?: 1; + /** #2867: 1 iff the canonical incoming system/developer fingerprint flipped + * WITHOUT the forwarded projection flipping (e.g. a mid-history developer + * edit under plugin mode, which never touches the head developer block) — + * observational only: a host-side change outside the projected system + * surface; no billing bucket of its own. */ + cf?: 1; + /** #2867: compression mode serving this sample on the responses lane — + * context for `pf` events (the before/after pair lives on consecutive + * lines). Sparse: other lanes and pre-#2867 lines omit it. */ + pm?: "plugin" | "proxy"; + /** #1536: 1 on the first KNOWN sample under a NEW daemon boot (#499 restart/refork). */ + rs?: 1; + /** #1536: 1 when the provider reported NO cache tokens — unmeasurable, quarantined out of closure totals. */ + unk?: 1; + /** #1891: 1 iff this sample had NO previous ledger baseline (the session's + * first measurable bill). Nothing was billed before, so nothing could have + * expired: its uncached input is initial content, booked as newContent and + * never a seam candidate. Sparse: omitted unless set. */ + nb?: 1; + /** #1847: the single primary cause this line's stable-prefix residual was charged to (a partition — + * never more than one); omitted when unattributed or unmeasured. */ + cause?: + | "restart" + | "model" + | "key" + | "prompt" + | "projection" + | "wire" + | "upstream"; + /** #2131: SHA-256 hex of this request's exact outbound body — the per-call + * byte-identity proof; sparse: omitted when no body was captured. */ + bd?: string; + /** #2131: 1 iff the outbound body was byte-identical to the PREVIOUS settled + * request's body (e.g. a transport retry), 0 iff it diverged. Sparse: + * omitted without a comparable predecessor. */ + be?: 0 | 1; + /** #2131: first diverging byte offset when be=0 and both full bodies were + * retained under BODY_FULL_CAP. Sparse. */ + bl?: number; + /** #2131: divergence class of a be=0 pair — "head": change within the first + * 1 KiB (model/tools/sampling-params/system region → host-side parameter + * change, not a history rewrite); "append": the whole shorter payload + * survives ±64 closing-bracket bytes (pure tail growth/trim); "mid": a + * mid-history rewrite; "tail" (#2982): the first divergence sits at/past + * the shorter body's message-array closing bracket — only trailing + * top-level params (host-computed max_tokens/…) or an ephemeral tail note + * that appeared/vanished between requests changed; shared history bytes + * untouched, prefix cache unaffected; "unknown": bodies above BODY_FULL_CAP + * (inequality proven by digest, offset unavailable). Sparse. */ + bs?: "head" | "append" | "mid" | "tail" | "unknown"; } interface CacheLedger { - v: 1; - lastBlockId: number; - consumedFoldSeq: number; - sampleSeq: number; - foldSeqCounter: number; - folds: LedgerFold[]; - lines: LedgerLine[]; - agg: { - requests: number; - input: number; - cached: number; - output: number; - nc: number; - cr: number; - tr: number; - switches: number; - switchMissed: number; - /** #2131: relay account rotations — the outbound credential - * fingerprint changed between consecutive samples (same URL can - * hide a key pool behind it). Counted independently of the model/ - * wire/upstream dimensions; charged only when `key` wins the - * attribution partition. */ - keySwitches: number; - keySwitchMissed: number; - /** #2350: host system-prompt rewrites — the system-prompt fingerprint - * changed between consecutive samples (the host rewrites its own - * instructions mid-session, e.g. a periodic dynamic section). Counted - * independently of the other dimensions; charged only when `prompt` - * wins the attribution partition. Post-#2867 this counts HOST-side - * flips only (canonical incoming view also changed); proxy-side mode - * switches book into projSwitches instead. */ - promptSwitches: number; - promptSwitchMissed: number; - /** #2867: proxy projection/mode switches — the forwarded system bytes - * flipped while the canonical incoming system/developer view stayed - * stable (self-heal degrade-to-proxy re-hoists mid-history developer - * items; the prefix invalidation is real but bili's own doing). */ - projSwitches: number; - projSwitchMissed: number; - wireSwitches: number; - wireSwitchMissed: number; - upstreamSwitches: number; - upstreamSwitchMissed: number; - restartDrops: number; - restartDropMissed: number; - attributedMissed: number; - unknownSamples: number; - unknownInput: number; - /** #1891: no-baseline first bills — samples booked as initial content - * (their uncached input could not be a prefix re-pay) + billed input. */ - nbSamples: number; - nbInput: number; - seamSuspects: number; - seamMissed: number; - /** #1592 follow-up: misses with no client-side prefix break — the current - * body is byte-stable vs the previous request, or the previous message - * list comes back byte-identical as a prefix with only tail messages - * appended (#2059). Either way the upstream simply did not serve its - * cache (TTL expiry / eviction / relay node rotation). Not a rebuild seam. */ - providerSideMisses: number; - providerSideMissed: number; - /** #3023: client-side mid-history rewrites — the inbound pair broke - * mid-list (host-side insert/rewrite: another plugin, paste hoisting, - * host re-rendering), so the residual belongs to the host, not to a - * bili rebuild seam. Charged only when the client arm wins. */ - clientInserts: number; - clientInsertMissed: number; - /** #2929: the provider-side arm split by idle gap — samples settled more - * than PROVIDER_TTL_GAP_MS after the previous sample are normal TTL - * expiry, not an abnormal provider failure. */ - providerTtlMisses: number; - providerTtlMissed: number; - /** #1592 follow-up: misses right after the client rewound history - * (revert/trim — fewer message elements than the previous request). - * Sanctioned client intent; recorded so the one-time re-bill is - * attributed instead of landing in the unexplained residual. */ - rewinds: number; - rewindMissed: number; - /** #1592 follow-up: samples settled within 30s of a client abort — - * abort/retry churn correlates with prefix misses (the retried - * request carries a rewritten tail). Correlation, not causation. */ - abortCorrelated: number; - }; - /** #1592-family: bounded forensic log of suspected mid-history cache-seam - * breaks (consecutive outbound bodies diverged with no structural - * attribution). Purely diagnostic — never part of the closure math. */ - seamEvents?: SeamEvent[]; - /** #1536: BOOT_ID of the process that recorded the last line — a mismatch on - * the next sample marks a proxy-restart boundary (#499). Absent pre-#1536. */ - lastBoot?: string; - /** #1847: incremental switch-attribution trackers, advanced by measured samples only. Absent - * pre-#1847 — robust detection + cold-window continuation simply don't apply to older ledgers. */ - lastKnownModel?: string; - lastKnownProto?: string; - lastKnownUp?: string; - /** #2131: last measured outbound credential fingerprint ("sha256:<12hex>"). - * Absent until the first sample that captured one — unknown never flags. */ - lastKnownKey?: string; - /** #2350: last noted system-prompt fingerprint ("sha256:<16hex>"). Absent - * until the first request that carried one — unknown never flags. */ - lastKnownSp?: string; - /** #2867: last noted CANONICAL incoming system/developer fingerprint — - * mode-independent, so a stable canon with a flipped forwarded projection - * is bili's own mode/projection switch, not a host rewrite. */ - lastKnownCanon?: string; - invModel?: { seq: number; at: number; from: string | null; to: string }; - invWire?: { seq: number; at: number; from: string | null; to: string }; - invUp?: { seq: number; at: number; from: string | null; to: string }; - invKey?: { seq: number; at: number; from: string | null; to: string }; - invSp?: { seq: number; at: number; from: string | null; to: string }; - invProj?: { seq: number; at: number; from: string | null; to: string }; + v: 1; + lastBlockId: number; + consumedFoldSeq: number; + sampleSeq: number; + foldSeqCounter: number; + folds: LedgerFold[]; + lines: LedgerLine[]; + agg: { + requests: number; + input: number; + cached: number; + output: number; + nc: number; + cr: number; + tr: number; + switches: number; + switchMissed: number; + /** #2131: relay account rotations — the outbound credential + * fingerprint changed between consecutive samples (same URL can + * hide a key pool behind it). Counted independently of the model/ + * wire/upstream dimensions; charged only when `key` wins the + * attribution partition. */ + keySwitches: number; + keySwitchMissed: number; + /** #2350: host system-prompt rewrites — the system-prompt fingerprint + * changed between consecutive samples (the host rewrites its own + * instructions mid-session, e.g. a periodic dynamic section). Counted + * independently of the other dimensions; charged only when `prompt` + * wins the attribution partition. Post-#2867 this counts HOST-side + * flips only (canonical incoming view also changed); proxy-side mode + * switches book into projSwitches instead. */ + promptSwitches: number; + promptSwitchMissed: number; + /** #2867: proxy projection/mode switches — the forwarded system bytes + * flipped while the canonical incoming system/developer view stayed + * stable (self-heal degrade-to-proxy re-hoists mid-history developer + * items; the prefix invalidation is real but bili's own doing). */ + projSwitches: number; + projSwitchMissed: number; + wireSwitches: number; + wireSwitchMissed: number; + upstreamSwitches: number; + upstreamSwitchMissed: number; + restartDrops: number; + restartDropMissed: number; + attributedMissed: number; + unknownSamples: number; + unknownInput: number; + /** #1891: no-baseline first bills — samples booked as initial content + * (their uncached input could not be a prefix re-pay) + billed input. */ + nbSamples: number; + nbInput: number; + seamSuspects: number; + seamMissed: number; + /** #1592 follow-up: misses with no client-side prefix break — the current + * body is byte-stable vs the previous request, or the previous message + * list comes back byte-identical as a prefix with only tail messages + * appended (#2059). Either way the upstream simply did not serve its + * cache (TTL expiry / eviction / relay node rotation). Not a rebuild seam. */ + providerSideMisses: number; + providerSideMissed: number; + /** #3023: client-side mid-history rewrites — the inbound pair broke + * mid-list (host-side insert/rewrite: another plugin, paste hoisting, + * host re-rendering), so the residual belongs to the host, not to a + * bili rebuild seam. Charged only when the client arm wins. */ + clientInserts: number; + clientInsertMissed: number; + /** #2929: the provider-side arm split by idle gap — samples settled more + * than PROVIDER_TTL_GAP_MS after the previous sample are normal TTL + * expiry, not an abnormal provider failure. */ + providerTtlMisses: number; + providerTtlMissed: number; + /** #1592 follow-up: misses right after the client rewound history + * (revert/trim — fewer message elements than the previous request). + * Sanctioned client intent; recorded so the one-time re-bill is + * attributed instead of landing in the unexplained residual. */ + rewinds: number; + rewindMissed: number; + /** #1592 follow-up: samples settled within 30s of a client abort — + * abort/retry churn correlates with prefix misses (the retried + * request carries a rewritten tail). Correlation, not causation. */ + abortCorrelated: number; + }; + /** #1592-family: bounded forensic log of suspected mid-history cache-seam + * breaks (consecutive outbound bodies diverged with no structural + * attribution). Purely diagnostic — never part of the closure math. */ + seamEvents?: SeamEvent[]; + /** #1536: BOOT_ID of the process that recorded the last line — a mismatch on + * the next sample marks a proxy-restart boundary (#499). Absent pre-#1536. */ + lastBoot?: string; + /** #1847: incremental switch-attribution trackers, advanced by measured samples only. Absent + * pre-#1847 — robust detection + cold-window continuation simply don't apply to older ledgers. */ + lastKnownModel?: string; + lastKnownProto?: string; + lastKnownUp?: string; + /** #2131: last measured outbound credential fingerprint ("sha256:<12hex>"). + * Absent until the first sample that captured one — unknown never flags. */ + lastKnownKey?: string; + /** #2350: last noted system-prompt fingerprint ("sha256:<16hex>"). Absent + * until the first request that carried one — unknown never flags. */ + lastKnownSp?: string; + /** #2867: last noted CANONICAL incoming system/developer fingerprint — + * mode-independent, so a stable canon with a flipped forwarded projection + * is bili's own mode/projection switch, not a host rewrite. */ + lastKnownCanon?: string; + invModel?: { seq: number; at: number; from: string | null; to: string }; + invWire?: { seq: number; at: number; from: string | null; to: string }; + invUp?: { seq: number; at: number; from: string | null; to: string }; + invKey?: { seq: number; at: number; from: string | null; to: string }; + invSp?: { seq: number; at: number; from: string | null; to: string }; + invProj?: { seq: number; at: number; from: string | null; to: string }; } const LEDGER_KEY = "cacheLedger"; function refNum(ref: string): number { - return Number(ref.replace(/\D/g, "")) || 0; + return Number(ref.replace(/\D/g, "")) || 0; } function round1(n: number): number { - return Math.round(n * 10) / 10; + return Math.round(n * 10) / 10; } /** Token offset of the view prefix that survives a fold starting at `ref`: @@ -321,39 +339,39 @@ function round1(n: number): number { * Refs are assigned in message order and never reused (kernel contract), * so numeric order IS view order. */ function prefixTokensBeforeRef(session: Session, ref: string): number { - const byRef = session.state?.messageRefs?.byRef; - const snap = session.state?.tokenSnapshot; - if (!byRef || !snap || refNum(ref) === 0) return 0; - let n = 0; - for (const key of Object.keys(byRef)) { - if (refNum(key) < refNum(ref)) n += snap[key] ?? 0; - } - return n; + const byRef = session.state?.messageRefs?.byRef; + const snap = session.state?.tokenSnapshot; + if (!byRef || !snap || refNum(ref) === 0) return 0; + let n = 0; + for (const key of Object.keys(byRef)) { + if (refNum(key) < refNum(ref)) n += snap[key] ?? 0; + } + return n; } /** #1592-family seam forensics: where two consecutive outbound bodies first * diverged, for samples whose miss has no structural attribution. */ export interface SeamEvent { - seq: number; - at: number; - input: number; - hitPct: number; - /** Byte offset of the first differing byte (a LOWER bound — bodies are - * capped at SEAM_BODY_CAP for storage, so huge prefixes report the cap). */ - lcpBytes: number; - /** Index of the first message element whose serialized form differs. - * `null` = position unknowable (a side clipped at SEAM_BODY_CAP or an - * unparseable body yields no message list to walk) — never a real index; - * renderers must show an unknown token, not 0 (#2339). */ - msgIndex: number | null; - prevMsgs: number; - curMsgs: number; - /** #3023: present iff this event was booked as a CLIENT-side mid-history - * rewrite/insert — the inbound pair itself broke mid-list, so the - * outbound seam is the faithful rebuild of host churn, not a bili - * rebuild artifact. Carries the divergent message's role/length/class - * (never raw content). */ - client?: { idx: number; role: string; len: number; cls: string }; + seq: number; + at: number; + input: number; + hitPct: number; + /** Byte offset of the first differing byte (a LOWER bound — bodies are + * capped at SEAM_BODY_CAP for storage, so huge prefixes report the cap). */ + lcpBytes: number; + /** Index of the first message element whose serialized form differs. + * `null` = position unknowable (a side clipped at SEAM_BODY_CAP or an + * unparseable body yields no message list to walk) — never a real index; + * renderers must show an unknown token, not 0 (#2339). */ + msgIndex: number | null; + prevMsgs: number; + curMsgs: number; + /** #3023: present iff this event was booked as a CLIENT-side mid-history + * rewrite/insert — the inbound pair itself broke mid-list, so the + * outbound seam is the faithful rebuild of host churn, not a bili + * rebuild artifact. Carries the divergent message's role/length/class + * (never raw content). */ + client?: { idx: number; role: string; len: number; cls: string }; } const SEAM_BODY_CAP = 512 * 1024; @@ -378,14 +396,14 @@ const BODY_FULL_CAP = 8 * 1024 * 1024; * `full` keeps the whole payload while it fits BODY_FULL_CAP so divergent * pairs can report their first-diverging byte offset. */ export interface SeamSlot { - str: string; - msgs: number | null; - digest: string; - full: string | null; - /** #2131: credential fingerprint of the headers that carried THIS body out. - * Preserved across byte-identical re-notes (the non-streaming settle - * re-notes the same wireBody without headers in hand). */ - keyFp?: string; + str: string; + msgs: number | null; + digest: string; + full: string | null; + /** #2131: credential fingerprint of the headers that carried THIS body out. + * Preserved across byte-identical re-notes (the non-streaming settle + * re-notes the same wireBody without headers in hand). */ + keyFp?: string; } // #3023: message-count ceiling for the inbound pair. The per-message @@ -404,13 +422,13 @@ const INBOUND_MSG_CAP = 8192; * rebuild seam: only the latter leaves the inbound list prefix-stable while * the outbound body diverges mid-list. */ export interface InboundSlot { - msgs: number; - /** sha256-16 of each message's canonical JSON, in list order. */ - fps: string[]; - /** Parallel to `fps`: role + JSON length + coarse content class of each - * message, recorded so a divergent index can report WHAT the client - * inserted without retaining its text. */ - meta: { role: string; len: number; cls: string }[]; + msgs: number; + /** sha256-16 of each message's canonical JSON, in list order. */ + fps: string[]; + /** Parallel to `fps`: role + JSON length + coarse content class of each + * message, recorded so a divergent index can report WHAT the client + * inserted without retaining its text. */ + meta: { role: string; len: number; cls: string }[]; } /** #3023: capture side of the inbound pair — call at the send chokepoint @@ -418,107 +436,168 @@ export interface InboundSlot { * original (pre-rebuild) message list. Cost is one canonical stringify per * message (≈ one extra body serialization, the outbound path already does * the same order of work hashing the wire body). */ -export function noteInboundMessages(session: Session, msgs: CoreMessage[]): void { - const transient = session.transient ??= {}; - if (msgs.length > INBOUND_MSG_CAP) { - // Too many messages to fingerprint whole: keep the count (so the - // settle-side guard can decline) but drop any stale slot from a - // previous request — a mismatched pair must never be compared. - delete transient.inBody; - transient.inBody = { msgs: msgs.length, fps: [], meta: [] }; - return; - } - const fps: string[] = []; - const meta: { role: string; len: number; cls: string }[] = []; - for (const m of msgs) { - const j = JSON.stringify(m); - fps.push(createHash("sha256").update(j).digest("hex").slice(0, 16)); - meta.push({ role: String((m as { role?: unknown }).role ?? "?"), len: j.length, cls: inboundMessageClass(m) }); - } - transient.inBody = { msgs: msgs.length, fps, meta }; +export function noteInboundMessages( + session: Session, + msgs: CoreMessage[], +): void { + const transient = (session.transient ??= {}); + if (msgs.length > INBOUND_MSG_CAP) { + // Too many messages to fingerprint whole: keep the count (so the + // settle-side guard can decline) but drop any stale slot from a + // previous request — a mismatched pair must never be compared. + delete transient.inBody; + transient.inBody = { msgs: msgs.length, fps: [], meta: [] }; + return; + } + const fps: string[] = []; + const meta: { role: string; len: number; cls: string }[] = []; + for (const m of msgs) { + const j = JSON.stringify(m); + fps.push(createHash("sha256").update(j).digest("hex").slice(0, 16)); + meta.push({ + role: String((m as { role?: unknown }).role ?? "?"), + len: j.length, + cls: inboundMessageClass(m), + }); + } + transient.inBody = { msgs: msgs.length, fps, meta }; } function inboundMessageClass(m: CoreMessage): string { - const r = m as unknown as Record; - if (r.tool_calls !== undefined || r.tool_use !== undefined) return "tool-call"; - const content = r.content; - if (typeof content === "string") return "text"; - if (Array.isArray(content)) { - for (const part of content) { - const t = (part as { type?: unknown } | null)?.type; - if (t === "image" || t === "image_url" || t === "input_image" || t === "inline_data") return "image"; - } - return "text"; - } - return "other"; + const r = m as unknown as Record; + if (r.tool_calls !== undefined || r.tool_use !== undefined) + return "tool-call"; + const content = r.content; + if (typeof content === "string") return "text"; + if (Array.isArray(content)) { + for (const part of content) { + const t = (part as { type?: unknown } | null)?.type; + if ( + t === "image" || + t === "image_url" || + t === "input_image" || + t === "inline_data" + ) + return "image"; + } + return "text"; + } + return "other"; } /** #3023: index of the first message whose fingerprint differs between the * settled pair — `null` when the recorded prefixes are identical (pure * tail-append or byte-stable list). Only meaningful when both sides were * captured whole (msgs <= INBOUND_MSG_CAP, checked by the caller). */ -function firstDivergentInboundMsg(prev: InboundSlot, cur: InboundSlot): number | null { - const n = Math.min(prev.fps.length, cur.fps.length); - for (let i = 0; i < n; i++) { - if (prev.fps[i] !== cur.fps[i]) return i; - } - return null; +function firstDivergentInboundMsg( + prev: InboundSlot, + cur: InboundSlot, +): number | null { + const n = Math.min(prev.fps.length, cur.fps.length); + for (let i = 0; i < n; i++) { + if (prev.fps[i] !== cur.fps[i]) return i; + } + return null; } const lastClientAbort = new WeakMap(); interface ContextObservation { - sessionId: string; - tokens: number; - source: "usage" | "estimate"; - at: number; - generation: string; + sessionId: string; + tokens: number; + source: "usage" | "estimate"; + at: number; + generation: string; } /** Public context provenance is separate from billing and nudge baselines. */ -export function recordContextObservation(session: Session, tokens: number, source: ContextObservation["source"]): void { - if (!Number.isFinite(tokens) || tokens < 0) { - delete session.metadata?.publicContextObservation; - return; - } - session.metadata ??= {}; - session.metadata.publicContextObservation = { sessionId: session.id, tokens, source, at: Date.now(), generation: randomUUID() } satisfies ContextObservation; +export function recordContextObservation( + session: Session, + tokens: number, + source: ContextObservation["source"], +): void { + if (!Number.isFinite(tokens) || tokens < 0) { + delete session.metadata?.publicContextObservation; + return; + } + session.metadata ??= {}; + session.metadata.publicContextObservation = { + sessionId: session.id, + tokens, + source, + at: Date.now(), + generation: randomUUID(), + } satisfies ContextObservation; } -export function currentContextObservation(session: Session): ContextObservation | undefined { - const raw = session.metadata?.publicContextObservation; - if (!raw || typeof raw !== "object") return undefined; - const o = raw as Record; - if (o.sessionId !== session.id || typeof o.tokens !== "number" || !Number.isFinite(o.tokens) || o.tokens < 0 || - (o.source !== "usage" && o.source !== "estimate") || typeof o.at !== "number" || !Number.isFinite(o.at) || o.at < 0 || - typeof o.generation !== "string" || o.generation.length === 0) return undefined; - return { sessionId: session.id, tokens: o.tokens, source: o.source, at: o.at, generation: o.generation }; +export function currentContextObservation( + session: Session, +): ContextObservation | undefined { + const raw = session.metadata?.publicContextObservation; + if (!raw || typeof raw !== "object") return undefined; + const o = raw as Record; + if ( + o.sessionId !== session.id || + typeof o.tokens !== "number" || + !Number.isFinite(o.tokens) || + o.tokens < 0 || + (o.source !== "usage" && o.source !== "estimate") || + typeof o.at !== "number" || + !Number.isFinite(o.at) || + o.at < 0 || + typeof o.generation !== "string" || + o.generation.length === 0 + ) + return undefined; + return { + sessionId: session.id, + tokens: o.tokens, + source: o.source, + at: o.at, + generation: o.generation, + }; } /** #1592 follow-up: stamp the wall-clock time of a client mid-stream abort * (wired at both forward abort chokepoints). The next settle in the same * session reads it to mark abort-correlated samples. */ export function noteClientAbort(session: Session): void { - lastClientAbort.set(session, Date.now()); + lastClientAbort.set(session, Date.now()); } /** #2131: stable fingerprint of the outbound credential — the ONLY form the * key is ever persisted in (raw secrets never reach the ledger, logs or the * web UI). Checks the standard bearer/api-key headers, case-insensitively; * returns undefined when the lane sent no recognized credential header. */ -export function credentialFingerprint(headers: Record | undefined | null): string | undefined { - if (!headers) return undefined; - let cred: string | undefined; - for (const [name, value] of Object.entries(headers)) { - const n = name.toLowerCase(); - if (n === "authorization" || n === "x-api-key" || n === "api-key" || n === "x-goog-api-key") { - // Strip the auth-scheme envelope so "Bearer X" (authorization) and - // a bare "X" (x-api-key) hash to the SAME credential identity. - const v = value.trim().replace(/^Bearer\s+/i, "").trim(); - if (v !== "") { cred = v; break; } - } - } - if (cred === undefined) return undefined; - return "sha256:" + createHash("sha256").update(cred, "utf8").digest("hex").slice(0, 12); +export function credentialFingerprint( + headers: Record | undefined | null, +): string | undefined { + if (!headers) return undefined; + let cred: string | undefined; + for (const [name, value] of Object.entries(headers)) { + const n = name.toLowerCase(); + if ( + n === "authorization" || + n === "x-api-key" || + n === "api-key" || + n === "x-goog-api-key" + ) { + // Strip the auth-scheme envelope so "Bearer X" (authorization) and + // a bare "X" (x-api-key) hash to the SAME credential identity. + const v = value + .trim() + .replace(/^Bearer\s+/i, "") + .trim(); + if (v !== "") { + cred = v; + break; + } + } + } + if (cred === undefined || isProxyManagedCredential(cred)) return undefined; + return ( + "sha256:" + + createHash("sha256").update(cred, "utf8").digest("hex").slice(0, 12) + ); } /** Record the body of the upstream round that is about to be sent. Called at @@ -529,29 +608,42 @@ export function credentialFingerprint(headers: Record | undefine * settle re-noting the same wireBody), the earlier count is kept. `keyFp` is * the outbound credential fingerprint (#2131) — likewise inherited from the * prior slot on a byte-identical re-note without a fresh capture. */ -export function noteForwardedBody(session: Session, body: string, msgs?: number | null, keyFp?: string): void { - // V8 的 substring 可保留整个请求;UTF-16 拷贝独立分配且保留孤立 surrogate。 - const str = Buffer.from(body.slice(0, SEAM_BODY_CAP), "utf16le").toString("utf16le"); - // #2131: hash the FULL body — the capped head alone cannot tell two payloads - // sharing a 512 KiB prefix apart. Re-noting a byte-identical payload (the - // non-streaming settle path) reuses the prior slot's count/full instead of - // re-deriving them. - const digest = createHash("sha256").update(body, "utf8").digest("hex"); - const transient = session.transient ??= {}; - const prior = transient.sentBody; - const samePayload = prior !== undefined && prior.digest === digest; - transient.sentBody = { - str, - msgs: msgs ?? (samePayload ? prior.msgs : null), - digest, - full: body.length <= SEAM_BODY_CAP ? str - : body.length <= BODY_FULL_CAP ? Buffer.from(body, "utf16le").toString("utf16le") - : samePayload ? prior.full : null, - keyFp: keyFp ?? (samePayload ? prior.keyFp : undefined), - }; - // prepare may reuse a measured baseline; this new payload is not measured yet. - if (session.stats.contextTokensSource !== undefined) recordContextObservation(session, session.stats.contextTokens, "estimate"); - else delete session.metadata?.publicContextObservation; +export function noteForwardedBody( + session: Session, + body: string, + msgs?: number | null, + keyFp?: string, +): void { + // V8 的 substring 可保留整个请求;UTF-16 拷贝独立分配且保留孤立 surrogate。 + const str = Buffer.from(body.slice(0, SEAM_BODY_CAP), "utf16le").toString( + "utf16le", + ); + // #2131: hash the FULL body — the capped head alone cannot tell two payloads + // sharing a 512 KiB prefix apart. Re-noting a byte-identical payload (the + // non-streaming settle path) reuses the prior slot's count/full instead of + // re-deriving them. + const digest = createHash("sha256").update(body, "utf8").digest("hex"); + const transient = (session.transient ??= {}); + const prior = transient.sentBody; + const samePayload = prior !== undefined && prior.digest === digest; + transient.sentBody = { + str, + msgs: msgs ?? (samePayload ? prior.msgs : null), + digest, + full: + body.length <= SEAM_BODY_CAP + ? str + : body.length <= BODY_FULL_CAP + ? Buffer.from(body, "utf16le").toString("utf16le") + : samePayload + ? prior.full + : null, + keyFp: keyFp ?? (samePayload ? prior.keyFp : undefined), + }; + // prepare may reuse a measured baseline; this new payload is not measured yet. + if (session.stats.contextTokensSource !== undefined) + recordContextObservation(session, session.stats.contextTokens, "estimate"); + else delete session.metadata?.publicContextObservation; } // #1843 L1: learned per-route image cost. The prior (pixel tile model or bytes) @@ -563,22 +655,22 @@ export function noteForwardedBody(session: Session, body: string, msgs?: number // restart keeps the converged value; invalidated by TTL or by a billing/cap // fingerprint change (a reconfigured route may bill differently). export interface LearnedImageCostEntry { - /** EMA of observed billed tokens per image for this host. */ - cost: number; - /** Samples absorbed into the EMA. */ - seen: number; - /** Last sample wall-clock ms — entries older than the TTL are ignored. */ - ts: number; - /** `${billing}:${cap}` fingerprint captured with the sample. */ - fp: string; + /** EMA of observed billed tokens per image for this host. */ + cost: number; + /** Samples absorbed into the EMA. */ + seen: number; + /** Last sample wall-clock ms — entries older than the TTL are ignored. */ + ts: number; + /** `${billing}:${cap}` fingerprint captured with the sample. */ + fp: string; } interface ForwardedImageFacts { - nImages: number; - /** Text-side estimate of the forwarded payload (messages + wire overhead) — - * whatever the usage total bills besides the images. */ - textSide: number; - host: string; - fp: string; + nImages: number; + /** Text-side estimate of the forwarded payload (messages + wire overhead) — + * whatever the usage total bills besides the images. */ + textSide: number; + host: string; + fp: string; } const LEARNED_IMAGE_COST_TTL_MS = 24 * 60 * 60 * 1000; const LEARNED_IMAGE_COST_ALPHA = 0.5; @@ -588,77 +680,121 @@ const imageFactsLastSent = new WeakMap(); /** Capture side of L1: called at the same send chokepoints as noteForwardedBody * with the image facts of the round about to be sent. The next settleUsageReport * consumes exactly this entry (same pairing guarantee as the seam forensics). */ -export function noteForwardedImageFacts(session: Session, facts: ForwardedImageFacts): void { - imageFactsLastSent.set(session, facts); +export function noteForwardedImageFacts( + session: Session, + facts: ForwardedImageFacts, +): void { + imageFactsLastSent.set(session, facts); } function settleImageLearning(session: Session, billedTotal: number): void { - const facts = imageFactsLastSent.get(session); - if (!facts) return; - imageFactsLastSent.delete(session); - if (facts.nImages <= 0 || billedTotal <= 0) return; - const observed = billedTotal - facts.textSide; - if (observed <= 0) return; // text estimate overshot the bill — no signal - const per = observed / facts.nImages; - if (!(per >= 1 && per <= LEARNED_PER_IMAGE_MAX)) return; // out-of-band sample - const store = (session.metadata.learnedImageCosts ?? {}) as Record; - const prev = store[facts.host]; - const cost = prev && typeof prev.cost === "number" ? prev.cost * (1 - LEARNED_IMAGE_COST_ALPHA) + per * LEARNED_IMAGE_COST_ALPHA : per; - store[facts.host] = { cost, seen: (prev?.seen ?? 0) + 1, ts: Date.now(), fp: facts.fp }; - session.metadata.learnedImageCosts = store; - markDirty(session); + const facts = imageFactsLastSent.get(session); + if (!facts) return; + imageFactsLastSent.delete(session); + if (facts.nImages <= 0 || billedTotal <= 0) return; + const observed = billedTotal - facts.textSide; + if (observed <= 0) return; // text estimate overshot the bill — no signal + const per = observed / facts.nImages; + if (!(per >= 1 && per <= LEARNED_PER_IMAGE_MAX)) return; // out-of-band sample + const store = (session.metadata.learnedImageCosts ?? {}) as Record< + string, + LearnedImageCostEntry + >; + const prev = store[facts.host]; + const cost = + prev && typeof prev.cost === "number" + ? prev.cost * (1 - LEARNED_IMAGE_COST_ALPHA) + + per * LEARNED_IMAGE_COST_ALPHA + : per; + store[facts.host] = { + cost, + seen: (prev?.seen ?? 0) + 1, + ts: Date.now(), + fp: facts.fp, + }; + session.metadata.learnedImageCosts = store; + markDirty(session); } /** Consume side of L1: the learned reserve for THIS payload — learned per-image * cost x current image count, or undefined when no fresh matching evidence * exists (caller then falls back to the prior-based estimate). */ -export function learnedImageReserve(session: Session, host: string, nImages: number, fp: string, cap: number): number | undefined { - if (nImages <= 0) return undefined; - const entry = (session.metadata.learnedImageCosts as Record | undefined)?.[host]; - if (!entry || typeof entry.cost !== "number" || entry.seen < 1) return undefined; - if (Date.now() - entry.ts > LEARNED_IMAGE_COST_TTL_MS) return undefined; - if (entry.fp !== fp) return undefined; // billing/cap reconfigured since learning - const per = cap > 0 ? Math.min(entry.cost, cap) : entry.cost; - return per * nImages; +export function learnedImageReserve( + session: Session, + host: string, + nImages: number, + fp: string, + cap: number, +): number | undefined { + if (nImages <= 0) return undefined; + const entry = ( + session.metadata.learnedImageCosts as + | Record + | undefined + )?.[host]; + if (!entry || typeof entry.cost !== "number" || entry.seen < 1) + return undefined; + if (Date.now() - entry.ts > LEARNED_IMAGE_COST_TTL_MS) return undefined; + if (entry.fp !== fp) return undefined; // billing/cap reconfigured since learning + const per = cap > 0 ? Math.min(entry.cost, cap) : entry.cost; + return per * nImages; } -function seamLcp(a: string, b: string): { lcpBytes: number; msgIndex: number | null; prevMsgs: number; curMsgs: number } { - let lcp = 0; - const n = Math.min(a.length, b.length); - while (lcp < n && a.charCodeAt(lcp) === b.charCodeAt(lcp)) lcp++; - // #2339: the message array lives under `messages` (Anthropic/chat), `input` - // (Responses) or `contents` (Google native) — same caliber as the send-time - // count captures (server.ts / loop/core.ts). Reading only `.messages` made - // every Responses/Google pair parse to zero messages: msgIndex degenerated - // to a fallback 0 that rendered as a real "message[0]", and the count-based - // classification arms went dead on those wires. - const msgsOf = (s: string): unknown[] => { - try { - const p = JSON.parse(s) as { messages?: unknown; input?: unknown; contents?: unknown }; - const arr = p.messages ?? p.input ?? p.contents; - return Array.isArray(arr) ? arr : []; - } catch { - return []; - } - }; - const ma = msgsOf(a); - const mb = msgsOf(b); - let i = 0; - const eq = (x: unknown, y: unknown): boolean => JSON.stringify(x) === JSON.stringify(y); - while (i < Math.min(ma.length, mb.length) && eq(ma[i], mb[i])) i++; - // null = position unknowable (neither side yielded a message list — capped or - // unparseable body). A bare 0 would be a real head-break index, not a fallback. - return { lcpBytes: lcp, msgIndex: ma.length > 0 && mb.length > 0 ? i : null, prevMsgs: ma.length, curMsgs: mb.length }; +function seamLcp( + a: string, + b: string, +): { + lcpBytes: number; + msgIndex: number | null; + prevMsgs: number; + curMsgs: number; +} { + let lcp = 0; + const n = Math.min(a.length, b.length); + while (lcp < n && a.charCodeAt(lcp) === b.charCodeAt(lcp)) lcp++; + // #2339: the message array lives under `messages` (Anthropic/chat), `input` + // (Responses) or `contents` (Google native) — same caliber as the send-time + // count captures (server.ts / loop/core.ts). Reading only `.messages` made + // every Responses/Google pair parse to zero messages: msgIndex degenerated + // to a fallback 0 that rendered as a real "message[0]", and the count-based + // classification arms went dead on those wires. + const msgsOf = (s: string): unknown[] => { + try { + const p = JSON.parse(s) as { + messages?: unknown; + input?: unknown; + contents?: unknown; + }; + const arr = p.messages ?? p.input ?? p.contents; + return Array.isArray(arr) ? arr : []; + } catch { + return []; + } + }; + const ma = msgsOf(a); + const mb = msgsOf(b); + let i = 0; + const eq = (x: unknown, y: unknown): boolean => + JSON.stringify(x) === JSON.stringify(y); + while (i < Math.min(ma.length, mb.length) && eq(ma[i], mb[i])) i++; + // null = position unknowable (neither side yielded a message list — capped or + // unparseable body). A bare 0 would be a real head-break index, not a fallback. + return { + lcpBytes: lcp, + msgIndex: ma.length > 0 && mb.length > 0 ? i : null, + prevMsgs: ma.length, + curMsgs: mb.length, + }; } // #2131: byte-LCP WITHOUT the JSON parse seamLcp does — the per-call stability // check runs on every settled pair and must stay cheap on multi-MiB bodies // (message-level detail belongs to detectSeam's forensics path only). function byteLcp(a: string, b: string): number { - let lcp = 0; - const n = Math.min(a.length, b.length); - while (lcp < n && a.charCodeAt(lcp) === b.charCodeAt(lcp)) lcp++; - return lcp; + let lcp = 0; + const n = Math.min(a.length, b.length); + while (lcp < n && a.charCodeAt(lcp) === b.charCodeAt(lcp)) lcp++; + return lcp; } // #2982: byte offset of the CLOSING bracket terminating the top-level @@ -669,280 +805,428 @@ function byteLcp(a: string, b: string): number { // and one linear pass keeps multi-MiB bodies cheap. Runs only on pairs that // would otherwise class "mid" — the hot path never pays for it. function messagesArrayCloseOffset(body: string): number | null { - const n = body.length; - let depth = 0; // object/array nesting depth - let inStr = false; - let esc = false; - let want = -1; // depth at which the tracked array closes (-1 = not tracking) - let keyAt = -1; // opening-quote offset of a candidate top-level key - for (let i = 0; i < n; i++) { - const c = body.charCodeAt(i); - if (inStr) { - if (esc) esc = false; - else if (c === 92) esc = true; // backslash - else if (c === 34) { - inStr = false; - if (keyAt >= 0) { - // +1/-1 strip the surrounding quotes from the captured range. - const key = body.slice(keyAt + 1, i); - keyAt = -1; - // A top-level string VALUE is also seen at depth 1 — the - // following-colon check below is what separates keys from it. - if (depth === 1 && (key === "messages" || key === "input" || key === "contents")) { - let j = i + 1; - while (j < n && body.charCodeAt(j) <= 32) j++; - if (body.charCodeAt(j) === 58) { // ':' - j++; - while (j < n && body.charCodeAt(j) <= 32) j++; - if (body.charCodeAt(j) === 91) want = depth + 1; // '[' - } - } - } - } - continue; - } - if (c === 34) { inStr = true; keyAt = depth === 1 ? i : -1; continue; } - if (c === 123 || c === 91) { depth++; continue; } - if (c === 125 || c === 93) { - if (want !== -1 && c === 93 && depth === want) return i; - depth--; - continue; - } - } - return null; + const n = body.length; + let depth = 0; // object/array nesting depth + let inStr = false; + let esc = false; + let want = -1; // depth at which the tracked array closes (-1 = not tracking) + let keyAt = -1; // opening-quote offset of a candidate top-level key + for (let i = 0; i < n; i++) { + const c = body.charCodeAt(i); + if (inStr) { + if (esc) esc = false; + else if (c === 92) + esc = true; // backslash + else if (c === 34) { + inStr = false; + if (keyAt >= 0) { + // +1/-1 strip the surrounding quotes from the captured range. + const key = body.slice(keyAt + 1, i); + keyAt = -1; + // A top-level string VALUE is also seen at depth 1 — the + // following-colon check below is what separates keys from it. + if ( + depth === 1 && + (key === "messages" || key === "input" || key === "contents") + ) { + let j = i + 1; + while (j < n && body.charCodeAt(j) <= 32) j++; + if (body.charCodeAt(j) === 58) { + // ':' + j++; + while (j < n && body.charCodeAt(j) <= 32) j++; + if (body.charCodeAt(j) === 91) want = depth + 1; // '[' + } + } + } + } + continue; + } + if (c === 34) { + inStr = true; + keyAt = depth === 1 ? i : -1; + continue; + } + if (c === 123 || c === 91) { + depth++; + continue; + } + if (c === 125 || c === 93) { + if (want !== -1 && c === 93 && depth === want) return i; + depth--; + } + } + return null; } function detectSeam(session: Session, led: CacheLedger): void { - const line = led.lines[led.lines.length - 1]; - if (!line || line.unk === 1 || line.missed <= 0) return; - // #1891: a no-baseline first bill has no prior prefix to break — its miss is - // initial content. The rebooking above already zeroes its tr; this guard also - // keeps it out of the rewind/provider-side body-pair classifications. - if (line.nb === 1) return; - // Abort correlation is counted for EVERY missed sample, independent of - // structural attribution — abort/retry churn is orthogonal evidence. - const abortAt = lastClientAbort.get(session); - if (abortAt !== undefined && Math.abs(line.at - abortAt) < 30_000) { - line.abortedNear = 1; - led.agg.abortCorrelated += 1; - } - // Structural attributions already explain the miss — not a seam candidate. `cause` additionally covers - // post-switch cold-tail continuations (they carry no sw/pw/uw flag); legacy lines lack it and keep old behavior. - if (line.sw === 1 || line.pw === 1 || line.uw === 1 || line.rs === 1 || line.cause !== undefined || line.foldSeq !== null) return; - // Substantive unexplained residual only: a big ttlRepay slice of a big bill. - if (!(line.tr > 8192 && line.tr > 0.3 * line.input)) return; - const agg = led.agg; - const cur = session.transient?.sentBody; - const prev = session.transient?.settledBody; - // #2929: split the provider-side arms by idle gap — a byte-stable miss - // after a long idle is normal TTL expiry; the same miss seconds after the - // previous request is the abnormal provider-side failure. - const prevSampleAt = led.lines.length >= 2 ? led.lines[led.lines.length - 2].at : line.at; - const ttlExpired = line.at - prevSampleAt > PROVIDER_TTL_GAP_MS; - const bookProvider = (): void => { - line.prov = ttlExpired ? "ttl" : "side"; - if (ttlExpired) { - agg.providerTtlMisses += 1; - agg.providerTtlMissed += line.tr; - } else { - agg.providerSideMisses += 1; - agg.providerSideMissed += line.tr; - } - }; - let f: ReturnType | undefined; - if (cur !== undefined && prev !== undefined) { - f = seamLcp(prev.str, cur.str); - // #2131: a body stored at full length is readable; one clipped at - // SEAM_BODY_CAP parses to zero messages, so parse-derived arms below - // only decide pairs where that side is under the cap. - const prevCapped = prev.str.length >= SEAM_BODY_CAP; - const curCapped = cur.str.length >= SEAM_BODY_CAP; - // Client reverted/trimmed history: the miss is the sanctioned - // one-time re-bill of the retained prefix (or the gap's TTL). Only - // trust the parsed counts when BOTH sides are fully stored — a side - // clipped at SEAM_BODY_CAP parses to zero messages and would fake a - // shrink (or hide one); those pairs go to the #2131 byte/count arms. - if (!prevCapped && !curCapped && f.prevMsgs > 0 && f.curMsgs < f.prevMsgs) { - line.prov = "rewind"; - agg.rewinds += 1; - agg.rewindMissed += line.tr; - return; - } - if (cur.str.length < prev.str.length && f.lcpBytes >= cur.str.length - 4) { - // #2131: the WHOLE current payload survives inside the previous - // one — a JSON array only diverges from its own longer superstring - // in the closing-bracket region (the 4-byte tolerance), so this is - // a sanctioned client-side trim/fold re-bill of the retained prefix, - // NOT a provider miss. Must run before the byte-stable arm, which - // would otherwise read "all of cur survives" and book it provider-side. - line.prov = "rewind"; - agg.rewinds += 1; - agg.rewindMissed += line.tr; - return; - } - if (f.lcpBytes >= cur.str.length) { - // Wire was byte-stable against the previous request — the - // upstream simply did not serve its cache. Provider-side. Above - // the cap this covers the identical-recorded-head case: anything - // past SEAM_BODY_CAP is beyond recorded evidence either way. - bookProvider(); - return; - } - // #2059: tail-append turns — the previous request's ENTIRE message list - // survives byte-identically as this one's prefix (msgIndex == prevMsgs) - // and only the tail grew, so there is NO mid-history break: provider-side - // again. The byte-LCP test above can't see it (it demands the whole body - // match, which a growing conversation never satisfies), so before this the - // common append+no-cache case falsely cried seam. Both bodies must be - // uncapped: one truncated at SEAM_BODY_CAP parses to zero messages and - // would fake the msgIndex == prevMsgs == 0 signature; prevMsgs > 0 keeps - // an empty prior list out. - if (!prevCapped && !curCapped && f.prevMsgs > 0 && f.msgIndex === f.prevMsgs && f.curMsgs > f.prevMsgs) { - bookProvider(); - return; - } - if (prev.str.length < cur.str.length && f.lcpBytes >= prev.str.length - 4) { - // #2131: the WHOLE previous payload survives inside the longer - // current one (JSON appends diverge only in the previous body's - // closing-bracket region — the 4-byte tolerance). Under the cap the - // #2059 arm above already decided clean appends, so reaching here - // means a clipped side was involved and the parsed counts are blind; - // the exact counts captured at send time must prove pure tail - // growth. Without them the pair is indistinguishable from a real - // break and falls through to suspect. - if (prev.msgs !== null && cur.msgs !== null && cur.msgs > prev.msgs) { - bookProvider(); - return; - } - } - // No decisive byte/count shape (visible break in the recorded region, - // or capped evidence without exact counts): suspect — unless the CLIENT - // pair proves the break is host-owned (#3023). - } - // #3023: client-side mid-history rewrite — the client's own resent list - // broke mid-list (insert/rewrite at index k, k < min(prevMsgs, curMsgs)), - // so bili's faithful rebuild carried the break to the wire and the miss - // belongs to the host (another plugin, paste hoisting, re-render), NOT to - // a bili rebuild seam. Requires BOTH inbound slots captured whole - // (msgs <= INBOUND_MSG_CAP — an above-cap list cannot prove where it - // broke, and a missing lane capture must keep the legacy bucket). - const curIn = session.transient?.inBody; - const prevIn = session.transient?.settledInBody; - if (curIn !== undefined && prevIn !== undefined && curIn.msgs <= INBOUND_MSG_CAP && prevIn.msgs <= INBOUND_MSG_CAP) { - const k = firstDivergentInboundMsg(prevIn, curIn); - if (k !== null && k < Math.min(prevIn.msgs, curIn.msgs)) { - line.prov = "client"; - agg.clientInserts += 1; - agg.clientInsertMissed += line.tr; - const m = curIn.meta[k] ?? { role: "?", len: 0, cls: "?" }; - if (cur !== undefined && prev !== undefined) { - if (led.seamEvents !== undefined && led.seamEvents.length >= SEAM_EVENTS_CAP) led.seamEvents.shift(); - const forensics = f ?? seamLcp(prev.str, cur.str); - (led.seamEvents ?? (led.seamEvents = [])).push({ seq: line.seq, at: line.at, input: line.input, hitPct: line.hitPct ?? 0, ...forensics, prevMsgs: prev.msgs ?? forensics.prevMsgs, curMsgs: cur.msgs ?? forensics.curMsgs, client: { idx: k, role: m.role, len: m.len, cls: m.cls } }); - } - if (agg.clientInserts === 1) { - loggerLog("warn", `[${session.id}] [cache-seam] client-side mid-history rewrite: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok) — the client's resent history diverged at inbound message[${k}] of ${prevIn.msgs}→${curIn.msgs} (${m.role}/${m.cls}, ${m.len}B JSON), so the wire break is the host's own churn, not a bili rebuild (#3023)`); - } - return; - } - // Inbound prefix-stable or a clean tail boundary: the outbound - // mid-list break is bili-side — fall through to the seam bucket. - } - agg.seamSuspects += 1; - agg.seamMissed += line.tr; - line.seam = 1; - if (cur !== undefined && prev !== undefined && led.seamEvents !== undefined && led.seamEvents.length >= SEAM_EVENTS_CAP) { - led.seamEvents.shift(); - } - if (cur !== undefined && prev !== undefined) { - const forensics = f ?? seamLcp(prev.str, cur.str); - const ev: SeamEvent = { seq: line.seq, at: line.at, input: line.input, hitPct: line.hitPct ?? 0, ...forensics, prevMsgs: prev.msgs ?? forensics.prevMsgs, curMsgs: cur.msgs ?? forensics.curMsgs }; - (led.seamEvents ?? (led.seamEvents = [])).push(ev); - if (agg.seamSuspects === 1) { - loggerLog("warn", `[${session.id}] [cache-seam] suspected mid-history prefix break: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok, no fold/switch/restart attribution); first divergence at byte ${ev.lcpBytes}, message[${ev.msgIndex ?? "?"}] of ${ev.prevMsgs}→${ev.curMsgs} — see /acp-cache for the seam section`); - } - } else if (agg.seamSuspects === 1) { - loggerLog("warn", `[${session.id}] [cache-seam] suspected mid-history prefix break: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok, no fold/switch/restart attribution); outbound body pair unavailable (lane without body capture) — aggregate flag only`); - } + const line = led.lines[led.lines.length - 1]; + if (!line || line.unk === 1 || line.missed <= 0) return; + // #1891: a no-baseline first bill has no prior prefix to break — its miss is + // initial content. The rebooking above already zeroes its tr; this guard also + // keeps it out of the rewind/provider-side body-pair classifications. + if (line.nb === 1) return; + // Abort correlation is counted for EVERY missed sample, independent of + // structural attribution — abort/retry churn is orthogonal evidence. + const abortAt = lastClientAbort.get(session); + if (abortAt !== undefined && Math.abs(line.at - abortAt) < 30_000) { + line.abortedNear = 1; + led.agg.abortCorrelated += 1; + } + // Structural attributions already explain the miss — not a seam candidate. `cause` additionally covers + // post-switch cold-tail continuations (they carry no sw/pw/uw flag); legacy lines lack it and keep old behavior. + if ( + line.sw === 1 || + line.pw === 1 || + line.uw === 1 || + line.rs === 1 || + line.cause !== undefined || + line.foldSeq !== null + ) + return; + // Substantive unexplained residual only: a big ttlRepay slice of a big bill. + if (!(line.tr > 8192 && line.tr > 0.3 * line.input)) return; + const agg = led.agg; + const cur = session.transient?.sentBody; + const prev = session.transient?.settledBody; + // #2929: split the provider-side arms by idle gap — a byte-stable miss + // after a long idle is normal TTL expiry; the same miss seconds after the + // previous request is the abnormal provider-side failure. + const prevSampleAt = + led.lines.length >= 2 ? led.lines[led.lines.length - 2].at : line.at; + const ttlExpired = line.at - prevSampleAt > PROVIDER_TTL_GAP_MS; + const bookProvider = (): void => { + line.prov = ttlExpired ? "ttl" : "side"; + if (ttlExpired) { + agg.providerTtlMisses += 1; + agg.providerTtlMissed += line.tr; + } else { + agg.providerSideMisses += 1; + agg.providerSideMissed += line.tr; + } + }; + let f: ReturnType | undefined; + if (cur !== undefined && prev !== undefined) { + f = seamLcp(prev.str, cur.str); + // #2131: a body stored at full length is readable; one clipped at + // SEAM_BODY_CAP parses to zero messages, so parse-derived arms below + // only decide pairs where that side is under the cap. + const prevCapped = prev.str.length >= SEAM_BODY_CAP; + const curCapped = cur.str.length >= SEAM_BODY_CAP; + // Client reverted/trimmed history: the miss is the sanctioned + // one-time re-bill of the retained prefix (or the gap's TTL). Only + // trust the parsed counts when BOTH sides are fully stored — a side + // clipped at SEAM_BODY_CAP parses to zero messages and would fake a + // shrink (or hide one); those pairs go to the #2131 byte/count arms. + if (!prevCapped && !curCapped && f.prevMsgs > 0 && f.curMsgs < f.prevMsgs) { + line.prov = "rewind"; + agg.rewinds += 1; + agg.rewindMissed += line.tr; + return; + } + if (cur.str.length < prev.str.length && f.lcpBytes >= cur.str.length - 4) { + // #2131: the WHOLE current payload survives inside the previous + // one — a JSON array only diverges from its own longer superstring + // in the closing-bracket region (the 4-byte tolerance), so this is + // a sanctioned client-side trim/fold re-bill of the retained prefix, + // NOT a provider miss. Must run before the byte-stable arm, which + // would otherwise read "all of cur survives" and book it provider-side. + line.prov = "rewind"; + agg.rewinds += 1; + agg.rewindMissed += line.tr; + return; + } + if (f.lcpBytes >= cur.str.length) { + // Wire was byte-stable against the previous request — the + // upstream simply did not serve its cache. Provider-side. Above + // the cap this covers the identical-recorded-head case: anything + // past SEAM_BODY_CAP is beyond recorded evidence either way. + bookProvider(); + return; + } + // #2059: tail-append turns — the previous request's ENTIRE message list + // survives byte-identically as this one's prefix (msgIndex == prevMsgs) + // and only the tail grew, so there is NO mid-history break: provider-side + // again. The byte-LCP test above can't see it (it demands the whole body + // match, which a growing conversation never satisfies), so before this the + // common append+no-cache case falsely cried seam. Both bodies must be + // uncapped: one truncated at SEAM_BODY_CAP parses to zero messages and + // would fake the msgIndex == prevMsgs == 0 signature; prevMsgs > 0 keeps + // an empty prior list out. + if ( + !prevCapped && + !curCapped && + f.prevMsgs > 0 && + f.msgIndex === f.prevMsgs && + f.curMsgs > f.prevMsgs + ) { + bookProvider(); + return; + } + if (prev.str.length < cur.str.length && f.lcpBytes >= prev.str.length - 4) { + // #2131: the WHOLE previous payload survives inside the longer + // current one (JSON appends diverge only in the previous body's + // closing-bracket region — the 4-byte tolerance). Under the cap the + // #2059 arm above already decided clean appends, so reaching here + // means a clipped side was involved and the parsed counts are blind; + // the exact counts captured at send time must prove pure tail + // growth. Without them the pair is indistinguishable from a real + // break and falls through to suspect. + if (prev.msgs !== null && cur.msgs !== null && cur.msgs > prev.msgs) { + bookProvider(); + return; + } + } + // No decisive byte/count shape (visible break in the recorded region, + // or capped evidence without exact counts): suspect — unless the CLIENT + // pair proves the break is host-owned (#3023). + } + // #3023: client-side mid-history rewrite — the client's own resent list + // broke mid-list (insert/rewrite at index k, k < min(prevMsgs, curMsgs)), + // so bili's faithful rebuild carried the break to the wire and the miss + // belongs to the host (another plugin, paste hoisting, re-render), NOT to + // a bili rebuild seam. Requires BOTH inbound slots captured whole + // (msgs <= INBOUND_MSG_CAP — an above-cap list cannot prove where it + // broke, and a missing lane capture must keep the legacy bucket). + const curIn = session.transient?.inBody; + const prevIn = session.transient?.settledInBody; + if ( + curIn !== undefined && + prevIn !== undefined && + curIn.msgs <= INBOUND_MSG_CAP && + prevIn.msgs <= INBOUND_MSG_CAP + ) { + const k = firstDivergentInboundMsg(prevIn, curIn); + if (k !== null && k < Math.min(prevIn.msgs, curIn.msgs)) { + line.prov = "client"; + agg.clientInserts += 1; + agg.clientInsertMissed += line.tr; + const m = curIn.meta[k] ?? { role: "?", len: 0, cls: "?" }; + if (cur !== undefined && prev !== undefined) { + if ( + led.seamEvents !== undefined && + led.seamEvents.length >= SEAM_EVENTS_CAP + ) + led.seamEvents.shift(); + const forensics = f ?? seamLcp(prev.str, cur.str); + (led.seamEvents ?? (led.seamEvents = [])).push({ + seq: line.seq, + at: line.at, + input: line.input, + hitPct: line.hitPct ?? 0, + ...forensics, + prevMsgs: prev.msgs ?? forensics.prevMsgs, + curMsgs: cur.msgs ?? forensics.curMsgs, + client: { idx: k, role: m.role, len: m.len, cls: m.cls }, + }); + } + if (agg.clientInserts === 1) { + loggerLog( + "warn", + `[${session.id}] [cache-seam] client-side mid-history rewrite: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok) — the client's resent history diverged at inbound message[${k}] of ${prevIn.msgs}→${curIn.msgs} (${m.role}/${m.cls}, ${m.len}B JSON), so the wire break is the host's own churn, not a bili rebuild (#3023)`, + ); + } + return; + } + // Inbound prefix-stable or a clean tail boundary: the outbound + // mid-list break is bili-side — fall through to the seam bucket. + } + agg.seamSuspects += 1; + agg.seamMissed += line.tr; + line.seam = 1; + if ( + cur !== undefined && + prev !== undefined && + led.seamEvents !== undefined && + led.seamEvents.length >= SEAM_EVENTS_CAP + ) { + led.seamEvents.shift(); + } + if (cur !== undefined && prev !== undefined) { + const forensics = f ?? seamLcp(prev.str, cur.str); + const ev: SeamEvent = { + seq: line.seq, + at: line.at, + input: line.input, + hitPct: line.hitPct ?? 0, + ...forensics, + prevMsgs: prev.msgs ?? forensics.prevMsgs, + curMsgs: cur.msgs ?? forensics.curMsgs, + }; + (led.seamEvents ?? (led.seamEvents = [])).push(ev); + if (agg.seamSuspects === 1) { + loggerLog( + "warn", + `[${session.id}] [cache-seam] suspected mid-history prefix break: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok, no fold/switch/restart attribution); first divergence at byte ${ev.lcpBytes}, message[${ev.msgIndex ?? "?"}] of ${ev.prevMsgs}→${ev.curMsgs} — see /acp-cache for the seam section`, + ); + } + } else if (agg.seamSuspects === 1) { + loggerLog( + "warn", + `[${session.id}] [cache-seam] suspected mid-history prefix break: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok, no fold/switch/restart attribution); outbound body pair unavailable (lane without body capture) — aggregate flag only`, + ); + } } export function getCacheLedger(session: Session): CacheLedger { - const meta = session.metadata ?? (session.metadata = {}); - const existing = meta[LEDGER_KEY] as CacheLedger | undefined; - if (existing && existing.v === 1) { - // Ledgers persisted before #1535/#1536 lack the newer counters — normalize - // in place so later arithmetic never sees undefined. - const g = existing.agg; - for (const key of [ - "switches", "switchMissed", "keySwitches", "keySwitchMissed", "promptSwitches", "promptSwitchMissed", "projSwitches", "projSwitchMissed", "wireSwitches", "wireSwitchMissed", - "upstreamSwitches", "upstreamSwitchMissed", "restartDrops", - "restartDropMissed", "attributedMissed", "unknownSamples", "unknownInput", - "nbSamples", "nbInput", - "seamSuspects", "seamMissed", - "providerSideMisses", "providerSideMissed", "providerTtlMisses", "providerTtlMissed", "rewinds", "rewindMissed", "abortCorrelated", "clientInserts", "clientInsertMissed", - ] as const) { - if (typeof g[key] !== "number") g[key] = 0; - } - return existing; - } - // Bootstrap: blocks already present predate ledger tracking — record - // their high-water mark WITHOUT fold events (no usage baseline existed). - const maxBlockId = (session.state?.blocks ?? []).reduce((n, b) => Math.max(n, refNum(b.blockId)), 0); - const led: CacheLedger = { - v: 1, - lastBlockId: maxBlockId, - consumedFoldSeq: 0, - sampleSeq: 0, - foldSeqCounter: 0, - folds: [], - lines: [], - agg: { requests: 0, input: 0, cached: 0, output: 0, nc: 0, cr: 0, tr: 0, switches: 0, switchMissed: 0, keySwitches: 0, keySwitchMissed: 0, promptSwitches: 0, promptSwitchMissed: 0, projSwitches: 0, projSwitchMissed: 0, wireSwitches: 0, wireSwitchMissed: 0, upstreamSwitches: 0, upstreamSwitchMissed: 0, restartDrops: 0, restartDropMissed: 0, attributedMissed: 0, unknownSamples: 0, unknownInput: 0, nbSamples: 0, nbInput: 0, seamSuspects: 0, seamMissed: 0, providerSideMisses: 0, providerSideMissed: 0, providerTtlMisses: 0, providerTtlMissed: 0, rewinds: 0, rewindMissed: 0, abortCorrelated: 0, clientInserts: 0, clientInsertMissed: 0 }, - }; - meta[LEDGER_KEY] = led; - return led; + const meta = session.metadata ?? (session.metadata = {}); + const existing = meta[LEDGER_KEY] as CacheLedger | undefined; + if (existing && existing.v === 1) { + // Ledgers persisted before #1535/#1536 lack the newer counters — normalize + // in place so later arithmetic never sees undefined. + const g = existing.agg; + for (const key of [ + "switches", + "switchMissed", + "keySwitches", + "keySwitchMissed", + "promptSwitches", + "promptSwitchMissed", + "projSwitches", + "projSwitchMissed", + "wireSwitches", + "wireSwitchMissed", + "upstreamSwitches", + "upstreamSwitchMissed", + "restartDrops", + "restartDropMissed", + "attributedMissed", + "unknownSamples", + "unknownInput", + "nbSamples", + "nbInput", + "seamSuspects", + "seamMissed", + "providerSideMisses", + "providerSideMissed", + "providerTtlMisses", + "providerTtlMissed", + "rewinds", + "rewindMissed", + "abortCorrelated", + "clientInserts", + "clientInsertMissed", + ] as const) { + if (typeof g[key] !== "number") g[key] = 0; + } + return existing; + } + // Bootstrap: blocks already present predate ledger tracking — record + // their high-water mark WITHOUT fold events (no usage baseline existed). + const maxBlockId = (session.state?.blocks ?? []).reduce( + (n, b) => Math.max(n, refNum(b.blockId)), + 0, + ); + const led: CacheLedger = { + v: 1, + lastBlockId: maxBlockId, + consumedFoldSeq: 0, + sampleSeq: 0, + foldSeqCounter: 0, + folds: [], + lines: [], + agg: { + requests: 0, + input: 0, + cached: 0, + output: 0, + nc: 0, + cr: 0, + tr: 0, + switches: 0, + switchMissed: 0, + keySwitches: 0, + keySwitchMissed: 0, + promptSwitches: 0, + promptSwitchMissed: 0, + projSwitches: 0, + projSwitchMissed: 0, + wireSwitches: 0, + wireSwitchMissed: 0, + upstreamSwitches: 0, + upstreamSwitchMissed: 0, + restartDrops: 0, + restartDropMissed: 0, + attributedMissed: 0, + unknownSamples: 0, + unknownInput: 0, + nbSamples: 0, + nbInput: 0, + seamSuspects: 0, + seamMissed: 0, + providerSideMisses: 0, + providerSideMissed: 0, + providerTtlMisses: 0, + providerTtlMissed: 0, + rewinds: 0, + rewindMissed: 0, + abortCorrelated: 0, + clientInserts: 0, + clientInsertMissed: 0, + }, + }; + meta[LEDGER_KEY] = led; + return led; } -function pushFold(led: CacheLedger, f: Omit): void { - // Freeze k = samples since each open fold (#1286): samples arrive in - // order, so at this instant the count equals the batch-path - // turnsToNextFold window (f.at < s.at <= nextFold.at); requestsAfter - // keeps growing afterward to the full post-fold total. - for (const open of led.folds) { - if (open.k === null) open.k = open.requestsAfter; - } - led.foldSeqCounter += 1; - led.folds.push({ ...f, seq: led.foldSeqCounter, T: 0, hPct: null, requestsAfter: 0, k: null }); +function pushFold( + led: CacheLedger, + f: Omit, +): void { + // Freeze k = samples since each open fold (#1286): samples arrive in + // order, so at this instant the count equals the batch-path + // turnsToNextFold window (f.at < s.at <= nextFold.at); requestsAfter + // keeps growing afterward to the full post-fold total. + for (const open of led.folds) { + if (open.k === null) open.k = open.requestsAfter; + } + led.foldSeqCounter += 1; + led.folds.push({ + ...f, + seq: led.foldSeqCounter, + T: 0, + hPct: null, + requestsAfter: 0, + k: null, + }); } /** Record compression folds materialized as new kernel blocks. Proxy mode * calls this eagerly at the applyCompression site; plugin mode folds are * caught lazily by detectNewFolds() via the blockId high-water mark. */ -export function recordCacheFoldsFromBlocks(session: Session, blocks: CompressionBlock[], geo?: { V?: number; Vp?: number }): void { - if (blocks.length === 0) return; - const led = getCacheLedger(session); - for (const b of blocks) { - const id = refNum(b.blockId); - if (id <= led.lastBlockId) continue; - pushFold(led, { - at: b.createdAt || Date.now(), - S: b.compressedTokens, - sigma: Math.ceil(b.summary.length / 4), - X: b.startRef ? prefixTokensBeforeRef(session, b.startRef) : undefined, - V: geo?.V, - Vp: geo?.Vp, - bid: b.blockId, - }); - led.lastBlockId = Math.max(led.lastBlockId, id); - } +export function recordCacheFoldsFromBlocks( + session: Session, + blocks: CompressionBlock[], + geo?: { V?: number; Vp?: number }, +): void { + if (blocks.length === 0) return; + const led = getCacheLedger(session); + for (const b of blocks) { + const id = refNum(b.blockId); + if (id <= led.lastBlockId) continue; + pushFold(led, { + at: b.createdAt || Date.now(), + S: b.compressedTokens, + sigma: Math.ceil(b.summary.length / 4), + X: b.startRef ? prefixTokensBeforeRef(session, b.startRef) : undefined, + V: geo?.V, + Vp: geo?.Vp, + bid: b.blockId, + }); + led.lastBlockId = Math.max(led.lastBlockId, id); + } } function detectNewFolds(session: Session, led: CacheLedger): void { - const blocks = session.state?.blocks ?? []; - let maxId = led.lastBlockId; - for (const b of blocks) maxId = Math.max(maxId, refNum(b.blockId)); - if (maxId > led.lastBlockId) { - recordCacheFoldsFromBlocks(session, blocks.filter((b) => refNum(b.blockId) > led.lastBlockId)); - } + const blocks = session.state?.blocks ?? []; + let maxId = led.lastBlockId; + for (const b of blocks) maxId = Math.max(maxId, refNum(b.blockId)); + if (maxId > led.lastBlockId) { + recordCacheFoldsFromBlocks( + session, + blocks.filter((b) => refNum(b.blockId) > led.lastBlockId), + ); + } } /** Record one provider usage report into the session ledger. `input` must be @@ -951,313 +1235,443 @@ function detectNewFolds(session: Session, led: CacheLedger): void { * are quarantined out of the closure totals instead of booking their whole * billed prefix as an unexplained ttlRepay residual (#1536). */ export function recordCacheSample( - session: Session, - s: { at: number; input: number; cached: number | null; output?: number; protocol?: string; upstream?: string; keyFp?: string; sysFp?: string; canonFp?: string; mode?: "plugin" | "proxy" }, + session: Session, + s: { + at: number; + input: number; + cached: number | null; + output?: number; + protocol?: string; + upstream?: string; + keyFp?: string; + sysFp?: string; + canonFp?: string; + mode?: "plugin" | "proxy"; + }, ): void { - const led = getCacheLedger(session); - detectNewFolds(session, led); - const prevLine = led.lines[led.lines.length - 1]; - // #1536: unknown-cache samples still need a prev/cur pair so the fold chain - // stays consistent, but decompose with cached=0 then QUARANTINE every derived - // bucket (line missed/nc/cr/tr forced to 0 + excluded from agg below). - const known = s.cached !== null; - const effCached: number = s.cached ?? 0; - // Same window as buildCacheReport: a fold counts once its timestamp has - // elapsed (f.at <= s.at), never earlier — keeps incremental and batch math - // identical under clock skew between block.createdAt and settle time. - // #2929: the window is now the fold's COLD TAIL (mirror of the kernel's - // buildCacheReport): the first following sample is claimed - // unconditionally, then cold continuations are claimed until a warm line - // (>= FOLD_CLAIM_WARM_HIT_PCT) proves re-cache or FOLD_CLAIM_COLD_ROUNDS - // samples have elapsed. Before this, the first measurable sample consumed - // the fold, so the client-echo re-bill ~25–66s later carried no fold stamp, - // fell into the unattributed ttlRepay residual, and tripped the seam - // detector with "no fold attribution" (#2929's seven seams were exactly - // this shape, 25–66s after a degenerate head fold). - const warmLine = - known && s.input > 0 && (effCached / s.input) * 100 >= FOLD_CLAIM_WARM_HIT_PCT; - const pendRefs = led.folds.filter( - (f) => f.at <= s.at && !f.retired && ((f.claims ?? 0) === 0 || !warmLine), - ); - const pending: FoldEvent[] = pendRefs.map((f) => ({ - at: f.at, - tokensCompressed: f.S, - summaryTokens: f.sigma, - firstFoldStartTokens: f.X, - viewBefore: f.V, - viewAfter: f.Vp, - })); - const rawDec = decomposeSample( - prevLine ? { at: prevLine.at, input: prevLine.input, cached: prevLine.cached } : null, - { at: s.at, input: s.input, cached: effCached }, - pending, - ); - // #1891: a sample with NO previous baseline (the session's first measurable - // bill) has no prior prefix that could have expired — decomposeSample's - // prev=null path forces growth=0 and books the ENTIRE uncached input as - // ttlRepay, which detectSeam then misreads as an unexplained mid-history - // break (every field-flagged event in #1891 was exactly this shape). Rebook - // the residual as new content: missed === nc+cr+tr holds either way, so the - // closure stays balanced and only the bucket moves. - const noBaseline = !prevLine && known; - const dec = noBaseline - ? { ...rawDec, newContent: rawDec.newContent + rawDec.ttlRepay, ttlRepay: 0 } - : rawDec; - let foldSeq: number | null = null; - if (known && dec.foldIndex !== null) foldSeq = pendRefs[dec.foldIndex]?.seq ?? null; - // Advance the claim window only for measurable samples: an unknown - // sample must not eat a fold, or its compRepay would never reach a fold owner. - // #2929: each claimed sample bumps the fold's claim count; warm line or - // the FOLD_CLAIM_COLD_ROUNDS bound retires it (consumedFoldSeq stays the - // high-water mark of RETIRED folds for schema compat). - if (known && pendRefs.length > 0) { - for (const f of pendRefs) { - f.claims = (f.claims ?? 0) + 1; - if (f.claims >= FOLD_CLAIM_COLD_ROUNDS) { - f.retired = true; - led.consumedFoldSeq = Math.max(led.consumedFoldSeq, f.seq); - } - } - } - // A warm line retires EVERY open window — claimed or not this sample - // (#1847 discipline): it proves the provider re-cached, so a later cold - // blip is a new, unrelated event and must not be swallowed by the fold. - if (known && warmLine) { - for (const f of led.folds) { - if (f.at <= s.at && !f.retired) { - f.retired = true; - led.consumedFoldSeq = Math.max(led.consumedFoldSeq, f.seq); - } - } - } - const hitPct: number | null = known && s.input > 0 ? round1((effCached / s.input) * 100) : null; - // Target identity (#1535 model, generalized to model|wire|upstream in #1536): - // each component flags only when BOTH sides are known (unknown never flags). - const model = typeof session.metadata?.lastModel === "string" && session.metadata.lastModel !== "" - ? session.metadata.lastModel - : undefined; - const proto = typeof s.protocol === "string" && s.protocol !== "" ? s.protocol : undefined; - const up = typeof s.upstream === "string" && s.upstream !== "" ? s.upstream : undefined; - // #2131: credential fingerprint — the fourth identity component. Same - // never-flags-on-unknown rule: a lane without header capture must not - // fabricate switch events. - const key = typeof s.keyFp === "string" && s.keyFp !== "" ? s.keyFp : undefined; - // #2350: system-prompt fingerprint — the fifth identity component, same - // never-flags-on-unknown rule as the others. - const sys = typeof s.sysFp === "string" && s.sysFp !== "" ? s.sysFp : undefined; - // #2867: canonical INCOMING system/developer fingerprint (mode-independent). - // Pairs with `sys`: a flipped `sys` with a STABLE canon means bili's own - // compression-mode/projection switch moved what was forwarded, not the host. - const canon = typeof s.canonFp === "string" && s.canonFp !== "" ? s.canonFp : undefined; - // #1847: detect a dimension change against the last KNOWN value, not the immediately-previous - // line — an unmeasured (null-cache) request at the switch boundary must not swallow the flag, - // or the following measured cold re-bill lands unattributed. Unknown samples never advance it. - const modelSwitched = known && model !== undefined && led.lastKnownModel !== undefined && model !== led.lastKnownModel; - const wireSwitched = known && proto !== undefined && led.lastKnownProto !== undefined && proto !== led.lastKnownProto; - const upstreamSwitched = known && up !== undefined && led.lastKnownUp !== undefined && up !== led.lastKnownUp; - const keySwitched = known && key !== undefined && led.lastKnownKey !== undefined && key !== led.lastKnownKey; - const promptSwitched = known && sys !== undefined && led.lastKnownSp !== undefined && sys !== led.lastKnownSp; - // #2867: projection-flip = forwarded system bytes changed but the canonical - // incoming view did NOT (both sides known — an unknown side keeps the legacy - // host-side reading, never a fabricated projection claim). - const canonSwitched = known && canon !== undefined && led.lastKnownCanon !== undefined && canon !== led.lastKnownCanon; - const projFlip = promptSwitched && !canonSwitched && canon !== undefined && led.lastKnownCanon !== undefined; - // #499: first KNOWN sample under a fresh daemon boot with prior history → - // proxy-restart / re-fork boundary (upstream KV dropped during downtime). - const restarted = known && led.lines.length > 0 && led.lastBoot !== undefined && led.lastBoot !== BOOT_ID; - // #1286: turn counting is decoupled from compRepay attribution — the - // consumedFoldSeq gate above applies to the pending list only. Every - // elapsed fold counts EVERY later sample, matching buildCacheReport's - // full post-fold requestsAfter window. hPct seeds from the first KNOWN - // post-fold sample only (unknown samples carry no measurable hit rate). - // #2202: condition the benefit claim on measured coverage. requestsAfter - // multiplies (S−σ) into the avoided-token projection — booking a request - // against a fold whose covered bytes are no longer on the wire bills a - // saving that stopped happening (#2193: netSaved climbed through a - // destroyed substrate). The fraction comes from reconcileFoldCoverage's - // per-block record, measured on THIS request's inbound (the wire sites' - // reconcile pass precedes the usage report that settles here): - // 1 — full coverage, legacy entries without a block link, or the - // never-present class (structural absence, unverifiable) → identical - // to the pre-#2202 counter; - // f — partial coverage → proportional accrual; - // 0 — verified coverage-lost → accrual frozen until coverage returns. - const covAll = session.metadata[METADATA_FOLD_COVERAGE] as Record | undefined; - const lostLogged = (session.metadata[LOST_LOGGED_KEY] as Record | undefined) ?? {}; - let lostDirty = false; - for (const f of led.folds) { - if (f.at <= s.at) { - const cov = f.bid !== undefined ? covAll?.[f.bid] : undefined; - let frac = 1; - let lost: boolean | null = null; - if (cov !== undefined && cov.e === 1 && typeof cov.t === "number" && cov.t > 0) { - const present = (cov.p ?? 0) + (cov.r ?? 0); - frac = Math.min(1, present / cov.t); - lost = present === 0; - } - f.requestsAfter += frac; - if (known && f.hPct === null) f.hPct = hitPct; - if (lost !== null && f.bid !== undefined) { - if (lost && lostLogged[f.bid] !== true) { - lostLogged[f.bid] = true; - lostDirty = true; - loggerLog("warn", `[${session.id}] [cache-ledger] fold seq ${f.seq} (block ${f.bid}) coverage-lost: covered id(s) no longer on the resent wire — avoided-token accrual frozen at requestsAfter=${f.requestsAfter.toFixed(1)} (#2202)`); - } else if (!lost && lostLogged[f.bid] === true) { - delete lostLogged[f.bid]; - lostDirty = true; - loggerLog("info", `[${session.id}] [cache-ledger] fold seq ${f.seq} (block ${f.bid}) coverage restored — avoided-token accrual resumes (#2202)`); - } - } - } - } - if (lostDirty) session.metadata[LOST_LOGGED_KEY] = lostLogged; - if (foldSeq !== null) { - const owner = led.folds.find((f) => f.seq === foldSeq); - if (owner) owner.T += dec.compRepay; - } - led.sampleSeq += 1; - // #1847: attribute this sample's stable-prefix residual to AT MOST ONE named cause — a partition, - // not overlapping charges. Priority: restart drops every KV entry regardless of identity; then - // identity changes (model recomputes everything, wire/upstream re-route); plain TTL expiry is the - // unattributed remainder. A changed dimension also claims the bounded post-switch cold tail until a - // warm line proves re-cache — so a switch that cools several rounds is fully charged to it. - const isWarm = known && s.input > 0 && (hitPct ?? 0) >= WARM_HIT_PCT; - const seq = led.sampleSeq; - const contWithin = (inv: { seq: number } | undefined): boolean => - inv !== undefined && !isWarm && seq - inv.seq <= SWITCH_COLD_ROUNDS; - // A fresh change on THIS line outranks any prior-line continuation; among fresh changes use the fixed - // priority; with none, fall to the highest-priority dimension whose cold window is still open. - // #2131: `key` sits between model and wire — a rotated account on the same - // URL/model is more specific than a wire change and produces the same - // full-cold re-bill a model change does. - // #2350: `prompt` sits between key and wire — a host system-prompt rewrite - // is more specific than a wire/upstream re-route and drops every downstream - // prefix cache entry just like a key rotation does. - // #2867: `projection` sits behind prompt — a forwarded-system flip whose - // canonical incoming view stayed stable is bili's own mode/projection - // switch (self-heal degrade-to-proxy), same full-cold shape, different actor. - const freshCause: "restart" | "model" | "key" | "prompt" | "projection" | "wire" | "upstream" | null = - restarted ? "restart" - : modelSwitched ? "model" - : keySwitched ? "key" - : (promptSwitched && !projFlip) ? "prompt" - : projFlip ? "projection" - : wireSwitched ? "wire" - : upstreamSwitched ? "upstream" - : null; - const cause: "restart" | "model" | "key" | "prompt" | "projection" | "wire" | "upstream" | null = - freshCause !== null ? freshCause - : contWithin(led.invModel) ? "model" - : contWithin(led.invKey) ? "key" - : contWithin(led.invSp) ? "prompt" - : contWithin(led.invProj) ? "projection" - : contWithin(led.invWire) ? "wire" - : contWithin(led.invUp) ? "upstream" - : null; - led.lines.push({ - seq: led.sampleSeq, - at: s.at, - input: s.input, - cached: effCached, - output: s.output ?? 0, - hitPct, - missed: known ? dec.missed : 0, - nc: known ? dec.newContent : 0, - cr: known ? dec.compRepay : 0, - tr: known ? dec.ttlRepay : 0, - foldSeq, - model, - proto, - up, - kp: key, - sp: sys, - sw: modelSwitched ? 1 : undefined, - pw: wireSwitched ? 1 : undefined, - uw: upstreamSwitched ? 1 : undefined, - kw: keySwitched ? 1 : undefined, - sf: promptSwitched ? 1 : undefined, - pf: projFlip ? 1 : undefined, - cf: !promptSwitched && canonSwitched ? 1 : undefined, - pm: s.mode, - rs: restarted ? 1 : undefined, - unk: known ? undefined : 1, - nb: noBaseline ? 1 : undefined, - cause: known && cause !== null ? cause : undefined, - }); - led.lastBoot = BOOT_ID; - const agg = led.agg; - agg.requests += 1; - agg.output += s.output ?? 0; - if (!known) { - // Unmeasurable: quarantine the whole billed prefix out of the closure. - agg.unknownInput += s.input; - agg.unknownSamples += 1; - return; - } - agg.input += s.input; - agg.cached += effCached; - agg.nc += dec.newContent; - agg.cr += dec.compRepay; - agg.tr += dec.ttlRepay; - // #2784: event counters follow the SAME rule as the token partition — one line, exactly ONE narrative - // cause. One user action often flips several identity dimensions at once (dsh's model switch re-renders - // the model name into its system prompt, so the prompt fingerprint flips on the SAME line as the model - // change); counting the shadowed dimensions narrates one action twice and the web panel renders them as - // independent zero-token causes ("prompt rewrite 0 x1"). The raw observation stays on the line itself - // (per-dimension flags + values + the winning cause), so forensics lose nothing. Token buckets charge - // EXACTLY the primary cause so the per-cause breakdown partitions the residual instead of overlapping it. - if (freshCause === "restart") agg.restartDrops += 1; - else if (freshCause === "model") agg.switches += 1; - else if (freshCause === "key") agg.keySwitches += 1; - else if (freshCause === "prompt") agg.promptSwitches += 1; - else if (freshCause === "projection") agg.projSwitches += 1; - else if (freshCause === "wire") agg.wireSwitches += 1; - else if (freshCause === "upstream") agg.upstreamSwitches += 1; - if (cause === "model") agg.switchMissed += dec.ttlRepay; - else if (cause === "key") agg.keySwitchMissed += dec.ttlRepay; - else if (cause === "prompt") agg.promptSwitchMissed += dec.ttlRepay; - else if (cause === "projection") agg.projSwitchMissed += dec.ttlRepay; - else if (cause === "wire") agg.wireSwitchMissed += dec.ttlRepay; - else if (cause === "upstream") agg.upstreamSwitchMissed += dec.ttlRepay; - else if (cause === "restart") agg.restartDropMissed += dec.ttlRepay; - if (cause !== null) agg.attributedMissed += dec.ttlRepay; - // Advance the trackers (measured samples only): a warm line retires every open cold-window, an expired - // window drops out, and a fresh change opens/replaces it. - if (isWarm) { - led.invModel = undefined; - led.invWire = undefined; - led.invUp = undefined; - led.invKey = undefined; - led.invSp = undefined; - led.invProj = undefined; - } else { - if (led.invModel && seq - led.invModel.seq > SWITCH_COLD_ROUNDS) led.invModel = undefined; - if (led.invWire && seq - led.invWire.seq > SWITCH_COLD_ROUNDS) led.invWire = undefined; - if (led.invUp && seq - led.invUp.seq > SWITCH_COLD_ROUNDS) led.invUp = undefined; - if (led.invKey && seq - led.invKey.seq > SWITCH_COLD_ROUNDS) led.invKey = undefined; - if (led.invSp && seq - led.invSp.seq > SWITCH_COLD_ROUNDS) led.invSp = undefined; - if (led.invProj && seq - led.invProj.seq > SWITCH_COLD_ROUNDS) led.invProj = undefined; - } - if (modelSwitched) led.invModel = { seq, at: s.at, from: led.lastKnownModel ?? null, to: model! }; - if (wireSwitched) led.invWire = { seq, at: s.at, from: led.lastKnownProto ?? null, to: proto! }; - if (upstreamSwitched) led.invUp = { seq, at: s.at, from: led.lastKnownUp ?? null, to: up! }; - if (keySwitched) led.invKey = { seq, at: s.at, from: led.lastKnownKey ?? null, to: key! }; - // #2867: a pure projection flip also sets promptSwitched (the - // forwarded bytes did change) — opening invSp as well would let - // the cold tail re-charge "prompt" for the proxy's own mode - // switch. Only the host-side reading owns invSp. - if (promptSwitched && !projFlip) led.invSp = { seq, at: s.at, from: led.lastKnownSp ?? null, to: sys! }; - if (projFlip) led.invProj = { seq, at: s.at, from: led.lastKnownSp ?? null, to: sys! }; - if (model !== undefined) led.lastKnownModel = model; - if (proto !== undefined) led.lastKnownProto = proto; - if (up !== undefined) led.lastKnownUp = up; - if (key !== undefined) led.lastKnownKey = key; - if (sys !== undefined) led.lastKnownSp = sys; - if (canon !== undefined) led.lastKnownCanon = canon; - if (noBaseline) { - agg.nbSamples += 1; - agg.nbInput += s.input; - } + const led = getCacheLedger(session); + detectNewFolds(session, led); + const prevLine = led.lines[led.lines.length - 1]; + // #1536: unknown-cache samples still need a prev/cur pair so the fold chain + // stays consistent, but decompose with cached=0 then QUARANTINE every derived + // bucket (line missed/nc/cr/tr forced to 0 + excluded from agg below). + const known = s.cached !== null; + const effCached: number = s.cached ?? 0; + // Same window as buildCacheReport: a fold counts once its timestamp has + // elapsed (f.at <= s.at), never earlier — keeps incremental and batch math + // identical under clock skew between block.createdAt and settle time. + // #2929: the window is now the fold's COLD TAIL (mirror of the kernel's + // buildCacheReport): the first following sample is claimed + // unconditionally, then cold continuations are claimed until a warm line + // (>= FOLD_CLAIM_WARM_HIT_PCT) proves re-cache or FOLD_CLAIM_COLD_ROUNDS + // samples have elapsed. Before this, the first measurable sample consumed + // the fold, so the client-echo re-bill ~25–66s later carried no fold stamp, + // fell into the unattributed ttlRepay residual, and tripped the seam + // detector with "no fold attribution" (#2929's seven seams were exactly + // this shape, 25–66s after a degenerate head fold). + const warmLine = + known && + s.input > 0 && + (effCached / s.input) * 100 >= FOLD_CLAIM_WARM_HIT_PCT; + const pendRefs = led.folds.filter( + (f) => f.at <= s.at && !f.retired && ((f.claims ?? 0) === 0 || !warmLine), + ); + const pending: FoldEvent[] = pendRefs.map((f) => ({ + at: f.at, + tokensCompressed: f.S, + summaryTokens: f.sigma, + firstFoldStartTokens: f.X, + viewBefore: f.V, + viewAfter: f.Vp, + })); + const rawDec = decomposeSample( + prevLine + ? { at: prevLine.at, input: prevLine.input, cached: prevLine.cached } + : null, + { at: s.at, input: s.input, cached: effCached }, + pending, + ); + // #1891: a sample with NO previous baseline (the session's first measurable + // bill) has no prior prefix that could have expired — decomposeSample's + // prev=null path forces growth=0 and books the ENTIRE uncached input as + // ttlRepay, which detectSeam then misreads as an unexplained mid-history + // break (every field-flagged event in #1891 was exactly this shape). Rebook + // the residual as new content: missed === nc+cr+tr holds either way, so the + // closure stays balanced and only the bucket moves. + const noBaseline = !prevLine && known; + const dec = noBaseline + ? { + ...rawDec, + newContent: rawDec.newContent + rawDec.ttlRepay, + ttlRepay: 0, + } + : rawDec; + let foldSeq: number | null = null; + if (known && dec.foldIndex !== null) + foldSeq = pendRefs[dec.foldIndex]?.seq ?? null; + // Advance the claim window only for measurable samples: an unknown + // sample must not eat a fold, or its compRepay would never reach a fold owner. + // #2929: each claimed sample bumps the fold's claim count; warm line or + // the FOLD_CLAIM_COLD_ROUNDS bound retires it (consumedFoldSeq stays the + // high-water mark of RETIRED folds for schema compat). + if (known && pendRefs.length > 0) { + for (const f of pendRefs) { + f.claims = (f.claims ?? 0) + 1; + if (f.claims >= FOLD_CLAIM_COLD_ROUNDS) { + f.retired = true; + led.consumedFoldSeq = Math.max(led.consumedFoldSeq, f.seq); + } + } + } + // A warm line retires EVERY open window — claimed or not this sample + // (#1847 discipline): it proves the provider re-cached, so a later cold + // blip is a new, unrelated event and must not be swallowed by the fold. + if (known && warmLine) { + for (const f of led.folds) { + if (f.at <= s.at && !f.retired) { + f.retired = true; + led.consumedFoldSeq = Math.max(led.consumedFoldSeq, f.seq); + } + } + } + const hitPct: number | null = + known && s.input > 0 ? round1((effCached / s.input) * 100) : null; + // Target identity (#1535 model, generalized to model|wire|upstream in #1536): + // each component flags only when BOTH sides are known (unknown never flags). + const model = + typeof session.metadata?.lastModel === "string" && + session.metadata.lastModel !== "" + ? session.metadata.lastModel + : undefined; + const proto = + typeof s.protocol === "string" && s.protocol !== "" + ? s.protocol + : undefined; + const up = + typeof s.upstream === "string" && s.upstream !== "" + ? s.upstream + : undefined; + // #2131: credential fingerprint — the fourth identity component. Same + // never-flags-on-unknown rule: a lane without header capture must not + // fabricate switch events. + const key = + typeof s.keyFp === "string" && s.keyFp !== "" ? s.keyFp : undefined; + // #2350: system-prompt fingerprint — the fifth identity component, same + // never-flags-on-unknown rule as the others. + const sys = + typeof s.sysFp === "string" && s.sysFp !== "" ? s.sysFp : undefined; + // #2867: canonical INCOMING system/developer fingerprint (mode-independent). + // Pairs with `sys`: a flipped `sys` with a STABLE canon means bili's own + // compression-mode/projection switch moved what was forwarded, not the host. + const canon = + typeof s.canonFp === "string" && s.canonFp !== "" ? s.canonFp : undefined; + // #1847: detect a dimension change against the last KNOWN value, not the immediately-previous + // line — an unmeasured (null-cache) request at the switch boundary must not swallow the flag, + // or the following measured cold re-bill lands unattributed. Unknown samples never advance it. + const modelSwitched = + known && + model !== undefined && + led.lastKnownModel !== undefined && + model !== led.lastKnownModel; + const wireSwitched = + known && + proto !== undefined && + led.lastKnownProto !== undefined && + proto !== led.lastKnownProto; + const upstreamSwitched = + known && + up !== undefined && + led.lastKnownUp !== undefined && + up !== led.lastKnownUp; + const keySwitched = + known && + key !== undefined && + led.lastKnownKey !== undefined && + key !== led.lastKnownKey; + const promptSwitched = + known && + sys !== undefined && + led.lastKnownSp !== undefined && + sys !== led.lastKnownSp; + // #2867: projection-flip = forwarded system bytes changed but the canonical + // incoming view did NOT (both sides known — an unknown side keeps the legacy + // host-side reading, never a fabricated projection claim). + const canonSwitched = + known && + canon !== undefined && + led.lastKnownCanon !== undefined && + canon !== led.lastKnownCanon; + const projFlip = + promptSwitched && + !canonSwitched && + canon !== undefined && + led.lastKnownCanon !== undefined; + // #499: first KNOWN sample under a fresh daemon boot with prior history → + // proxy-restart / re-fork boundary (upstream KV dropped during downtime). + const restarted = + known && + led.lines.length > 0 && + led.lastBoot !== undefined && + led.lastBoot !== BOOT_ID; + // #1286: turn counting is decoupled from compRepay attribution — the + // consumedFoldSeq gate above applies to the pending list only. Every + // elapsed fold counts EVERY later sample, matching buildCacheReport's + // full post-fold requestsAfter window. hPct seeds from the first KNOWN + // post-fold sample only (unknown samples carry no measurable hit rate). + // #2202: condition the benefit claim on measured coverage. requestsAfter + // multiplies (S−σ) into the avoided-token projection — booking a request + // against a fold whose covered bytes are no longer on the wire bills a + // saving that stopped happening (#2193: netSaved climbed through a + // destroyed substrate). The fraction comes from reconcileFoldCoverage's + // per-block record, measured on THIS request's inbound (the wire sites' + // reconcile pass precedes the usage report that settles here): + // 1 — full coverage, legacy entries without a block link, or the + // never-present class (structural absence, unverifiable) → identical + // to the pre-#2202 counter; + // f — partial coverage → proportional accrual; + // 0 — verified coverage-lost → accrual frozen until coverage returns. + const covAll = session.metadata[METADATA_FOLD_COVERAGE] as + | Record + | undefined; + const lostLogged = + (session.metadata[LOST_LOGGED_KEY] as Record | undefined) ?? + {}; + let lostDirty = false; + for (const f of led.folds) { + if (f.at <= s.at) { + const cov = f.bid !== undefined ? covAll?.[f.bid] : undefined; + let frac = 1; + let lost: boolean | null = null; + if ( + cov !== undefined && + cov.e === 1 && + typeof cov.t === "number" && + cov.t > 0 + ) { + const present = (cov.p ?? 0) + (cov.r ?? 0); + frac = Math.min(1, present / cov.t); + lost = present === 0; + } + f.requestsAfter += frac; + if (known && f.hPct === null) f.hPct = hitPct; + if (lost !== null && f.bid !== undefined) { + if (lost && lostLogged[f.bid] !== true) { + lostLogged[f.bid] = true; + lostDirty = true; + loggerLog( + "warn", + `[${session.id}] [cache-ledger] fold seq ${f.seq} (block ${f.bid}) coverage-lost: covered id(s) no longer on the resent wire — avoided-token accrual frozen at requestsAfter=${f.requestsAfter.toFixed(1)} (#2202)`, + ); + } else if (!lost && lostLogged[f.bid] === true) { + delete lostLogged[f.bid]; + lostDirty = true; + loggerLog( + "info", + `[${session.id}] [cache-ledger] fold seq ${f.seq} (block ${f.bid}) coverage restored — avoided-token accrual resumes (#2202)`, + ); + } + } + } + } + if (lostDirty) session.metadata[LOST_LOGGED_KEY] = lostLogged; + if (foldSeq !== null) { + const owner = led.folds.find((f) => f.seq === foldSeq); + if (owner) owner.T += dec.compRepay; + } + led.sampleSeq += 1; + // #1847: attribute this sample's stable-prefix residual to AT MOST ONE named cause — a partition, + // not overlapping charges. Priority: restart drops every KV entry regardless of identity; then + // identity changes (model recomputes everything, wire/upstream re-route); plain TTL expiry is the + // unattributed remainder. A changed dimension also claims the bounded post-switch cold tail until a + // warm line proves re-cache — so a switch that cools several rounds is fully charged to it. + const isWarm = known && s.input > 0 && (hitPct ?? 0) >= WARM_HIT_PCT; + const seq = led.sampleSeq; + const contWithin = (inv: { seq: number } | undefined): boolean => + inv !== undefined && !isWarm && seq - inv.seq <= SWITCH_COLD_ROUNDS; + // A fresh change on THIS line outranks any prior-line continuation; among fresh changes use the fixed + // priority; with none, fall to the highest-priority dimension whose cold window is still open. + // #2131: `key` sits between model and wire — a rotated account on the same + // URL/model is more specific than a wire change and produces the same + // full-cold re-bill a model change does. + // #2350: `prompt` sits between key and wire — a host system-prompt rewrite + // is more specific than a wire/upstream re-route and drops every downstream + // prefix cache entry just like a key rotation does. + // #2867: `projection` sits behind prompt — a forwarded-system flip whose + // canonical incoming view stayed stable is bili's own mode/projection + // switch (self-heal degrade-to-proxy), same full-cold shape, different actor. + const freshCause: + | "restart" + | "model" + | "key" + | "prompt" + | "projection" + | "wire" + | "upstream" + | null = restarted + ? "restart" + : modelSwitched + ? "model" + : keySwitched + ? "key" + : promptSwitched && !projFlip + ? "prompt" + : projFlip + ? "projection" + : wireSwitched + ? "wire" + : upstreamSwitched + ? "upstream" + : null; + const cause: + | "restart" + | "model" + | "key" + | "prompt" + | "projection" + | "wire" + | "upstream" + | null = + freshCause !== null + ? freshCause + : contWithin(led.invModel) + ? "model" + : contWithin(led.invKey) + ? "key" + : contWithin(led.invSp) + ? "prompt" + : contWithin(led.invProj) + ? "projection" + : contWithin(led.invWire) + ? "wire" + : contWithin(led.invUp) + ? "upstream" + : null; + led.lines.push({ + seq: led.sampleSeq, + at: s.at, + input: s.input, + cached: effCached, + output: s.output ?? 0, + hitPct, + missed: known ? dec.missed : 0, + nc: known ? dec.newContent : 0, + cr: known ? dec.compRepay : 0, + tr: known ? dec.ttlRepay : 0, + foldSeq, + model, + proto, + up, + kp: key, + sp: sys, + sw: modelSwitched ? 1 : undefined, + pw: wireSwitched ? 1 : undefined, + uw: upstreamSwitched ? 1 : undefined, + kw: keySwitched ? 1 : undefined, + sf: promptSwitched ? 1 : undefined, + pf: projFlip ? 1 : undefined, + cf: !promptSwitched && canonSwitched ? 1 : undefined, + pm: s.mode, + rs: restarted ? 1 : undefined, + unk: known ? undefined : 1, + nb: noBaseline ? 1 : undefined, + cause: known && cause !== null ? cause : undefined, + }); + led.lastBoot = BOOT_ID; + const agg = led.agg; + agg.requests += 1; + agg.output += s.output ?? 0; + if (!known) { + // Unmeasurable: quarantine the whole billed prefix out of the closure. + agg.unknownInput += s.input; + agg.unknownSamples += 1; + return; + } + agg.input += s.input; + agg.cached += effCached; + agg.nc += dec.newContent; + agg.cr += dec.compRepay; + agg.tr += dec.ttlRepay; + // #2784: event counters follow the SAME rule as the token partition — one line, exactly ONE narrative + // cause. One user action often flips several identity dimensions at once (dsh's model switch re-renders + // the model name into its system prompt, so the prompt fingerprint flips on the SAME line as the model + // change); counting the shadowed dimensions narrates one action twice and the web panel renders them as + // independent zero-token causes ("prompt rewrite 0 x1"). The raw observation stays on the line itself + // (per-dimension flags + values + the winning cause), so forensics lose nothing. Token buckets charge + // EXACTLY the primary cause so the per-cause breakdown partitions the residual instead of overlapping it. + if (freshCause === "restart") agg.restartDrops += 1; + else if (freshCause === "model") agg.switches += 1; + else if (freshCause === "key") agg.keySwitches += 1; + else if (freshCause === "prompt") agg.promptSwitches += 1; + else if (freshCause === "projection") agg.projSwitches += 1; + else if (freshCause === "wire") agg.wireSwitches += 1; + else if (freshCause === "upstream") agg.upstreamSwitches += 1; + if (cause === "model") agg.switchMissed += dec.ttlRepay; + else if (cause === "key") agg.keySwitchMissed += dec.ttlRepay; + else if (cause === "prompt") agg.promptSwitchMissed += dec.ttlRepay; + else if (cause === "projection") agg.projSwitchMissed += dec.ttlRepay; + else if (cause === "wire") agg.wireSwitchMissed += dec.ttlRepay; + else if (cause === "upstream") agg.upstreamSwitchMissed += dec.ttlRepay; + else if (cause === "restart") agg.restartDropMissed += dec.ttlRepay; + if (cause !== null) agg.attributedMissed += dec.ttlRepay; + // Advance the trackers (measured samples only): a warm line retires every open cold-window, an expired + // window drops out, and a fresh change opens/replaces it. + if (isWarm) { + led.invModel = undefined; + led.invWire = undefined; + led.invUp = undefined; + led.invKey = undefined; + led.invSp = undefined; + led.invProj = undefined; + } else { + if (led.invModel && seq - led.invModel.seq > SWITCH_COLD_ROUNDS) + led.invModel = undefined; + if (led.invWire && seq - led.invWire.seq > SWITCH_COLD_ROUNDS) + led.invWire = undefined; + if (led.invUp && seq - led.invUp.seq > SWITCH_COLD_ROUNDS) + led.invUp = undefined; + if (led.invKey && seq - led.invKey.seq > SWITCH_COLD_ROUNDS) + led.invKey = undefined; + if (led.invSp && seq - led.invSp.seq > SWITCH_COLD_ROUNDS) + led.invSp = undefined; + if (led.invProj && seq - led.invProj.seq > SWITCH_COLD_ROUNDS) + led.invProj = undefined; + } + if (modelSwitched) + led.invModel = { + seq, + at: s.at, + from: led.lastKnownModel ?? null, + to: model!, + }; + if (wireSwitched) + led.invWire = { + seq, + at: s.at, + from: led.lastKnownProto ?? null, + to: proto!, + }; + if (upstreamSwitched) + led.invUp = { seq, at: s.at, from: led.lastKnownUp ?? null, to: up! }; + if (keySwitched) + led.invKey = { seq, at: s.at, from: led.lastKnownKey ?? null, to: key! }; + // #2867: a pure projection flip also sets promptSwitched (the + // forwarded bytes did change) — opening invSp as well would let + // the cold tail re-charge "prompt" for the proxy's own mode + // switch. Only the host-side reading owns invSp. + if (promptSwitched && !projFlip) + led.invSp = { seq, at: s.at, from: led.lastKnownSp ?? null, to: sys! }; + if (projFlip) + led.invProj = { seq, at: s.at, from: led.lastKnownSp ?? null, to: sys! }; + if (model !== undefined) led.lastKnownModel = model; + if (proto !== undefined) led.lastKnownProto = proto; + if (up !== undefined) led.lastKnownUp = up; + if (key !== undefined) led.lastKnownKey = key; + if (sys !== undefined) led.lastKnownSp = sys; + if (canon !== undefined) led.lastKnownCanon = canon; + if (noBaseline) { + agg.nbSamples += 1; + agg.nbInput += s.input; + } } /** #1547: single settle path for one successful upstream turn's usage report. @@ -1311,183 +1725,263 @@ const CALIBRATION_CONSISTENCY_RATIO = 2; * (feeding it would mis-bucket the #2867 host-rewrite-vs-proxy-projection * attribution). Split out as a pure helper so the lane gate is unit-testable * off-Windows. */ -export function canonicalSysFpForSettle(session: Session, protocol?: string): string | undefined { - if (protocol !== "responses") return undefined; - const noted = session.metadata?.[METADATA_CANONICAL_SYS_FP] as { fp?: unknown } | undefined; - return typeof noted?.fp === "string" && noted.fp !== "" ? noted.fp : undefined; +export function canonicalSysFpForSettle( + session: Session, + protocol?: string, +): string | undefined { + if (protocol !== "responses") return undefined; + const noted = session.metadata?.[METADATA_CANONICAL_SYS_FP] as + | { fp?: unknown } + | undefined; + return typeof noted?.fp === "string" && noted.fp !== "" + ? noted.fp + : undefined; } export function settleUsageReport( - session: Session, - s: { total: number; reportedCached: number | null; output?: number; protocol?: string; upstream?: string }, - localTextEstimate?: number, + session: Session, + s: { + total: number; + reportedCached: number | null; + output?: number; + protocol?: string; + upstream?: string; + }, + localTextEstimate?: number, ): void { - // #793: a zero-total sample carries no information (gateway placeholder or - // relay echo) — it must not clobber the last trusted lastInputTokens. - if (s.total > 0) { - session.stats.inputTokens += s.total; - // Net out this turn's compress credit: the post-compress re-request - // re-sends the unfolded history, so its usage report over-reports the - // context the NEXT request will actually carry (see stream.ts applyRanges). - session.stats.lastInputTokens = Math.max(0, s.total - (session.stats.compressCreditTokens ?? 0)); - // #1569: calibration anchor for estimate-grade turns — written ONLY by - // real upstream usage reports (all three response shapes funnel here), - // never by estimate-grade samples or arming paths; dropped at native- - // compaction boundaries via resetSessionCompression (session.ts). - session.stats.lastUsageGradeTokens = session.stats.lastInputTokens; - session.stats.lastInputTokensSource = "usage"; - session.stats.contextTokens = session.stats.lastInputTokens; - session.stats.contextTokensSource = "usage"; - if (session.metadata) session.metadata.contextTokensAt = Date.now(); - recordContextObservation(session, session.stats.lastInputTokens, (session.stats.compressCreditTokens ?? 0) > 0 ? "estimate" : "usage"); - // #1933 F2: record which route measured this baseline — the gate uses - // it to demote the baseline when the current request routes elsewhere. - const settleOrigin = normalizeUpstreamOrigin(s.upstream); - if (settleOrigin !== undefined) session.stats.lastInputTokensOrigin = settleOrigin; - // #1933 F1: consume the pending pair — the local text estimate of the - // payload THIS report bills, recorded at prepare time. Same route - // required. Admitted samples (plausibility band) accumulate in a - // per-origin ring; the factor is published only once ≥2 recent samples - // agree within ×2, and cleared again when they stop agreeing — until - // then the raw estimate decides (legacy behavior). - const pendingEst = session.stats.lastLocalTextEstimate; - const pendingOrigin = normalizeUpstreamOrigin(session.stats.lastLocalTextEstimateOrigin); - if (pendingEst !== undefined && pendingEst >= CALIBRATION_MIN_ESTIMATE && settleOrigin !== undefined && pendingOrigin === settleOrigin) { - const rawSample = s.total / pendingEst; - // #2117 B: the ring is keyed by route AND model — tokenizers bill - // differently across models, so a mid-session model switch starts a - // FRESH ring instead of blending two models' billing scales into one - // factor. Missing model info NEVER invalidates (same discipline as - // currentCalibrationFactor): a ring without a model key — legacy - // pre-upgrade files included, and records restored after a restart - // whose load whitelist drops the model fields (#2141) — continues - // and ADOPTS the first known model. Discarding it would clear a - // provenance-matched published k̂ on the first post-restart settle - // (the #2129 regression class). - const settleModel = typeof session.metadata?.lastModel === "string" && session.metadata.lastModel !== "" ? session.metadata.lastModel : undefined; - let ring = session.stats.calibrationRing; - if (!ring || ring.origin !== settleOrigin || (ring.model !== undefined && settleModel !== undefined && ring.model !== settleModel)) { - ring = { origin: settleOrigin, model: settleModel, values: [] }; - } else if (ring.model === undefined && settleModel !== undefined) { - ring.model = settleModel; - } - if (rawSample >= CALIBRATION_SAMPLE_MIN && rawSample <= CALIBRATION_SAMPLE_MAX) { - ring.values.push(rawSample); - if (ring.values.length > CALIBRATION_SAMPLE_WINDOW) ring.values.shift(); - const spread = Math.max(...ring.values) / Math.min(...ring.values); - if (ring.values.length >= 2 && spread <= CALIBRATION_CONSISTENCY_RATIO) { - const mean = ring.values.reduce((a, b) => a + b, 0) / ring.values.length; - session.stats.calibratedEstimate = Math.min(CALIBRATION_CLAMP_MAX, Math.max(CALIBRATION_CLAMP_MIN, mean)); - session.stats.calibratedEstimateOrigin = settleOrigin; - // Provenance is the ring's model key, not this sample's stamp — - // an unknown-model settle continues a model-keyed ring without - // blanking the established provenance. - session.stats.calibratedEstimateModel = ring.model; - } else { - delete session.stats.calibratedEstimate; - delete session.stats.calibratedEstimateOrigin; - delete session.stats.calibratedEstimateModel; - } - } - session.stats.calibrationRing = ring; - } - // #1820: a real usage-grade sample supersedes the post-rebuild meter - // anchor immediately — no need to wait out its prepare budget. - clearPostRebuildAnchor(session); - // #1110: a real usage report retires the one-shot overflow arm. - delete session.stats.overflowArmTokens; - // #1595: a real report landing far below a stale-high nudge reference - // retires that reference too (one call covers all three lanes). - reanchorNudgeOnUsageDrop(session); - } - // #1933 F1: roll the pending pair forward to the current turn's value — - // it will be consumed by the NEXT report (or cleared when the lane - // provides none, so a stale pair can never be mispaired). - session.stats.lastLocalTextEstimate = localTextEstimate; - session.stats.lastLocalTextEstimateOrigin = localTextEstimate !== undefined ? normalizeUpstreamOrigin(s.upstream) : undefined; - if (s.reportedCached !== null && s.total > 0) { - session.stats.cachedTokens += s.reportedCached; - session.stats.cacheSamples += 1; - } - // #2131: the credential fingerprint captured at the send chokepoint rides - // the seam slot — read it BEFORE recordCacheSample so the line it pushes - // already carries the identity (kp/kw) without a second slot lookup. - const curKeyFp = session.transient?.sentBody?.keyFp; - // #2350: the host's system-prompt fingerprint as noted for THIS request by - // fold-reconcile's wire sites (they precede this settle under the session - // lock). Sparse: lanes that never noted one (title-gen / compaction-trigger - // sidecars) carry no value and can neither flag nor advance the baseline. - const notedSys = session.metadata?.[METADATA_SYSTEM_FP] as { fp?: unknown } | undefined; - const curSysFp = typeof notedSys?.fp === "string" && notedSys.fp !== "" ? notedSys.fp : undefined; - // #2867: the canonical incoming fingerprint + compression mode ride along so - // recordCacheSample can tell a host-side prompt rewrite from bili's own - // projection/mode switch (responses lane only; other lanes omit both). - const curCanonFp = canonicalSysFpForSettle(session, s.protocol); - // Same lane-gate as the canon slot above: the mode stamp is written only by - // prepare-responses, so on a non-responses settle it would leak the last - // responses request's label into an inert-but-misleading line field. - const lastMode = s.protocol === "responses" ? (session.metadata?.[METADATA_LAST_RESPONSES_MODE] as unknown) : undefined; - const led = getCacheLedger(session); - recordCacheSample(session, { at: Date.now(), input: s.total, cached: s.reportedCached, output: s.output, protocol: s.protocol, upstream: s.upstream, keyFp: curKeyFp, sysFp: curSysFp, canonFp: curCanonFp, mode: lastMode === "plugin" || lastMode === "proxy" ? lastMode : undefined }); - // #2131: per-call body-stability proof on the just-recorded line — the same - // pairing detectSeam uses (this request's forwarded body vs the previous - // settled one), so "prefix unchanged between calls" is stored data, not an - // interpretation. Digest equality decides; the LCP offset localizes where - // a divergence started when both full bodies were retained. - const curSlot = session.transient?.sentBody; - if (curSlot !== undefined) { - const curLine = led.lines[led.lines.length - 1]; - if (curLine !== undefined) { - curLine.bd = curSlot.digest; - const prevSlot = session.transient?.settledBody; - if (prevSlot !== undefined) { - if (curSlot.digest === prevSlot.digest) { - curLine.be = 1; - } else { - curLine.be = 0; - if (curSlot.full !== null && prevSlot.full !== null) { - const lcp = byteLcp(prevSlot.full, curSlot.full); - curLine.bl = lcp; - // Append/trim first: "the whole shorter payload survives" - // is anchored to the END of the payload and stays true on - // small bodies where the head threshold alone would lie. - // #2982: the would-be-mid branch pays one extra scan over - // the SHORTER body: when the first divergence sits at/past - // that body's message-array closing bracket, no shared - // history byte moved — only trailing top-level params - // (host-computed max_tokens/…) or an ephemeral tail note - // that appeared/vanished between requests differ (#2980). - // The shorter side is decisive: when one side grew the - // array, the LCP stops at ITS closing bracket (`]` vs `,`), - // which lies inside the LONGER side's array — parsing that - // side would misread the pair as mid. No array locatable - // (unparseable body) keeps the conservative pre-fix class. - const shorterFull = prevSlot.full.length <= curSlot.full.length ? prevSlot.full : curSlot.full; - const arrClose = messagesArrayCloseOffset(shorterFull); - curLine.bs = lcp >= Math.min(prevSlot.full.length, curSlot.full.length) - 64 ? "append" : lcp < 1024 ? "head" : arrClose !== null && lcp >= arrClose ? "tail" : "mid"; - } else { - curLine.bs = "unknown"; - } - } - } - } - } - // #1843 L1: the usage total is ground truth for what the route's vision - // encoder actually billed — fold any captured image facts into the learned - // per-route cost (no-op when the request carried no images or no capture). - settleImageLearning(session, s.total); - // #1592-family seam forensics: pair this settle with the body that was - // actually sent (noteForwardedBody), then keep it as the next pair's - // baseline. Lanes without body capture still get the aggregate flag. - detectSeam(session, led); - const seamBody = session.transient?.sentBody; - if (seamBody !== undefined) (session.transient ??= {}).settledBody = seamBody; - delete session.transient?.sentBody; - // #3023: settle the inbound pair with the same lifecycle — the next - // settle's client arm compares against THIS request's client view. - const seamIn = session.transient?.inBody; - if (seamIn !== undefined) (session.transient ??= {}).settledInBody = seamIn; - delete session.transient?.inBody; + // #793: a zero-total sample carries no information (gateway placeholder or + // relay echo) — it must not clobber the last trusted lastInputTokens. + if (s.total > 0) { + session.stats.inputTokens += s.total; + // Net out this turn's compress credit: the post-compress re-request + // re-sends the unfolded history, so its usage report over-reports the + // context the NEXT request will actually carry (see stream.ts applyRanges). + session.stats.lastInputTokens = Math.max( + 0, + s.total - (session.stats.compressCreditTokens ?? 0), + ); + // #1569: calibration anchor for estimate-grade turns — written ONLY by + // real upstream usage reports (all three response shapes funnel here), + // never by estimate-grade samples or arming paths; dropped at native- + // compaction boundaries via resetSessionCompression (session.ts). + session.stats.lastUsageGradeTokens = session.stats.lastInputTokens; + session.stats.lastInputTokensSource = "usage"; + session.stats.contextTokens = session.stats.lastInputTokens; + session.stats.contextTokensSource = "usage"; + if (session.metadata) session.metadata.contextTokensAt = Date.now(); + recordContextObservation( + session, + session.stats.lastInputTokens, + (session.stats.compressCreditTokens ?? 0) > 0 ? "estimate" : "usage", + ); + // #1933 F2: record which route measured this baseline — the gate uses + // it to demote the baseline when the current request routes elsewhere. + const settleOrigin = normalizeUpstreamOrigin(s.upstream); + if (settleOrigin !== undefined) + session.stats.lastInputTokensOrigin = settleOrigin; + // #1933 F1: consume the pending pair — the local text estimate of the + // payload THIS report bills, recorded at prepare time. Same route + // required. Admitted samples (plausibility band) accumulate in a + // per-origin ring; the factor is published only once ≥2 recent samples + // agree within ×2, and cleared again when they stop agreeing — until + // then the raw estimate decides (legacy behavior). + const pendingEst = session.stats.lastLocalTextEstimate; + const pendingOrigin = normalizeUpstreamOrigin( + session.stats.lastLocalTextEstimateOrigin, + ); + if ( + pendingEst !== undefined && + pendingEst >= CALIBRATION_MIN_ESTIMATE && + settleOrigin !== undefined && + pendingOrigin === settleOrigin + ) { + const rawSample = s.total / pendingEst; + // #2117 B: the ring is keyed by route AND model — tokenizers bill + // differently across models, so a mid-session model switch starts a + // FRESH ring instead of blending two models' billing scales into one + // factor. Missing model info NEVER invalidates (same discipline as + // currentCalibrationFactor): a ring without a model key — legacy + // pre-upgrade files included, and records restored after a restart + // whose load whitelist drops the model fields (#2141) — continues + // and ADOPTS the first known model. Discarding it would clear a + // provenance-matched published k̂ on the first post-restart settle + // (the #2129 regression class). + const settleModel = + typeof session.metadata?.lastModel === "string" && + session.metadata.lastModel !== "" + ? session.metadata.lastModel + : undefined; + let ring = session.stats.calibrationRing; + if ( + !ring || + ring.origin !== settleOrigin || + (ring.model !== undefined && + settleModel !== undefined && + ring.model !== settleModel) + ) { + ring = { origin: settleOrigin, model: settleModel, values: [] }; + } else if (ring.model === undefined && settleModel !== undefined) { + ring.model = settleModel; + } + if ( + rawSample >= CALIBRATION_SAMPLE_MIN && + rawSample <= CALIBRATION_SAMPLE_MAX + ) { + ring.values.push(rawSample); + if (ring.values.length > CALIBRATION_SAMPLE_WINDOW) ring.values.shift(); + const spread = Math.max(...ring.values) / Math.min(...ring.values); + if ( + ring.values.length >= 2 && + spread <= CALIBRATION_CONSISTENCY_RATIO + ) { + const mean = + ring.values.reduce((a, b) => a + b, 0) / ring.values.length; + session.stats.calibratedEstimate = Math.min( + CALIBRATION_CLAMP_MAX, + Math.max(CALIBRATION_CLAMP_MIN, mean), + ); + session.stats.calibratedEstimateOrigin = settleOrigin; + // Provenance is the ring's model key, not this sample's stamp — + // an unknown-model settle continues a model-keyed ring without + // blanking the established provenance. + session.stats.calibratedEstimateModel = ring.model; + } else { + delete session.stats.calibratedEstimate; + delete session.stats.calibratedEstimateOrigin; + delete session.stats.calibratedEstimateModel; + } + } + session.stats.calibrationRing = ring; + } + // #1820: a real usage-grade sample supersedes the post-rebuild meter + // anchor immediately — no need to wait out its prepare budget. + clearPostRebuildAnchor(session); + // #1110: a real usage report retires the one-shot overflow arm. + delete session.stats.overflowArmTokens; + // #1595: a real report landing far below a stale-high nudge reference + // retires that reference too (one call covers all three lanes). + reanchorNudgeOnUsageDrop(session); + } + // #1933 F1: roll the pending pair forward to the current turn's value — + // it will be consumed by the NEXT report (or cleared when the lane + // provides none, so a stale pair can never be mispaired). + session.stats.lastLocalTextEstimate = localTextEstimate; + session.stats.lastLocalTextEstimateOrigin = + localTextEstimate !== undefined + ? normalizeUpstreamOrigin(s.upstream) + : undefined; + if (s.reportedCached !== null && s.total > 0) { + session.stats.cachedTokens += s.reportedCached; + session.stats.cacheSamples += 1; + } + // #2131: the credential fingerprint captured at the send chokepoint rides + // the seam slot — read it BEFORE recordCacheSample so the line it pushes + // already carries the identity (kp/kw) without a second slot lookup. + const curKeyFp = session.transient?.sentBody?.keyFp; + // #2350: the host's system-prompt fingerprint as noted for THIS request by + // fold-reconcile's wire sites (they precede this settle under the session + // lock). Sparse: lanes that never noted one (title-gen / compaction-trigger + // sidecars) carry no value and can neither flag nor advance the baseline. + const notedSys = session.metadata?.[METADATA_SYSTEM_FP] as + | { fp?: unknown } + | undefined; + const curSysFp = + typeof notedSys?.fp === "string" && notedSys.fp !== "" + ? notedSys.fp + : undefined; + // #2867: the canonical incoming fingerprint + compression mode ride along so + // recordCacheSample can tell a host-side prompt rewrite from bili's own + // projection/mode switch (responses lane only; other lanes omit both). + const curCanonFp = canonicalSysFpForSettle(session, s.protocol); + // Same lane-gate as the canon slot above: the mode stamp is written only by + // prepare-responses, so on a non-responses settle it would leak the last + // responses request's label into an inert-but-misleading line field. + const lastMode = + s.protocol === "responses" + ? (session.metadata?.[METADATA_LAST_RESPONSES_MODE] as unknown) + : undefined; + const led = getCacheLedger(session); + recordCacheSample(session, { + at: Date.now(), + input: s.total, + cached: s.reportedCached, + output: s.output, + protocol: s.protocol, + upstream: s.upstream, + keyFp: curKeyFp, + sysFp: curSysFp, + canonFp: curCanonFp, + mode: lastMode === "plugin" || lastMode === "proxy" ? lastMode : undefined, + }); + // #2131: per-call body-stability proof on the just-recorded line — the same + // pairing detectSeam uses (this request's forwarded body vs the previous + // settled one), so "prefix unchanged between calls" is stored data, not an + // interpretation. Digest equality decides; the LCP offset localizes where + // a divergence started when both full bodies were retained. + const curSlot = session.transient?.sentBody; + if (curSlot !== undefined) { + const curLine = led.lines[led.lines.length - 1]; + if (curLine !== undefined) { + curLine.bd = curSlot.digest; + const prevSlot = session.transient?.settledBody; + if (prevSlot !== undefined) { + if (curSlot.digest === prevSlot.digest) { + curLine.be = 1; + } else { + curLine.be = 0; + if (curSlot.full !== null && prevSlot.full !== null) { + const lcp = byteLcp(prevSlot.full, curSlot.full); + curLine.bl = lcp; + // Append/trim first: "the whole shorter payload survives" + // is anchored to the END of the payload and stays true on + // small bodies where the head threshold alone would lie. + // #2982: the would-be-mid branch pays one extra scan over + // the SHORTER body: when the first divergence sits at/past + // that body's message-array closing bracket, no shared + // history byte moved — only trailing top-level params + // (host-computed max_tokens/…) or an ephemeral tail note + // that appeared/vanished between requests differ (#2980). + // The shorter side is decisive: when one side grew the + // array, the LCP stops at ITS closing bracket (`]` vs `,`), + // which lies inside the LONGER side's array — parsing that + // side would misread the pair as mid. No array locatable + // (unparseable body) keeps the conservative pre-fix class. + const shorterFull = + prevSlot.full.length <= curSlot.full.length + ? prevSlot.full + : curSlot.full; + const arrClose = messagesArrayCloseOffset(shorterFull); + curLine.bs = + lcp >= Math.min(prevSlot.full.length, curSlot.full.length) - 64 + ? "append" + : lcp < 1024 + ? "head" + : arrClose !== null && lcp >= arrClose + ? "tail" + : "mid"; + } else { + curLine.bs = "unknown"; + } + } + } + } + } + // #1843 L1: the usage total is ground truth for what the route's vision + // encoder actually billed — fold any captured image facts into the learned + // per-route cost (no-op when the request carried no images or no capture). + settleImageLearning(session, s.total); + // #1592-family seam forensics: pair this settle with the body that was + // actually sent (noteForwardedBody), then keep it as the next pair's + // baseline. Lanes without body capture still get the aggregate flag. + detectSeam(session, led); + const seamBody = session.transient?.sentBody; + if (seamBody !== undefined) (session.transient ??= {}).settledBody = seamBody; + delete session.transient?.sentBody; + // #3023: settle the inbound pair with the same lifecycle — the next + // settle's client arm compares against THIS request's client view. + const seamIn = session.transient?.inBody; + if (seamIn !== undefined) (session.transient ??= {}).settledInBody = seamIn; + delete session.transient?.inBody; } /** [#1279] Price profile stamped by the last request (server.ts runPrepare). @@ -1495,49 +1989,49 @@ export function settleUsageReport( * finite non-negative numbers survive — a corrupt stamp degrades to the * kernel defaults instead of poisoning the report. */ function stampedPriceProfile(session: Session): PriceProfile | undefined { - const v = session.metadata?.cachePriceProfile; - if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; - const o = v as Record; - const out: PriceProfile = {}; - for (const key of ["w", "r", "q"] as const) { - const n = o[key]; - if (typeof n === "number" && Number.isFinite(n) && n >= 0) out[key] = n; - } - return Object.keys(out).length > 0 ? out : undefined; + const v = session.metadata?.cachePriceProfile; + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const o = v as Record; + const out: PriceProfile = {}; + for (const key of ["w", "r", "q"] as const) { + const n = o[key]; + if (typeof n === "number" && Number.isFinite(n) && n >= 0) out[key] = n; + } + return Object.keys(out).length > 0 ? out : undefined; } interface ModelSwitchEvent { - seq: number; - at: number; - from: string | null; - to: string; - input: number; - cached: number; - hitPct: number; - /** This sample's unexplained residual (tr) — the re-bill charged to the switch. */ - attributed: number; + seq: number; + at: number; + from: string | null; + to: string; + input: number; + cached: number; + hitPct: number; + /** This sample's unexplained residual (tr) — the re-bill charged to the switch. */ + attributed: number; } interface ModelSwitchStats { - count: number; - missedTokens: number; - events: ModelSwitchEvent[]; + count: number; + missedTokens: number; + events: ModelSwitchEvent[]; } interface InvalidationTokenBreakdown { - model: number; - key: number; - /** #2350: stable-prefix re-bill charged to host system-prompt rewrites. */ - prompt: number; - /** #2867: stable-prefix re-bill charged to bili's own compression-mode / - * projection switch (forwarded system flipped, incoming view unchanged). */ - projection: number; - wire: number; - upstream: number; - restart: number; - /** Residual stable-prefix miss NOT charged to any named cause — the true - * upstream TTL/eviction/wire-rewrite remainder (kernel cannot name it). */ - remaining: number; + model: number; + key: number; + /** #2350: stable-prefix re-bill charged to host system-prompt rewrites. */ + prompt: number; + /** #2867: stable-prefix re-bill charged to bili's own compression-mode / + * projection switch (forwarded system flipped, incoming view unchanged). */ + projection: number; + wire: number; + upstream: number; + restart: number; + /** Residual stable-prefix miss NOT charged to any named cause — the true + * upstream TTL/eviction/wire-rewrite remainder (kernel cannot name it). */ + remaining: number; } /** #2131: per-call outbound body stability (SHA-256 compared against the @@ -1545,442 +2039,738 @@ interface InvalidationTokenBreakdown { * provider-side cache behavior from bili-side rewrites. Computed at report * time from the unbounded line set; no new hot-path state. */ interface BodyStability { - /** Adjacent pairs where both bodies were captured (be defined). */ - paired: number; - /** be=1: byte-identical resends (transport retries, re-requests). */ - equal: number; - /** be=0: diverged; the five classes partition this count. */ - diverged: number; - /** Divergence inside the first 1 KiB — host-side parameter region (model/tools/sampling/system), NOT a history rewrite. */ - head: number; - /** Whole shorter payload survives ±64 closing-bracket bytes — pure tail growth/trim. */ - append: number; - /** Mid-history byte change — the shape a real rewrite has. */ - mid: number; - /** #2982: divergence at/past the shorter body's message-array closing bracket — trailing top-level params or ephemeral tail notes; shared history bytes untouched, prefix cache unaffected. */ - tail: number; - /** Diverged but offset unknown (bodies above BODY_FULL_CAP, digest-only mode). */ - unknownOffset: number; - /** Median/min hit rate per 20K-token input-size bucket — flat across sizes argues against KV-pool capacity thrashing. */ - sizeBuckets: Array<{ lo: number; hi: number; n: number; hitMedian: number; hitMin: number }>; - /** Median inter-request gap for low-hit (<80%) vs high-hit lines — comparable medians argue against TTL/gap expiry. */ - gapSplit: { lowHitMedGapMs: number | null; highHitMedGapMs: number | null }; + /** Adjacent pairs where both bodies were captured (be defined). */ + paired: number; + /** be=1: byte-identical resends (transport retries, re-requests). */ + equal: number; + /** be=0: diverged; the five classes partition this count. */ + diverged: number; + /** Divergence inside the first 1 KiB — host-side parameter region (model/tools/sampling/system), NOT a history rewrite. */ + head: number; + /** Whole shorter payload survives ±64 closing-bracket bytes — pure tail growth/trim. */ + append: number; + /** Mid-history byte change — the shape a real rewrite has. */ + mid: number; + /** #2982: divergence at/past the shorter body's message-array closing bracket — trailing top-level params or ephemeral tail notes; shared history bytes untouched, prefix cache unaffected. */ + tail: number; + /** Diverged but offset unknown (bodies above BODY_FULL_CAP, digest-only mode). */ + unknownOffset: number; + /** Median/min hit rate per 20K-token input-size bucket — flat across sizes argues against KV-pool capacity thrashing. */ + sizeBuckets: Array<{ + lo: number; + hi: number; + n: number; + hitMedian: number; + hitMin: number; + }>; + /** Median inter-request gap for low-hit (<80%) vs high-hit lines — comparable medians argue against TTL/gap expiry. */ + gapSplit: { lowHitMedGapMs: number | null; highHitMedGapMs: number | null }; } interface BiliCacheReport extends CacheReport { - stability: BodyStability; - /** #2131: line set widened with the per-call body-stability fields. */ - lines: Array; - modelSwitches: ModelSwitchStats; - /** #2131: relay account rotations (credential fingerprint changes) — - * the identity a URL-granular upstream switch cannot see. */ - keySwitches: ModelSwitchStats; - /** #2350: host system-prompt rewrites (system fingerprint changes between - * consecutive requests — the host edits its own instructions). Post-#2867 - * this section narrates HOST-side flips only; proxy-side mode switches - * appear under projSwitches. */ - promptSwitches: ModelSwitchStats; - /** #2867: proxy projection/mode switches (forwarded system flipped while - * the canonical incoming view stayed stable — bili's self-heal - * degrade-to-proxy re-hoisting mid-history developer items). */ - projSwitches: ModelSwitchStats; - wireSwitches: ModelSwitchStats; - upstreamSwitches: ModelSwitchStats; - restartDrops: ModelSwitchStats; - unmeasured: { samples: number; inputTokens: number }; - /** #1891: first-bill samples with no prior baseline — their uncached input - * is booked as new content, never as a prefix re-pay. */ - initialBills: { samples: number; inputTokens: number }; - invalidation: InvalidationTokenBreakdown; - seam: { suspects: number; missed: number; events: SeamEvent[]; providerSide: { count: number; missed: number }; providerTtl: { count: number; missed: number }; rewinds: { count: number; missed: number }; abortCorrelated: number; client: { count: number; missed: number } }; + stability: BodyStability; + /** #2131: line set widened with the per-call body-stability fields. */ + lines: Array< + CacheReportLine & { + bodyDigest?: string; + bodyEqual?: 0 | 1; + bodyLcp?: number; + bodyClass?: "head" | "append" | "mid" | "tail" | "unknown"; + keyFp?: string; + sysFp?: string; + seam?: 1; + prov?: "ttl" | "side" | "rewind" | "client"; + } + >; + modelSwitches: ModelSwitchStats; + /** #2131: relay account rotations (credential fingerprint changes) — + * the identity a URL-granular upstream switch cannot see. */ + keySwitches: ModelSwitchStats; + /** #2350: host system-prompt rewrites (system fingerprint changes between + * consecutive requests — the host edits its own instructions). Post-#2867 + * this section narrates HOST-side flips only; proxy-side mode switches + * appear under projSwitches. */ + promptSwitches: ModelSwitchStats; + /** #2867: proxy projection/mode switches (forwarded system flipped while + * the canonical incoming view stayed stable — bili's self-heal + * degrade-to-proxy re-hoisting mid-history developer items). */ + projSwitches: ModelSwitchStats; + wireSwitches: ModelSwitchStats; + upstreamSwitches: ModelSwitchStats; + restartDrops: ModelSwitchStats; + unmeasured: { samples: number; inputTokens: number }; + /** #1891: first-bill samples with no prior baseline — their uncached input + * is booked as new content, never as a prefix re-pay. */ + initialBills: { samples: number; inputTokens: number }; + invalidation: InvalidationTokenBreakdown; + seam: { + suspects: number; + missed: number; + events: SeamEvent[]; + providerSide: { count: number; missed: number }; + providerTtl: { count: number; missed: number }; + rewinds: { count: number; missed: number }; + abortCorrelated: number; + client: { count: number; missed: number }; + }; } export function buildSessionCacheReport(session: Session): BiliCacheReport { - const led = getCacheLedger(session); - // Effective profile = stamped value over kernel defaults (w=1, r=0.1, q=4), - // mirroring the per-field fallback inside computeFoldEconomics. Unstamped - // sessions keep the pre-#1279 Anthropic-ratio output byte-for-byte. - const price = stampedPriceProfile(session); - const effective: Required = { w: price?.w ?? 1, r: price?.r ?? 0.1, q: price?.q ?? 4 }; - const a = led.agg; - const totals: CacheTotals = { - requests: a.requests, - input: a.input, - cached: a.cached, - output: a.output, - hitPct: a.input > 0 ? round1((a.cached / a.input) * 100) : 0, - newContent: a.nc, - compRepay: a.cr, - ttlRepay: a.tr, - residual: a.input - a.cached - (a.nc + a.cr + a.tr), - balanced: true, - }; - totals.balanced = totals.residual === 0; - const folds = led.folds.map((f) => - computeFoldEconomics({ - seq: f.seq, - at: f.at, - S: f.S, - sigma: f.sigma, - Vprime: f.Vp ?? null, - hPct: f.hPct, - T: f.T, - requestsAfter: f.requestsAfter, - turnsToNextFold: f.k, - }, effective), - ); - // Unknown-cache samples are quarantined out of the rendered line set — they - // carry no measurable hit rate and would show as misleading 0% rows. - const knownLines = led.lines.filter((l) => l.unk !== 1); - const switchEvents = (flag: (l: LedgerLine) => boolean, value: (l: LedgerLine | undefined) => string | undefined, dim: "model" | "key" | "prompt" | "projection" | "wire" | "upstream"): ModelSwitchEvent[] => { - const evs: ModelSwitchEvent[] = []; - for (let i = 0; i < led.lines.length; i++) { - const l = led.lines[i]; - if (!l || l.unk === 1 || !flag(l)) continue; - // #2784: only lines where THIS dimension won the partition are narrated as events — a flip - // shadowed by a higher-priority cause on the same line stays on the line itself (flag + value), - // not in the narrative list. Lines persisted pre-#1847 have no `cause` field: keep their - // historical display so old ledgers render as before. - if (l.cause !== undefined && l.cause !== dim) continue; - // #1847: from = the last KNOWN line strictly before this one (its value is the pre-switch - // identity) — scanning past intervening unmeasured lines keeps the pair intact when a - // switch straddles an unknown-cache boundary. - let from: string | undefined; - for (let j = i - 1; j >= 0; j--) { - const p = led.lines[j]; - if (p && p.unk !== 1) { from = value(p); break; } - } - evs.push({ - seq: l.seq, - at: l.at, - from: from ?? null, - to: value(l) ?? "?", - input: l.input, - cached: l.cached, - hitPct: l.hitPct ?? 0, - // #1847: this event's share is the residual only when this dimension won the partition — - // a co-occurring higher-priority cause absorbs the charge into its own bucket instead. - // Lines persisted pre-#1847 have no `cause` field: keep their historical display (full tr), - // so old ledgers render as before and the header's cold-tail delta stays honest. - attributed: l.cause === dim || l.cause === undefined ? l.tr : 0, - }); - } - return evs; - }; - const restartEvents: ModelSwitchEvent[] = []; - for (const l of led.lines) { - if (l.rs !== 1 || l.unk === 1) continue; - restartEvents.push({ seq: l.seq, at: l.at, from: null, to: "(restart)", input: l.input, cached: l.cached, hitPct: l.hitPct ?? 0, attributed: l.cause === "restart" || l.cause === undefined ? l.tr : 0 }); - } - const invalidation: InvalidationTokenBreakdown = { - model: a.switchMissed, - key: a.keySwitchMissed, - prompt: a.promptSwitchMissed, - projection: a.projSwitchMissed, - wire: a.wireSwitchMissed, - upstream: a.upstreamSwitchMissed, - restart: a.restartDropMissed, - remaining: Math.max(0, a.tr - a.attributedMissed), - }; - // #2131: per-call body-stability proof + hit-rate context checks (size - // stratification, gap split) — computed from the stored line flags. - let paired = 0; - let equal = 0; - let head = 0; - let append = 0; - let mid = 0; - let tail = 0; - let unknownOffset = 0; - for (const l of knownLines) { - if (l.be === undefined) continue; - paired += 1; - if (l.be === 1) { equal += 1; continue; } - if (l.bs === "head") head += 1; - else if (l.bs === "append") append += 1; - else if (l.bs === "mid") mid += 1; - else if (l.bs === "tail") tail += 1; - else unknownOffset += 1; - } - const sizeBuckets: BodyStability["sizeBuckets"] = []; - { - const byLo = new Map(); - for (const l of knownLines) { - if (l.hitPct === null || l.input <= 0) continue; - const lo = Math.floor(l.input / SIZE_BUCKET_TOK) * SIZE_BUCKET_TOK; - const hits = byLo.get(lo); - if (hits) hits.push(l.hitPct); - else byLo.set(lo, [l.hitPct]); - } - for (const [lo, hits] of [...byLo.entries()].sort((x, y) => x[0] - y[0]).slice(0, 24)) { - sizeBuckets.push({ lo, hi: lo + SIZE_BUCKET_TOK, n: hits.length, hitMedian: median(hits) ?? 0, hitMin: Math.min(...hits) }); - } - } - const lowGaps: number[] = []; - const highGaps: number[] = []; - for (let i = 1; i < led.lines.length; i++) { - const p = led.lines[i - 1]; - const c = led.lines[i]; - if (!p || !c || c.hitPct === null) continue; - const gap = c.at - p.at; - if (!(gap > 0)) continue; - (c.hitPct < 80 ? lowGaps : highGaps).push(gap); - } - const stability: BodyStability = { - paired, - equal, - diverged: paired - equal, - head, - append, - mid, - tail, - unknownOffset, - sizeBuckets, - gapSplit: { lowHitMedGapMs: median(lowGaps), highHitMedGapMs: median(highGaps) }, - }; - return { - generatedAt: Date.now(), - profile: effective, - totals, - economics: summarizeFoldEconomics(folds), - folds, - lines: knownLines.map((l) => ({ - seq: l.seq, - at: l.at, - input: l.input, - cached: l.cached, - output: l.output, - hitPct: l.hitPct ?? 0, - missed: l.missed, - newContent: l.nc, - compRepay: l.cr, - ttlRepay: l.tr, - foldSeq: l.foldSeq, - seam: l.seam, - prov: l.prov, - bodyDigest: l.bd, - keyFp: l.kp, - sysFp: l.sp, - bodyEqual: l.be, - bodyLcp: l.bl, - bodyClass: l.bs, - })), - linesOmitted: led.sampleSeq - led.lines.length, - modelSwitches: { count: a.switches, missedTokens: a.switchMissed, events: switchEvents((l) => l.sw === 1 && l.model !== undefined, (l) => l?.model, "model") }, - keySwitches: { count: a.keySwitches, missedTokens: a.keySwitchMissed, events: switchEvents((l) => l.kw === 1 && l.kp !== undefined, (l) => l?.kp, "key") }, - promptSwitches: { count: a.promptSwitches, missedTokens: a.promptSwitchMissed, events: switchEvents((l) => l.sf === 1 && l.sp !== undefined, (l) => l?.sp, "prompt") }, - projSwitches: { count: a.projSwitches, missedTokens: a.projSwitchMissed, events: switchEvents((l) => l.pf === 1 && l.sp !== undefined, (l) => l?.sp, "projection") }, - wireSwitches: { count: a.wireSwitches, missedTokens: a.wireSwitchMissed, events: switchEvents((l) => l.pw === 1 && l.proto !== undefined, (l) => l?.proto, "wire") }, - upstreamSwitches: { count: a.upstreamSwitches, missedTokens: a.upstreamSwitchMissed, events: switchEvents((l) => l.uw === 1 && l.up !== undefined, (l) => l?.up, "upstream") }, - restartDrops: { count: a.restartDrops, missedTokens: a.restartDropMissed, events: restartEvents }, - unmeasured: { samples: a.unknownSamples, inputTokens: a.unknownInput }, - initialBills: { samples: a.nbSamples, inputTokens: a.nbInput }, - invalidation, - stability, - seam: { suspects: a.seamSuspects, missed: a.seamMissed, events: led.seamEvents ?? [], providerSide: { count: a.providerSideMisses, missed: a.providerSideMissed }, providerTtl: { count: a.providerTtlMisses, missed: a.providerTtlMissed }, rewinds: { count: a.rewinds, missed: a.rewindMissed }, abortCorrelated: a.abortCorrelated, client: { count: a.clientInserts, missed: a.clientInsertMissed } }, - }; + const led = getCacheLedger(session); + // Effective profile = stamped value over kernel defaults (w=1, r=0.1, q=4), + // mirroring the per-field fallback inside computeFoldEconomics. Unstamped + // sessions keep the pre-#1279 Anthropic-ratio output byte-for-byte. + const price = stampedPriceProfile(session); + const effective: Required = { + w: price?.w ?? 1, + r: price?.r ?? 0.1, + q: price?.q ?? 4, + }; + const a = led.agg; + const totals: CacheTotals = { + requests: a.requests, + input: a.input, + cached: a.cached, + output: a.output, + hitPct: a.input > 0 ? round1((a.cached / a.input) * 100) : 0, + newContent: a.nc, + compRepay: a.cr, + ttlRepay: a.tr, + residual: a.input - a.cached - (a.nc + a.cr + a.tr), + balanced: true, + }; + totals.balanced = totals.residual === 0; + const folds = led.folds.map((f) => + computeFoldEconomics( + { + seq: f.seq, + at: f.at, + S: f.S, + sigma: f.sigma, + Vprime: f.Vp ?? null, + hPct: f.hPct, + T: f.T, + requestsAfter: f.requestsAfter, + turnsToNextFold: f.k, + }, + effective, + ), + ); + // Unknown-cache samples are quarantined out of the rendered line set — they + // carry no measurable hit rate and would show as misleading 0% rows. + const knownLines = led.lines.filter((l) => l.unk !== 1); + const switchEvents = ( + flag: (l: LedgerLine) => boolean, + value: (l: LedgerLine | undefined) => string | undefined, + dim: "model" | "key" | "prompt" | "projection" | "wire" | "upstream", + ): ModelSwitchEvent[] => { + const evs: ModelSwitchEvent[] = []; + for (let i = 0; i < led.lines.length; i++) { + const l = led.lines[i]; + if (!l || l.unk === 1 || !flag(l)) continue; + // #2784: only lines where THIS dimension won the partition are narrated as events — a flip + // shadowed by a higher-priority cause on the same line stays on the line itself (flag + value), + // not in the narrative list. Lines persisted pre-#1847 have no `cause` field: keep their + // historical display so old ledgers render as before. + if (l.cause !== undefined && l.cause !== dim) continue; + // #1847: from = the last KNOWN line strictly before this one (its value is the pre-switch + // identity) — scanning past intervening unmeasured lines keeps the pair intact when a + // switch straddles an unknown-cache boundary. + let from: string | undefined; + for (let j = i - 1; j >= 0; j--) { + const p = led.lines[j]; + if (p && p.unk !== 1) { + from = value(p); + break; + } + } + evs.push({ + seq: l.seq, + at: l.at, + from: from ?? null, + to: value(l) ?? "?", + input: l.input, + cached: l.cached, + hitPct: l.hitPct ?? 0, + // #1847: this event's share is the residual only when this dimension won the partition — + // a co-occurring higher-priority cause absorbs the charge into its own bucket instead. + // Lines persisted pre-#1847 have no `cause` field: keep their historical display (full tr), + // so old ledgers render as before and the header's cold-tail delta stays honest. + attributed: l.cause === dim || l.cause === undefined ? l.tr : 0, + }); + } + return evs; + }; + const restartEvents: ModelSwitchEvent[] = []; + for (const l of led.lines) { + if (l.rs !== 1 || l.unk === 1) continue; + restartEvents.push({ + seq: l.seq, + at: l.at, + from: null, + to: "(restart)", + input: l.input, + cached: l.cached, + hitPct: l.hitPct ?? 0, + attributed: l.cause === "restart" || l.cause === undefined ? l.tr : 0, + }); + } + const invalidation: InvalidationTokenBreakdown = { + model: a.switchMissed, + key: a.keySwitchMissed, + prompt: a.promptSwitchMissed, + projection: a.projSwitchMissed, + wire: a.wireSwitchMissed, + upstream: a.upstreamSwitchMissed, + restart: a.restartDropMissed, + remaining: Math.max(0, a.tr - a.attributedMissed), + }; + // #2131: per-call body-stability proof + hit-rate context checks (size + // stratification, gap split) — computed from the stored line flags. + let paired = 0; + let equal = 0; + let head = 0; + let append = 0; + let mid = 0; + let tail = 0; + let unknownOffset = 0; + for (const l of knownLines) { + if (l.be === undefined) continue; + paired += 1; + if (l.be === 1) { + equal += 1; + continue; + } + if (l.bs === "head") head += 1; + else if (l.bs === "append") append += 1; + else if (l.bs === "mid") mid += 1; + else if (l.bs === "tail") tail += 1; + else unknownOffset += 1; + } + const sizeBuckets: BodyStability["sizeBuckets"] = []; + { + const byLo = new Map(); + for (const l of knownLines) { + if (l.hitPct === null || l.input <= 0) continue; + const lo = Math.floor(l.input / SIZE_BUCKET_TOK) * SIZE_BUCKET_TOK; + const hits = byLo.get(lo); + if (hits) hits.push(l.hitPct); + else byLo.set(lo, [l.hitPct]); + } + for (const [lo, hits] of [...byLo.entries()] + .sort((x, y) => x[0] - y[0]) + .slice(0, 24)) { + sizeBuckets.push({ + lo, + hi: lo + SIZE_BUCKET_TOK, + n: hits.length, + hitMedian: median(hits) ?? 0, + hitMin: Math.min(...hits), + }); + } + } + const lowGaps: number[] = []; + const highGaps: number[] = []; + for (let i = 1; i < led.lines.length; i++) { + const p = led.lines[i - 1]; + const c = led.lines[i]; + if (!p || !c || c.hitPct === null) continue; + const gap = c.at - p.at; + if (!(gap > 0)) continue; + (c.hitPct < 80 ? lowGaps : highGaps).push(gap); + } + const stability: BodyStability = { + paired, + equal, + diverged: paired - equal, + head, + append, + mid, + tail, + unknownOffset, + sizeBuckets, + gapSplit: { + lowHitMedGapMs: median(lowGaps), + highHitMedGapMs: median(highGaps), + }, + }; + return { + generatedAt: Date.now(), + profile: effective, + totals, + economics: summarizeFoldEconomics(folds), + folds, + lines: knownLines.map((l) => ({ + seq: l.seq, + at: l.at, + input: l.input, + cached: l.cached, + output: l.output, + hitPct: l.hitPct ?? 0, + missed: l.missed, + newContent: l.nc, + compRepay: l.cr, + ttlRepay: l.tr, + foldSeq: l.foldSeq, + seam: l.seam, + prov: l.prov, + bodyDigest: l.bd, + keyFp: l.kp, + sysFp: l.sp, + bodyEqual: l.be, + bodyLcp: l.bl, + bodyClass: l.bs, + })), + linesOmitted: led.sampleSeq - led.lines.length, + modelSwitches: { + count: a.switches, + missedTokens: a.switchMissed, + events: switchEvents( + (l) => l.sw === 1 && l.model !== undefined, + (l) => l?.model, + "model", + ), + }, + keySwitches: { + count: a.keySwitches, + missedTokens: a.keySwitchMissed, + events: switchEvents( + (l) => l.kw === 1 && l.kp !== undefined, + (l) => l?.kp, + "key", + ), + }, + promptSwitches: { + count: a.promptSwitches, + missedTokens: a.promptSwitchMissed, + events: switchEvents( + (l) => l.sf === 1 && l.sp !== undefined, + (l) => l?.sp, + "prompt", + ), + }, + projSwitches: { + count: a.projSwitches, + missedTokens: a.projSwitchMissed, + events: switchEvents( + (l) => l.pf === 1 && l.sp !== undefined, + (l) => l?.sp, + "projection", + ), + }, + wireSwitches: { + count: a.wireSwitches, + missedTokens: a.wireSwitchMissed, + events: switchEvents( + (l) => l.pw === 1 && l.proto !== undefined, + (l) => l?.proto, + "wire", + ), + }, + upstreamSwitches: { + count: a.upstreamSwitches, + missedTokens: a.upstreamSwitchMissed, + events: switchEvents( + (l) => l.uw === 1 && l.up !== undefined, + (l) => l?.up, + "upstream", + ), + }, + restartDrops: { + count: a.restartDrops, + missedTokens: a.restartDropMissed, + events: restartEvents, + }, + unmeasured: { samples: a.unknownSamples, inputTokens: a.unknownInput }, + initialBills: { samples: a.nbSamples, inputTokens: a.nbInput }, + invalidation, + stability, + seam: { + suspects: a.seamSuspects, + missed: a.seamMissed, + events: led.seamEvents ?? [], + providerSide: { + count: a.providerSideMisses, + missed: a.providerSideMissed, + }, + providerTtl: { count: a.providerTtlMisses, missed: a.providerTtlMissed }, + rewinds: { count: a.rewinds, missed: a.rewindMissed }, + abortCorrelated: a.abortCorrelated, + client: { count: a.clientInserts, missed: a.clientInsertMissed }, + }, + }; } /** Read-only switch stats for the web sessions table — returns null instead of * bootstrapping an empty ledger just to render zeros. */ -export function readModelSwitchStats(session: Session): { count: number; missedTokens: number } | null { - const raw = session.metadata?.[LEDGER_KEY]; - if (!raw || typeof raw !== "object") return null; - const led = raw as CacheLedger; - if (led.v !== 1) return null; - return { - count: typeof led.agg?.switches === "number" ? led.agg.switches : 0, - missedTokens: typeof led.agg?.switchMissed === "number" ? led.agg.switchMissed : 0, - }; +export function readModelSwitchStats( + session: Session, +): { count: number; missedTokens: number } | null { + const raw = session.metadata?.[LEDGER_KEY]; + if (!raw || typeof raw !== "object") return null; + const led = raw as CacheLedger; + if (led.v !== 1) return null; + return { + count: typeof led.agg?.switches === "number" ? led.agg.switches : 0, + missedTokens: + typeof led.agg?.switchMissed === "number" ? led.agg.switchMissed : 0, + }; } /** #2131: read-only KEY switch stats for the web sessions table — same * no-bootstrap contract as readModelSwitchStats. */ -export function readKeySwitchStats(session: Session): { count: number; missedTokens: number } | null { - const raw = session.metadata?.[LEDGER_KEY]; - if (!raw || typeof raw !== "object") return null; - const led = raw as CacheLedger; - if (led.v !== 1) return null; - return { - count: typeof led.agg?.keySwitches === "number" ? led.agg.keySwitches : 0, - missedTokens: typeof led.agg?.keySwitchMissed === "number" ? led.agg.keySwitchMissed : 0, - }; +export function readKeySwitchStats( + session: Session, +): { count: number; missedTokens: number } | null { + const raw = session.metadata?.[LEDGER_KEY]; + if (!raw || typeof raw !== "object") return null; + const led = raw as CacheLedger; + if (led.v !== 1) return null; + return { + count: typeof led.agg?.keySwitches === "number" ? led.agg.keySwitches : 0, + missedTokens: + typeof led.agg?.keySwitchMissed === "number" + ? led.agg.keySwitchMissed + : 0, + }; } /** #2350: read-only PROMPT switch stats for the web sessions table — same * no-bootstrap contract as readKeySwitchStats. */ -export function readPromptSwitchStats(session: Session): { count: number; missedTokens: number } | null { - const raw = session.metadata?.[LEDGER_KEY]; - if (!raw || typeof raw !== "object") return null; - const led = raw as CacheLedger; - if (led.v !== 1) return null; - return { - count: typeof led.agg?.promptSwitches === "number" ? led.agg.promptSwitches : 0, - missedTokens: typeof led.agg?.promptSwitchMissed === "number" ? led.agg.promptSwitchMissed : 0, - }; +export function readPromptSwitchStats( + session: Session, +): { count: number; missedTokens: number } | null { + const raw = session.metadata?.[LEDGER_KEY]; + if (!raw || typeof raw !== "object") return null; + const led = raw as CacheLedger; + if (led.v !== 1) return null; + return { + count: + typeof led.agg?.promptSwitches === "number" ? led.agg.promptSwitches : 0, + missedTokens: + typeof led.agg?.promptSwitchMissed === "number" + ? led.agg.promptSwitchMissed + : 0, + }; } /** #2867: read-only PROJECTION switch stats for the web sessions table — same * no-bootstrap contract as readPromptSwitchStats. */ -export function readProjSwitchStats(session: Session): { count: number; missedTokens: number } | null { - const raw = session.metadata?.[LEDGER_KEY]; - if (!raw || typeof raw !== "object") return null; - const led = raw as CacheLedger; - if (led.v !== 1) return null; - return { - count: typeof led.agg?.projSwitches === "number" ? led.agg.projSwitches : 0, - missedTokens: typeof led.agg?.projSwitchMissed === "number" ? led.agg.projSwitchMissed : 0, - }; +export function readProjSwitchStats( + session: Session, +): { count: number; missedTokens: number } | null { + const raw = session.metadata?.[LEDGER_KEY]; + if (!raw || typeof raw !== "object") return null; + const led = raw as CacheLedger; + if (led.v !== 1) return null; + return { + count: typeof led.agg?.projSwitches === "number" ? led.agg.projSwitches : 0, + missedTokens: + typeof led.agg?.projSwitchMissed === "number" + ? led.agg.projSwitchMissed + : 0, + }; } function formatStability(st: BodyStability): string { - if (st.paired === 0) return ""; - const out: string[] = ["BODY STABILITY (per-call outbound byte proof, vs previous settled request)"]; - out.push(` ${st.paired} pair(s): ${st.equal} byte-identical · ${st.diverged} diverged`); - out.push(` divergence class: head <1KiB ${st.head} · tail-append ${st.append} · mid-history ${st.mid} · tail(params/notes) ${st.tail} · offset-unknown(capped) ${st.unknownOffset}`); - if (st.head > 0) out.push(` ⚠ ${st.head} head-region divergence(s) — model/tools/sampling/system changed between calls (host-side parameter change, NOT a bili history rewrite)`); - if (st.mid > 0) out.push(` ⚠ ${st.mid} mid-history divergence(s) — real prefix rewrites; inspect the seam events above`); - if (st.tail > 0) out.push(` ${st.tail} tail-region divergence(s) — trailing top-level params or ephemeral tail notes at/past the message-array end; shared history bytes untouched, prefix cache unaffected (#2982)`); - const sb = st.sizeBuckets.filter((b) => b.n >= 3); - if (sb.length >= 2) out.push(" hit% by input size (median): " + sb.map((b) => `${Math.round(b.lo / 1000)}K=${b.hitMedian}%`).join(" ")); - const g = st.gapSplit; - if (g.lowHitMedGapMs !== null && g.highHitMedGapMs !== null) { - out.push(` inter-request gap median: low-hit(<80%) ${(g.lowHitMedGapMs / 1000).toFixed(1)}s vs high-hit ${(g.highHitMedGapMs / 1000).toFixed(1)}s`); - } - return out.join("\n"); + if (st.paired === 0) return ""; + const out: string[] = [ + "BODY STABILITY (per-call outbound byte proof, vs previous settled request)", + ]; + out.push( + ` ${st.paired} pair(s): ${st.equal} byte-identical · ${st.diverged} diverged`, + ); + out.push( + ` divergence class: head <1KiB ${st.head} · tail-append ${st.append} · mid-history ${st.mid} · tail(params/notes) ${st.tail} · offset-unknown(capped) ${st.unknownOffset}`, + ); + if (st.head > 0) + out.push( + ` ⚠ ${st.head} head-region divergence(s) — model/tools/sampling/system changed between calls (host-side parameter change, NOT a bili history rewrite)`, + ); + if (st.mid > 0) + out.push( + ` ⚠ ${st.mid} mid-history divergence(s) — real prefix rewrites; inspect the seam events above`, + ); + if (st.tail > 0) + out.push( + ` ${st.tail} tail-region divergence(s) — trailing top-level params or ephemeral tail notes at/past the message-array end; shared history bytes untouched, prefix cache unaffected (#2982)`, + ); + const sb = st.sizeBuckets.filter((b) => b.n >= 3); + if (sb.length >= 2) + out.push( + " hit% by input size (median): " + + sb.map((b) => `${Math.round(b.lo / 1000)}K=${b.hitMedian}%`).join(" "), + ); + const g = st.gapSplit; + if (g.lowHitMedGapMs !== null && g.highHitMedGapMs !== null) { + out.push( + ` inter-request gap median: low-hit(<80%) ${(g.lowHitMedGapMs / 1000).toFixed(1)}s vs high-hit ${(g.highHitMedGapMs / 1000).toFixed(1)}s`, + ); + } + return out.join("\n"); } -export function handleAcpCache(session: Session, args?: Record): ProxyToolResult { - try { - const detail = args?.detail === "full" ? "full" : "summary"; - const report = buildSessionCacheReport(session); - const stabilityText = formatStability(report.stability); - const tail = (base: string): string => base + (stabilityText ? "\n\n" + stabilityText : "") + (formatSeam(report) ? "\n\n" + formatSeam(report) : ""); - // #2131: key switches get their own section only when observed — the - // common case (one account, no rotation) stays byte-identical. - const keyText = report.keySwitches.count > 0 ? "\n\n" + formatModelSwitches(report.keySwitches, detail, "KEY SWITCHES (relay account rotation)") : ""; - // #2350: host system-prompt rewrites get their own section only when - // observed — sessions whose host never rewrites stay byte-identical. - const promptText = report.promptSwitches.count > 0 ? "\n\n" + formatModelSwitches(report.promptSwitches, detail, "PROMPT SWITCHES (host rewrote system prompt)") : ""; - // #2867: proxy-side mode/projection switches get their own section only - // when observed — a session that never switches modes stays byte-identical. - const projText = report.projSwitches.count > 0 ? "\n\n" + formatModelSwitches(report.projSwitches, detail, "PROJECTION SWITCHES (proxy mode/projection change — bili's own doing, e.g. self-heal degrade-to-proxy)") : ""; - if (detail === "full" && report.lines.length > FULL_DETAIL_LINES) { - const dropped = report.lines.length - FULL_DETAIL_LINES; - const capped = formatCacheReport( - { ...report, lines: report.lines.slice(-FULL_DETAIL_LINES), linesOmitted: report.linesOmitted + dropped }, - session.id, - { detail }, - ); - return toolOk(tail(capped + "\n\n" + formatModelSwitches(report.modelSwitches, detail) + keyText + promptText + projText + "\n\n" + formatInvalidation(report))); - } - return toolOk(tail(formatCacheReport(report, session.id, { detail }) + "\n\n" + formatModelSwitches(report.modelSwitches, detail) + keyText + promptText + projText + "\n\n" + formatInvalidation(report))); - } catch (err) { - loggerLog("warn", `[${session.id}] [acp_cache] report failed: ${String(err)}`); - return toolFail(`[acp_cache FAILED: ${String(err)}]`); - } +export function handleAcpCache( + session: Session, + args?: Record, +): ProxyToolResult { + try { + const detail = args?.detail === "full" ? "full" : "summary"; + const report = buildSessionCacheReport(session); + const stabilityText = formatStability(report.stability); + const tail = (base: string): string => + base + + (stabilityText ? "\n\n" + stabilityText : "") + + (formatSeam(report) ? "\n\n" + formatSeam(report) : ""); + // #2131: key switches get their own section only when observed — the + // common case (one account, no rotation) stays byte-identical. + const keyText = + report.keySwitches.count > 0 + ? "\n\n" + + formatModelSwitches( + report.keySwitches, + detail, + "KEY SWITCHES (relay account rotation)", + ) + : ""; + // #2350: host system-prompt rewrites get their own section only when + // observed — sessions whose host never rewrites stay byte-identical. + const promptText = + report.promptSwitches.count > 0 + ? "\n\n" + + formatModelSwitches( + report.promptSwitches, + detail, + "PROMPT SWITCHES (host rewrote system prompt)", + ) + : ""; + // #2867: proxy-side mode/projection switches get their own section only + // when observed — a session that never switches modes stays byte-identical. + const projText = + report.projSwitches.count > 0 + ? "\n\n" + + formatModelSwitches( + report.projSwitches, + detail, + "PROJECTION SWITCHES (proxy mode/projection change — bili's own doing, e.g. self-heal degrade-to-proxy)", + ) + : ""; + if (detail === "full" && report.lines.length > FULL_DETAIL_LINES) { + const dropped = report.lines.length - FULL_DETAIL_LINES; + const capped = formatCacheReport( + { + ...report, + lines: report.lines.slice(-FULL_DETAIL_LINES), + linesOmitted: report.linesOmitted + dropped, + }, + session.id, + { detail }, + ); + return toolOk( + tail( + capped + + "\n\n" + + formatModelSwitches(report.modelSwitches, detail) + + keyText + + promptText + + projText + + "\n\n" + + formatInvalidation(report), + ), + ); + } + return toolOk( + tail( + formatCacheReport(report, session.id, { detail }) + + "\n\n" + + formatModelSwitches(report.modelSwitches, detail) + + keyText + + promptText + + projText + + "\n\n" + + formatInvalidation(report), + ), + ); + } catch (err) { + loggerLog( + "warn", + `[${session.id}] [acp_cache] report failed: ${String(err)}`, + ); + return toolFail(`[acp_cache FAILED: ${String(err)}]`); + } } function fmtTok(n: number): string { - const v = Math.round(n); - return v >= 1e6 ? `${(v / 1e6).toFixed(2)}M` : v >= 1e4 ? `${(v / 1e3).toFixed(1)}K` : String(v); + const v = Math.round(n); + return v >= 1e6 + ? `${(v / 1e6).toFixed(2)}M` + : v >= 1e4 + ? `${(v / 1e3).toFixed(1)}K` + : String(v); } function fmtTime(at: number): string { - const d = new Date(at); - const p = (x: number) => String(x).padStart(2, "0"); - return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; + const d = new Date(at); + const p = (x: number) => String(x).padStart(2, "0"); + return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; } const SWITCH_LIST_CAP = 8; -function formatModelSwitches(sw: ModelSwitchStats, detail: "summary" | "full", title = "MODEL SWITCHES"): string { - const out: string[] = [title]; - if (sw.count === 0) { - out.push(" none observed"); - return out.join("\n"); - } - // #1847: missedTokens includes the bounded post-switch cold rounds (attributed to the switch but not - // discrete from→to events); surface that delta so the per-event list reconciles with the total. - const eventSum = sw.events.reduce((n, e) => n + e.attributed, 0); - const tail = sw.missedTokens - eventSum; - out.push(` ${sw.count} switch(es) · ${fmtTok(sw.missedTokens)} tok re-billed${tail > 0 ? ` (${fmtTok(tail)} on post-switch cold rounds)` : ""}`); - const shown = detail === "full" ? sw.events : sw.events.slice(-SWITCH_LIST_CAP); - for (const e of shown) { - out.push(` #${e.seq} ${fmtTime(e.at)} ${e.from ?? "?"} → ${e.to} · hit ${e.hitPct.toFixed(1)}% · attributed ${fmtTok(e.attributed)}`); - } - if (shown.length < sw.events.length) { - out.push(` … ${sw.events.length - shown.length} earlier switch(es) omitted (detail:"full" lists all)`); - } - return out.join("\n"); +function formatModelSwitches( + sw: ModelSwitchStats, + detail: "summary" | "full", + title = "MODEL SWITCHES", +): string { + const out: string[] = [title]; + if (sw.count === 0) { + out.push(" none observed"); + return out.join("\n"); + } + // #1847: missedTokens includes the bounded post-switch cold rounds (attributed to the switch but not + // discrete from→to events); surface that delta so the per-event list reconciles with the total. + const eventSum = sw.events.reduce((n, e) => n + e.attributed, 0); + const tail = sw.missedTokens - eventSum; + out.push( + ` ${sw.count} switch(es) · ${fmtTok(sw.missedTokens)} tok re-billed${tail > 0 ? ` (${fmtTok(tail)} on post-switch cold rounds)` : ""}`, + ); + const shown = + detail === "full" ? sw.events : sw.events.slice(-SWITCH_LIST_CAP); + for (const e of shown) { + out.push( + ` #${e.seq} ${fmtTime(e.at)} ${e.from ?? "?"} → ${e.to} · hit ${e.hitPct.toFixed(1)}% · attributed ${fmtTok(e.attributed)}`, + ); + } + if (shown.length < sw.events.length) { + out.push( + ` … ${sw.events.length - shown.length} earlier switch(es) omitted (detail:"full" lists all)`, + ); + } + return out.join("\n"); } function formatSeam(r: BiliCacheReport): string { - const out: string[] = []; - if (r.seam.suspects > 0) { - out.push("⚠ CACHE SEAM (suspected mid-history prefix breaks)"); - out.push(` ${r.seam.suspects} sample(s) · ${fmtTok(r.seam.missed)} tok re-billed with no fold/switch/restart attribution`); - for (const e of r.seam.events) { - out.push(` #${e.seq} ${fmtTime(e.at)} hit ${e.hitPct.toFixed(1)}% · input ${fmtTok(e.input)} · divergence ≥${fmtTok(e.lcpBytes)}B at message[${e.msgIndex ?? "?"}] of ${e.prevMsgs}→${e.curMsgs}`); - } - if (r.seam.events.length === 0) { - out.push(" (no body-pair forensics on this lane — aggregate flag only; report the session + log if this persists)"); - } - out.push(" if reproducible: /acp-cache detail:\"full\" + bili.log around the timestamps above (likely a #1548-family round-2/steady render seam)"); - } - if (r.seam.rewinds.count > 0) { - out.push("↩ HISTORY REWOUND (client revert/trim)"); - out.push(` ${r.seam.rewinds.count} sample(s) · ${fmtTok(r.seam.rewinds.missed)} tok re-billed once for the retained prefix — sanctioned client intent, not a rebuild seam`); - } - if (r.seam.providerTtl.count > 0) { - out.push("⏱ UPSTREAM TTL EXPIRY — NORMAL (long idle gap)"); - out.push(` ${r.seam.providerTtl.count} sample(s) · ${fmtTok(r.seam.providerTtl.missed)} tok — byte-stable/append-shaped misses settled more than ${Math.round(PROVIDER_TTL_GAP_MS / 60_000)} min after the previous sample: the upstream prefix cache simply aged out. Expected cost, not a failure.`); - } - if (r.seam.providerSide.count > 0) { - out.push("▲ PROVIDER-SIDE MISS (previous request's message list fully preserved)"); - out.push(` ${r.seam.providerSide.count} sample(s) · ${fmtTok(r.seam.providerSide.missed)} tok — the previous request's message list is preserved in this one (byte-for-byte under the 512 KiB forensics cap; above it, proven by the stable recorded head plus exact message-count growth — any difference is only the appended tail), and the sample arrived within ${Math.round(PROVIDER_TTL_GAP_MS / 60_000)} min of the previous one, so this is an ABNORMAL provider miss (eviction / relay node rotation), not TTL ageing. Not a bili rebuild seam.`); - out.push(` stateful-upstream check (#2483): if your upstream keeps a live session per conversation and validates the echoed history against its own transcript (claude-code-based relays such as magpie), bili's render tags on assistant text trip that check even though bili's own list is unchanged — set diagnostics.renderNone=true until per-route render-tags control ships; expect exactly ONE replay when flipping the flag mid-session`); - } - if (r.seam.client.count > 0) { - out.push("✎ CLIENT MID-HISTORY REWRITE (host-side insert — NOT a bili seam)"); - out.push(` ${r.seam.client.count} sample(s) · ${fmtTok(r.seam.client.missed)} tok — the client's own resent history broke mid-list, so bili's faithful rebuild carried the break to the wire (host plugin insert / paste hoisting / re-render). Client-owned re-bill, not a rebuild seam.`); - for (const e of r.seam.events) { - if (e.client) out.push(` #${e.seq} ${fmtTime(e.at)} hit ${e.hitPct.toFixed(1)}% · input ${fmtTok(e.input)} · inbound message[${e.client.idx}] ${e.client.role}/${e.client.cls} ${e.client.len}B JSON · outbound ${fmtTok(e.lcpBytes)}B @ message[${e.msgIndex ?? "?"}] of ${e.prevMsgs}→${e.curMsgs}`); - } - } - if (r.seam.abortCorrelated > 0) { - out.push("⏻ ABORT-CORRELATED"); - out.push(` ${r.seam.abortCorrelated} missed sample(s) within 30s of a client mid-stream abort — abort/retry churn rewrites the resent tail; correlation, not causation (see bili.log 'client aborted mid-stream')`); - } - return out.length > 0 ? out.join("\n") : ""; + const out: string[] = []; + if (r.seam.suspects > 0) { + out.push("⚠ CACHE SEAM (suspected mid-history prefix breaks)"); + out.push( + ` ${r.seam.suspects} sample(s) · ${fmtTok(r.seam.missed)} tok re-billed with no fold/switch/restart attribution`, + ); + for (const e of r.seam.events) { + out.push( + ` #${e.seq} ${fmtTime(e.at)} hit ${e.hitPct.toFixed(1)}% · input ${fmtTok(e.input)} · divergence ≥${fmtTok(e.lcpBytes)}B at message[${e.msgIndex ?? "?"}] of ${e.prevMsgs}→${e.curMsgs}`, + ); + } + if (r.seam.events.length === 0) { + out.push( + " (no body-pair forensics on this lane — aggregate flag only; report the session + log if this persists)", + ); + } + out.push( + ' if reproducible: /acp-cache detail:"full" + bili.log around the timestamps above (likely a #1548-family round-2/steady render seam)', + ); + } + if (r.seam.rewinds.count > 0) { + out.push("↩ HISTORY REWOUND (client revert/trim)"); + out.push( + ` ${r.seam.rewinds.count} sample(s) · ${fmtTok(r.seam.rewinds.missed)} tok re-billed once for the retained prefix — sanctioned client intent, not a rebuild seam`, + ); + } + if (r.seam.providerTtl.count > 0) { + out.push("⏱ UPSTREAM TTL EXPIRY — NORMAL (long idle gap)"); + out.push( + ` ${r.seam.providerTtl.count} sample(s) · ${fmtTok(r.seam.providerTtl.missed)} tok — byte-stable/append-shaped misses settled more than ${Math.round(PROVIDER_TTL_GAP_MS / 60_000)} min after the previous sample: the upstream prefix cache simply aged out. Expected cost, not a failure.`, + ); + } + if (r.seam.providerSide.count > 0) { + out.push( + "▲ PROVIDER-SIDE MISS (previous request's message list fully preserved)", + ); + out.push( + ` ${r.seam.providerSide.count} sample(s) · ${fmtTok(r.seam.providerSide.missed)} tok — the previous request's message list is preserved in this one (byte-for-byte under the 512 KiB forensics cap; above it, proven by the stable recorded head plus exact message-count growth — any difference is only the appended tail), and the sample arrived within ${Math.round(PROVIDER_TTL_GAP_MS / 60_000)} min of the previous one, so this is an ABNORMAL provider miss (eviction / relay node rotation), not TTL ageing. Not a bili rebuild seam.`, + ); + out.push( + ` stateful-upstream check (#2483): if your upstream keeps a live session per conversation and validates the echoed history against its own transcript (claude-code-based relays such as magpie), bili's render tags on assistant text trip that check even though bili's own list is unchanged — set diagnostics.renderNone=true until per-route render-tags control ships; expect exactly ONE replay when flipping the flag mid-session`, + ); + } + if (r.seam.client.count > 0) { + out.push( + "✎ CLIENT MID-HISTORY REWRITE (host-side insert — NOT a bili seam)", + ); + out.push( + ` ${r.seam.client.count} sample(s) · ${fmtTok(r.seam.client.missed)} tok — the client's own resent history broke mid-list, so bili's faithful rebuild carried the break to the wire (host plugin insert / paste hoisting / re-render). Client-owned re-bill, not a rebuild seam.`, + ); + for (const e of r.seam.events) { + if (e.client) + out.push( + ` #${e.seq} ${fmtTime(e.at)} hit ${e.hitPct.toFixed(1)}% · input ${fmtTok(e.input)} · inbound message[${e.client.idx}] ${e.client.role}/${e.client.cls} ${e.client.len}B JSON · outbound ${fmtTok(e.lcpBytes)}B @ message[${e.msgIndex ?? "?"}] of ${e.prevMsgs}→${e.curMsgs}`, + ); + } + } + if (r.seam.abortCorrelated > 0) { + out.push("⏻ ABORT-CORRELATED"); + out.push( + ` ${r.seam.abortCorrelated} missed sample(s) within 30s of a client mid-stream abort — abort/retry churn rewrites the resent tail; correlation, not causation (see bili.log 'client aborted mid-stream')`, + ); + } + return out.length > 0 ? out.join("\n") : ""; } function formatInvalidation(r: BiliCacheReport): string { - const b = r.invalidation; - const named = b.model + b.key + b.prompt + b.projection + b.wire + b.upstream + b.restart; - const total = named + b.remaining; - const out: string[] = ["CACHE INVALIDATION"]; - out.push(` stable-prefix re-bill by cause (mutually exclusive, sums to total): ${fmtTok(named)} tok charged · ${fmtTok(b.remaining)} tok unattributed (upstream TTL/eviction/wire rewrite)`); - out.push(` model switch: ${fmtTok(b.model)} (${r.modelSwitches.count})`); - out.push(` key switch: ${fmtTok(b.key)} (${r.keySwitches.count}) — relay account rotation, fingerprinted headers never logged raw`); - out.push(` prompt rewrite: ${fmtTok(b.prompt)} (${r.promptSwitches.count}) — host rewrote its system prompt between requests (#2350)`); - out.push(` projection switch: ${fmtTok(b.projection)} (${r.projSwitches.count}) — proxy switched compression mode/projection (self-heal degrade-to-proxy re-hoists mid-history developer items, #2867)`); - out.push(` wire switch: ${fmtTok(b.wire)} (${r.wireSwitches.count})`); - out.push(` upstream switch: ${fmtTok(b.upstream)} (${r.upstreamSwitches.count})`); - out.push(` restart/refork: ${fmtTok(b.restart)} (${r.restartDrops.count})`); - // #1847: a dominant unattributed residual with NO observed cause is the misleading case — the README - // triage order would steer users to "③ bili bug". Name it explicitly as expected provider-side behavior. - if (b.remaining > 0 && total > 0 && b.remaining / total >= 0.5) { - const pct = Math.round((b.remaining / total) * 100); - const noCauseEver = r.modelSwitches.count === 0 && r.keySwitches.count === 0 && r.promptSwitches.count === 0 && r.projSwitches.count === 0 && r.wireSwitches.count === 0 && r.upstreamSwitches.count === 0 && r.restartDrops.count === 0; - out.push(noCauseEver - ? ` ⚠ ${pct}% of your stable-prefix re-bill has no observable cause (no model/wire/upstream switch or restart seen) — expected provider-side behavior (cache TTL expiry / eviction / relay rotation), NOT a bili bug; if reproducible see #1195 coverage-mismatch` - : ` ⚠ ${pct}% of your stable-prefix re-bill is unnameable provider-side behavior (cache TTL expiry / eviction / relay rotation) beyond the causes listed above`); - } - if (r.unmeasured.samples > 0) { - out.push(` unmeasured (provider reported no cache tokens): ${r.unmeasured.samples} sample(s) · ${fmtTok(r.unmeasured.inputTokens)} tok — excluded from hit rate`); - } - if (r.initialBills.samples > 0) { - out.push(` initial bills (no prior baseline): ${r.initialBills.samples} sample(s) · ${fmtTok(r.initialBills.inputTokens)} tok — first request(s) of a session; booked as new content, not a prefix re-pay`); - } - return out.join("\n"); + const b = r.invalidation; + const named = + b.model + b.key + b.prompt + b.projection + b.wire + b.upstream + b.restart; + const total = named + b.remaining; + const out: string[] = ["CACHE INVALIDATION"]; + out.push( + ` stable-prefix re-bill by cause (mutually exclusive, sums to total): ${fmtTok(named)} tok charged · ${fmtTok(b.remaining)} tok unattributed (upstream TTL/eviction/wire rewrite)`, + ); + out.push( + ` model switch: ${fmtTok(b.model)} (${r.modelSwitches.count})`, + ); + out.push( + ` key switch: ${fmtTok(b.key)} (${r.keySwitches.count}) — relay account rotation, fingerprinted headers never logged raw`, + ); + out.push( + ` prompt rewrite: ${fmtTok(b.prompt)} (${r.promptSwitches.count}) — host rewrote its system prompt between requests (#2350)`, + ); + out.push( + ` projection switch: ${fmtTok(b.projection)} (${r.projSwitches.count}) — proxy switched compression mode/projection (self-heal degrade-to-proxy re-hoists mid-history developer items, #2867)`, + ); + out.push(` wire switch: ${fmtTok(b.wire)} (${r.wireSwitches.count})`); + out.push( + ` upstream switch: ${fmtTok(b.upstream)} (${r.upstreamSwitches.count})`, + ); + out.push( + ` restart/refork: ${fmtTok(b.restart)} (${r.restartDrops.count})`, + ); + // #1847: a dominant unattributed residual with NO observed cause is the misleading case — the README + // triage order would steer users to "③ bili bug". Name it explicitly as expected provider-side behavior. + if (b.remaining > 0 && total > 0 && b.remaining / total >= 0.5) { + const pct = Math.round((b.remaining / total) * 100); + const noCauseEver = + r.modelSwitches.count === 0 && + r.keySwitches.count === 0 && + r.promptSwitches.count === 0 && + r.projSwitches.count === 0 && + r.wireSwitches.count === 0 && + r.upstreamSwitches.count === 0 && + r.restartDrops.count === 0; + out.push( + noCauseEver + ? ` ⚠ ${pct}% of your stable-prefix re-bill has no observable cause (no model/wire/upstream switch or restart seen) — expected provider-side behavior (cache TTL expiry / eviction / relay rotation), NOT a bili bug; if reproducible see #1195 coverage-mismatch` + : ` ⚠ ${pct}% of your stable-prefix re-bill is unnameable provider-side behavior (cache TTL expiry / eviction / relay rotation) beyond the causes listed above`, + ); + } + if (r.unmeasured.samples > 0) { + out.push( + ` unmeasured (provider reported no cache tokens): ${r.unmeasured.samples} sample(s) · ${fmtTok(r.unmeasured.inputTokens)} tok — excluded from hit rate`, + ); + } + if (r.initialBills.samples > 0) { + out.push( + ` initial bills (no prior baseline): ${r.initialBills.samples} sample(s) · ${fmtTok(r.initialBills.inputTokens)} tok — first request(s) of a session; booked as new content, not a prefix re-pay`, + ); + } + return out.join("\n"); } diff --git a/src/cli.ts b/src/cli.ts index 9969cf73b3..22d9c70a01 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -29,16 +29,45 @@ import { configFile as defaultConfigFile } from "./paths.js"; import { log as loggerLog } from "./logger.js"; import { createAutoRestartHandler } from "./restart.js"; import { checkForUpdate, startAutoUpdate } from "./update.js"; -import { startAdvisoryWatcher, getAdvisoryState, advisoryDeferring, advisoryBlocksVersion } from "./advisory.js"; +import { + startAdvisoryWatcher, + advisoryDeferring, + advisoryBlocksVersion, +} from "./advisory.js"; import { startReleaseNotesWatcher } from "./update-notes.js"; import { resolveProxy } from "./upstream-proxy.js"; import { runMcpStdio } from "./mcp.js"; -import { PLUGIN_AGENTS, isPluginAgent, pluginInstall, pluginRemove, pluginStatusAll, pluginUpdate, renderPluginList, warnActivePluginSessions, type PluginAgent } from "./plugin-install.js"; -import { runLaunch, runTestPi, isLaunchClient, type ClientName } from "./launcher.js"; +import { + PLUGIN_AGENTS, + codexInstallWithService, + codexRemoveWithService, + isPluginAgent, + pluginInstall, + pluginRemove, + pluginStatusAll, + pluginUpdate, + renderPluginList, + warnActivePluginSessions, + type PluginAgent, +} from "./plugin-install.js"; +import { + runLaunch, + runTestPi, + isLaunchClient, + type ClientName, +} from "./launcher.js"; import { exportSession } from "./export.js"; import { renderJson, renderText, runDiff } from "./acp-cache-diff.js"; import { renderDoctorReport, runDoctor } from "./doctor.js"; import { VERSION, PACKAGE_NAME, BUILD_COMMIT } from "./version.js"; +import { + disableProxyService, + enableProxyService, + installProxyService, + proxyServiceStatus, + removeProxyService, + restartProxyService, +} from "./proxy-service/service.js"; const HELP = `bili ${VERSION} — billion-context proxy @@ -78,6 +107,8 @@ Usage: each (pure-append / mid-stream-rewrite / prefix-stable-miss); --json machine output, --log FILE correlates [acp-usage] lines (default /bili.log), --no-log skips, --session SID filters + bili service install|status|restart|enable|disable|remove + manage the per-user Windows logon proxy task bili update check for & install a newer version now bili doctor audit every install lane: versions, owners, freshness vs registry, running proxy processes @@ -157,516 +188,718 @@ Docs: https://github.com/ranxianglei/billion-context `; type Parsed = { - command: "start" | "update" | "doctor" | "help" | "version" | "launch" | "test" | "export" | "plugin-register" | "mcp" | "plugin" | "acp-cache"; - client?: ClientName; - clientArgs: string[]; - mitmDomains: string[]; - overrides: Record; - exportSelector?: string; - exportOutput?: string; - exportFull?: boolean; - exportJsonl?: boolean; - registerConversationId?: string; - pluginAction?: "install" | "remove" | "update" | "list"; - pluginAgent?: PluginAgent; - pluginWithMcp?: boolean; - acpCacheDir?: string; - acpCacheLog?: string; - acpCacheNoLog?: boolean; - acpCacheSession?: string; - jsonOutput?: boolean; - doctorJson?: boolean; + command: + | "start" + | "update" + | "doctor" + | "help" + | "version" + | "launch" + | "test" + | "export" + | "plugin-register" + | "mcp" + | "plugin" + | "acp-cache" + | "service"; + client?: ClientName; + clientArgs: string[]; + mitmDomains: string[]; + overrides: Record; + exportSelector?: string; + exportOutput?: string; + exportFull?: boolean; + exportJsonl?: boolean; + registerConversationId?: string; + pluginAction?: "install" | "remove" | "update" | "list"; + pluginAgent?: PluginAgent; + pluginWithMcp?: boolean; + acpCacheDir?: string; + acpCacheLog?: string; + acpCacheNoLog?: boolean; + acpCacheSession?: string; + jsonOutput?: boolean; + doctorJson?: boolean; + serviceAction?: + | "install" + | "status" + | "restart" + | "enable" + | "disable" + | "remove"; }; export function parseArgs(argv: string[]): Parsed { - const overrides: Record = {}; - let command: Parsed["command"] = "start"; - const positional: string[] = []; - let client: ClientName | undefined; - let clientArgs: string[] = []; - const mitmDomains: string[] = []; - let exportSelector: string | undefined; - let registerConversationId: string | undefined; - let exportOutput: string | undefined; - let exportFull = false; - let exportJsonl = false; - let pluginAction: Parsed["pluginAction"]; - let pluginAgent: Parsed["pluginAgent"]; - let pluginWithMcp = false; - let acpCacheDir: string | undefined; - let acpCacheLog: string | undefined; - let acpCacheNoLog = false; - let acpCacheSession: string | undefined; - let jsonOutput = false; - let doctorJson = false; + const overrides: Record = {}; + let command: Parsed["command"] = "start"; + const positional: string[] = []; + let client: ClientName | undefined; + let clientArgs: string[] = []; + const mitmDomains: string[] = []; + let exportSelector: string | undefined; + let registerConversationId: string | undefined; + let exportOutput: string | undefined; + let exportFull = false; + let exportJsonl = false; + let pluginAction: Parsed["pluginAction"]; + let pluginAgent: Parsed["pluginAgent"]; + let pluginWithMcp = false; + let acpCacheDir: string | undefined; + let acpCacheLog: string | undefined; + let acpCacheNoLog = false; + let acpCacheSession: string | undefined; + let jsonOutput = false; + let doctorJson = false; + let serviceAction: Parsed["serviceAction"]; - for (let i = 0; i < argv.length; i++) { - const a = argv[i]!; - if (!client && positional.length === 0 && isLaunchClient(a)) { - client = a; - const rest = argv.slice(i + 1); - // Consume a leading "--" separator (documented form: `bili [opts --] [args]`) - // so it is never forwarded to the client (clap-style parsers treat everything - // after "--" as positionals). - clientArgs = rest[0] === "--" ? rest.slice(1) : rest; - break; - } - switch (a) { - case "--help": - case "-h": - command = "help"; - break; - case "--version": - case "-V": - command = "version"; - break; - case "--debug": - overrides.ACP_DEBUG = "1"; - break; - case "--no-auto-update": - overrides.ACP_AUTO_UPDATE = "0"; - break; - case "--auto-restart-on-update": - overrides.ACP_AUTO_RESTART_ON_UPDATE = "1"; - break; - case "--passthrough": - overrides.ACP_PASSTHROUGH = "1"; - break; - case "--no-passthrough": - overrides.ACP_PASSTHROUGH = "0"; - break; - case "--mitm-domain": { - const val = argv[++i]; - if (val === undefined) { - console.error(`bili: ${a} requires a value`); - process.exit(2); - } - mitmDomains.push(val); - break; - } - case "--full": - exportFull = true; - break; - case "--jsonl": - exportJsonl = true; - break; - case "--output": { - const val = argv[++i]; - if (val === undefined) { - console.error(`bili: ${a} requires a value`); - process.exit(2); - } - exportOutput = val; - break; - } - case "--with-mcp": - pluginWithMcp = true; - break; - case "--json": - jsonOutput = true; - doctorJson = true; - break; - case "--no-log": - acpCacheNoLog = true; - break; - case "--log": { - const val = argv[++i]; - if (val === undefined) { - console.error(`bili: ${a} requires a value`); - process.exit(2); - } - acpCacheLog = val; - break; - } - case "--session": { - const val = argv[++i]; - if (val === undefined) { - console.error(`bili: ${a} requires a value`); - process.exit(2); - } - acpCacheSession = val; - break; - } - case "-F": - case "--port": - case "--host": - case "--config": - case "--origin": - case "--agent": - case "--bin": { - const val = argv[++i]; - if (val === undefined || val.length === 0) { - console.error(`bili: ${a} requires a non-empty value`); - process.exit(2); - } - if (a === "--port") overrides.ACP_PORT = val; - else if (a === "--host") overrides.ACP_HOST = val; - else if (a === "--config") overrides.BILI_CONFIG_FILE = val; - else if (a === "--origin") overrides.BILI_MCP_PROXY = val; - else if (a === "--bin") process.env.BILI_CLIENT_BIN = val; - else if (a === "-F") overrides.BILI_UPSTREAM_PROXY = val; - else overrides.BILI_PLUGIN_AGENT = val; - break; - } - default: - if (a.startsWith("--")) { - // Allow --port=9000 form. - const eq = a.indexOf("="); - if (eq > 0) { - argv.splice(i, 1, a.slice(0, eq), a.slice(eq + 1)); - i--; - break; - } - console.error(`bili: unknown option ${a}`); - process.exit(2); - } - positional.push(a); - } - } + for (let i = 0; i < argv.length; i++) { + const a = argv[i]!; + if (!client && positional.length === 0 && isLaunchClient(a)) { + client = a; + const rest = argv.slice(i + 1); + // Consume a leading "--" separator (documented form: `bili [opts --] [args]`) + // so it is never forwarded to the client (clap-style parsers treat everything + // after "--" as positionals). + clientArgs = rest[0] === "--" ? rest.slice(1) : rest; + break; + } + switch (a) { + case "--help": + case "-h": + command = "help"; + break; + case "--version": + case "-V": + command = "version"; + break; + case "--debug": + overrides.ACP_DEBUG = "1"; + break; + case "--no-auto-update": + overrides.ACP_AUTO_UPDATE = "0"; + break; + case "--auto-restart-on-update": + overrides.ACP_AUTO_RESTART_ON_UPDATE = "1"; + break; + case "--passthrough": + overrides.ACP_PASSTHROUGH = "1"; + break; + case "--no-passthrough": + overrides.ACP_PASSTHROUGH = "0"; + break; + case "--mitm-domain": { + const val = argv[++i]; + if (val === undefined) { + console.error(`bili: ${a} requires a value`); + process.exit(2); + } + mitmDomains.push(val); + break; + } + case "--full": + exportFull = true; + break; + case "--jsonl": + exportJsonl = true; + break; + case "--output": { + const val = argv[++i]; + if (val === undefined) { + console.error(`bili: ${a} requires a value`); + process.exit(2); + } + exportOutput = val; + break; + } + case "--with-mcp": + pluginWithMcp = true; + break; + case "--json": + jsonOutput = true; + doctorJson = true; + break; + case "--no-log": + acpCacheNoLog = true; + break; + case "--log": { + const val = argv[++i]; + if (val === undefined) { + console.error(`bili: ${a} requires a value`); + process.exit(2); + } + acpCacheLog = val; + break; + } + case "--session": { + const val = argv[++i]; + if (val === undefined) { + console.error(`bili: ${a} requires a value`); + process.exit(2); + } + acpCacheSession = val; + break; + } + case "-F": + case "--port": + case "--host": + case "--config": + case "--origin": + case "--agent": + case "--bin": { + const val = argv[++i]; + if (val === undefined || val.length === 0) { + console.error(`bili: ${a} requires a non-empty value`); + process.exit(2); + } + if (a === "--port") overrides.ACP_PORT = val; + else if (a === "--host") overrides.ACP_HOST = val; + else if (a === "--config") overrides.BILI_CONFIG_FILE = val; + else if (a === "--origin") overrides.BILI_MCP_PROXY = val; + else if (a === "--bin") process.env.BILI_CLIENT_BIN = val; + else if (a === "-F") overrides.BILI_UPSTREAM_PROXY = val; + else overrides.BILI_PLUGIN_AGENT = val; + break; + } + default: + if (a.startsWith("--")) { + // Allow --port=9000 form. + const eq = a.indexOf("="); + if (eq > 0) { + argv.splice(i, 1, a.slice(0, eq), a.slice(eq + 1)); + i--; + break; + } + console.error(`bili: unknown option ${a}`); + process.exit(2); + } + positional.push(a); + } + } - // First positional (if any) is the command. "start" | "update" | "test" - // are recognized; an unknown command is an error. - if (client) { - command = "launch"; - } else if (positional.length > 0) { - const cmd = positional[0]!; - if (cmd === "start") { - command = command === "help" || command === "version" ? command : "start"; - } else if (cmd === "update") { - command = "update"; - } else if (cmd === "doctor") { - command = "doctor"; - } else if (cmd === "export") { - command = "export"; - exportSelector = positional[1]; - } else if (cmd === "plugin-register") { - command = "plugin-register"; - registerConversationId = positional[1]; - } else if (cmd === "mcp") { - command = "mcp"; - } else if (cmd === "plugin") { - command = "plugin"; - const action = positional[1]; - if (action === "install" || action === "remove" || action === "update" || action === "list") { - pluginAction = action; - } else { - console.error(`bili plugin: unknown action "${action ?? ""}" (try "bili plugin install|remove|update|list ")`); - process.exit(2); - } - const agent = positional[2]; - if (agent !== undefined) { - if (!isPluginAgent(agent)) { - console.error(`bili plugin: unknown agent "${agent}" (try one of: ${PLUGIN_AGENTS.join(", ")})`); - process.exit(2); - } - pluginAgent = agent; - } - if (pluginAction !== "list" && pluginAction !== "update" && pluginAgent === undefined) { - console.error(`bili plugin ${pluginAction}: agent is required (try one of: ${PLUGIN_AGENTS.join(", ")})`); - process.exit(2); - } - } else if (cmd === "test") { - const target = positional[1]; - if (target && isLaunchClient(target)) { - command = "test"; - client = target; - } else { - console.error(`bili test: unknown client "${target ?? ""}" (try "bili test pi")`); - process.exit(2); - } - } else if (cmd === "acp-cache") { - command = "acp-cache"; - const action = positional[1]; - if (action !== "diff") { - console.error(`bili acp-cache: unknown action "${action ?? ""}" (try "bili acp-cache diff ")`); - process.exit(2); - } - acpCacheDir = positional[2]; - if (!acpCacheDir) { - console.error("bili acp-cache diff: dump-dir is required"); - process.exit(2); - } - } else { - console.error(`bili: unknown command "${cmd}" (try "bili --help")`); - process.exit(2); - } - } + // First positional (if any) is the command. "start" | "update" | "test" + // are recognized; an unknown command is an error. + if (client) { + command = "launch"; + } else if (positional.length > 0) { + const cmd = positional[0]!; + if (cmd === "start") { + command = command === "help" || command === "version" ? command : "start"; + } else if (cmd === "update") { + command = "update"; + } else if (cmd === "doctor") { + command = "doctor"; + } else if (cmd === "export") { + command = "export"; + exportSelector = positional[1]; + } else if (cmd === "service") { + command = "service"; + const action = positional[1]; + if ( + action === "install" || + action === "status" || + action === "restart" || + action === "enable" || + action === "disable" || + action === "remove" + ) { + serviceAction = action; + } else { + console.error( + `bili service: unknown action "${action ?? ""}" (try "bili service install|status|restart|enable|disable|remove")`, + ); + process.exit(2); + } + } else if (cmd === "plugin-register") { + command = "plugin-register"; + registerConversationId = positional[1]; + } else if (cmd === "mcp") { + command = "mcp"; + } else if (cmd === "plugin") { + command = "plugin"; + const action = positional[1]; + if ( + action === "install" || + action === "remove" || + action === "update" || + action === "list" + ) { + pluginAction = action; + } else { + console.error( + `bili plugin: unknown action "${action ?? ""}" (try "bili plugin install|remove|update|list ")`, + ); + process.exit(2); + } + const agent = positional[2]; + if (agent !== undefined) { + if (!isPluginAgent(agent)) { + console.error( + `bili plugin: unknown agent "${agent}" (try one of: ${PLUGIN_AGENTS.join(", ")})`, + ); + process.exit(2); + } + pluginAgent = agent; + } + if ( + pluginAction !== "list" && + pluginAction !== "update" && + pluginAgent === undefined + ) { + console.error( + `bili plugin ${pluginAction}: agent is required (try one of: ${PLUGIN_AGENTS.join(", ")})`, + ); + process.exit(2); + } + } else if (cmd === "test") { + const target = positional[1]; + if (target && isLaunchClient(target)) { + command = "test"; + client = target; + } else { + console.error( + `bili test: unknown client "${target ?? ""}" (try "bili test pi")`, + ); + process.exit(2); + } + } else if (cmd === "acp-cache") { + command = "acp-cache"; + const action = positional[1]; + if (action !== "diff") { + console.error( + `bili acp-cache: unknown action "${action ?? ""}" (try "bili acp-cache diff ")`, + ); + process.exit(2); + } + acpCacheDir = positional[2]; + if (!acpCacheDir) { + console.error("bili acp-cache diff: dump-dir is required"); + process.exit(2); + } + } else { + console.error(`bili: unknown command "${cmd}" (try "bili --help")`); + process.exit(2); + } + } - return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, jsonOutput, doctorJson }; + return { + command, + client, + clientArgs, + mitmDomains, + overrides, + exportSelector, + exportOutput, + exportFull, + exportJsonl, + registerConversationId, + pluginAction, + pluginAgent, + pluginWithMcp, + acpCacheDir, + acpCacheLog, + acpCacheNoLog, + acpCacheSession, + jsonOutput, + doctorJson, + serviceAction, + }; } export async function main(): Promise { - const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, jsonOutput, doctorJson } = parseArgs(process.argv.slice(2)); - if (command === "help") { - process.stdout.write(HELP); - return; - } - if (command === "version") { - // "0.1.187 (8f9faf9e)" — the commit identifies the exact build for - // locally-installed test trees whose semver matches a released version. - process.stdout.write(`${VERSION} (${BUILD_COMMIT})\n`); - return; - } - if (command === "acp-cache") { - try { - const report = runDiff(acpCacheDir!, { logFile: acpCacheLog, noLog: acpCacheNoLog, session: acpCacheSession }); - process.stdout.write(jsonOutput ? renderJson(report) : renderText(report)); - } catch (error) { - console.error(`bili acp-cache: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - } - return; - } - if (command === "plugin-register") { - const conversationId = registerConversationId?.trim(); - if (!conversationId) { - console.error('bili plugin-register: conversation id is required (e.g. bili plugin-register "$CLAUDE_SESSION_ID" --origin http://127.0.0.1:8787 --agent claude)'); - process.exit(2); - } - const agent = (overrides.BILI_PLUGIN_AGENT ?? process.env.BILI_PLUGIN_AGENT ?? "claude").trim() || "claude"; - const origin = (overrides.BILI_MCP_PROXY ?? process.env.BILI_MCP_PROXY ?? "http://127.0.0.1:8787").replace(/\/$/, ""); - try { - const res = await fetch(`${origin}/__bili/plugin/register`, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ conversationId, agent, identity: true }), - signal: AbortSignal.timeout(5000), - }); - const data = (await res.json()) as { ok?: boolean; error?: string }; - if (!res.ok || !data.ok) throw new Error(data.error ?? `HTTP ${res.status}`); - } catch (error) { - console.error(`bili plugin-register: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - } - return; - } - if (command === "mcp") { - runMcpStdio(); - return; - } - if (command === "plugin") { - // Installers read resolveProxyOrigin() (env first) at dispatch time. - // Apply --origin BEFORE handling the subcommand: the generic env - // merge further down runs only on the server path, which this - // branch returns ahead of — without this, a stale ~/.bili/ - // proxy-origin discovery file would silently win over the flag. - if (overrides.BILI_MCP_PROXY !== undefined) process.env.BILI_MCP_PROXY = overrides.BILI_MCP_PROXY; - if (pluginAction === "list") { - process.stdout.write(renderPluginList(pluginStatusAll())); - return; - } - if (pluginAction === "update") { - // Same updater egress/channel wiring as `bili update` (#609): the - // dsh lane resolves the latest registry version and the global - // check downloads through the same proxy decision as model - // traffic. - for (const [k, v] of Object.entries(overrides)) { - if (v !== undefined) process.env[k] = v; - } - let updaterResolveProxy: ((url: string) => string | undefined) | undefined; - let updateTag: string | undefined; - try { - const o = loadOptions(); - updaterResolveProxy = (url) => resolveProxy(o.routes, o.proxy, url, o.proxyFallback); - updateTag = o.updateTag; - } catch { - // config unloadable — updater egress goes direct - } - try { - const lines = await pluginUpdate(pluginAgent ? [pluginAgent] : undefined, { - packageName: PACKAGE_NAME, - resolveProxy: updaterResolveProxy, - updateTag, - globalCheck: () => checkForUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, true), - log: (_level, msg) => console.log(msg), - }); - for (const line of lines) console.log(line); - } catch (error) { - console.error(`bili plugin: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - } - return; - } - if (pluginAction === "install") { - try { - console.log(pluginInstall(pluginAgent!, { withMcp: pluginWithMcp })); - } catch (error) { - console.error(`bili plugin: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - } - return; - } - if (pluginAction === "remove") { - try { - // #2155: best-effort note about still-open client windows. - const removed = pluginRemove(pluginAgent!); - const warn = await warnActivePluginSessions(pluginAgent!); - console.log(warn === "" ? removed : removed + "\n" + warn); - } catch (error) { - console.error(`bili plugin: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - } - return; - } - } - if (command === "export") { - try { - const text = await exportSession(exportSelector, { output: exportOutput, full: exportFull, jsonl: exportJsonl }); - process.stdout.write(text + "\n"); - } catch (error) { - console.error(`bili export: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - } - return; - } - if (command === "doctor") { - // Read-only lane audit (#1235). Same egress/channel wiring as `bili - // update` so the registry freshness check honors -F and updateTag. - for (const [k, v] of Object.entries(overrides)) { - if (v !== undefined) process.env[k] = v; - } - let updaterResolveProxy: ((url: string) => string | undefined) | undefined; - let updateTag: string | undefined; - let advisoryUrl: string | undefined; - try { - const o = loadOptions(); - updaterResolveProxy = (url) => resolveProxy(o.routes, o.proxy, url, o.proxyFallback); - updateTag = o.updateTag; - advisoryUrl = o.advisoryUrl; - } catch { - // config unloadable — registry egress goes direct - } - try { - const report = await runDoctor({ packageName: PACKAGE_NAME, runningVersion: VERSION, resolveProxy: updaterResolveProxy, updateTag, advisoryUrl }); - process.stdout.write(doctorJson ? JSON.stringify(report, null, 2) + "\n" : renderDoctorReport(report)); - } catch (error) { - console.error(`bili doctor: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - } - return; - } - if (command === "update") { - // Manual one-shot update — bypasses the throttle. Apply flag - // overrides first so `-F ` reaches loadOptions; the registry - // and tarball egress then honor the same upstream-proxy decision as - // model traffic (#609), and the configured channel (updateTag) so - // `bili update` follows the same dist-tag as the background - // auto-updater. - for (const [k, v] of Object.entries(overrides)) { - if (v !== undefined) process.env[k] = v; - } - let updaterResolveProxy: ((url: string) => string | undefined) | undefined; - let updateTag: string | undefined; - try { - const o = loadOptions(); - updaterResolveProxy = (url) => resolveProxy(o.routes, o.proxy, url, o.proxyFallback); - updateTag = o.updateTag; - } catch (e) { - console.error(`bili update: config load failed (${String(e)}); updater egress goes direct`); - } - await checkForUpdate( - { packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, - true, - ); - return; - } - if (command === "test") { - if (client === "pi") { - await runTestPi({ overrides, mitmDomains }); - return; - } - console.error("bili test: only 'pi' supported for now"); - process.exit(2); - } - if (command === "launch") { - await runLaunch({ client: client!, clientArgs, mitmDomains, overrides }); - return; - } + const { + command, + client, + clientArgs, + mitmDomains, + overrides, + exportSelector, + exportOutput, + exportFull, + exportJsonl, + registerConversationId, + pluginAction, + pluginAgent, + pluginWithMcp, + acpCacheDir, + acpCacheLog, + acpCacheNoLog, + acpCacheSession, + jsonOutput, + doctorJson, + serviceAction, + } = parseArgs(process.argv.slice(2)); + if (command === "help") { + process.stdout.write(HELP); + return; + } + if (command === "version") { + // "0.1.187 (8f9faf9e)" — the commit identifies the exact build for + // locally-installed test trees whose semver matches a released version. + process.stdout.write(`${VERSION} (${BUILD_COMMIT})\n`); + return; + } + if (command === "acp-cache") { + try { + const report = runDiff(acpCacheDir!, { + logFile: acpCacheLog, + noLog: acpCacheNoLog, + session: acpCacheSession, + }); + process.stdout.write( + jsonOutput ? renderJson(report) : renderText(report), + ); + } catch (error) { + console.error( + `bili acp-cache: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + } + return; + } + if (command === "plugin-register") { + const conversationId = registerConversationId?.trim(); + if (!conversationId) { + console.error( + 'bili plugin-register: conversation id is required (e.g. bili plugin-register "$CLAUDE_SESSION_ID" --origin http://127.0.0.1:8787 --agent claude)', + ); + process.exit(2); + } + const agent = + ( + overrides.BILI_PLUGIN_AGENT ?? + process.env.BILI_PLUGIN_AGENT ?? + "claude" + ).trim() || "claude"; + const origin = ( + overrides.BILI_MCP_PROXY ?? + process.env.BILI_MCP_PROXY ?? + "http://127.0.0.1:8787" + ).replace(/\/$/, ""); + try { + const res = await fetch(`${origin}/__bili/plugin/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId, agent, identity: true }), + signal: AbortSignal.timeout(5000), + }); + const data = (await res.json()) as { ok?: boolean; error?: string }; + if (!res.ok || !data.ok) + throw new Error(data.error ?? `HTTP ${res.status}`); + } catch (error) { + console.error( + `bili plugin-register: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + } + return; + } + if (command === "mcp") { + runMcpStdio(); + return; + } + if (command === "service") { + const operations = { + install: installProxyService, + status: proxyServiceStatus, + restart: restartProxyService, + enable: enableProxyService, + disable: disableProxyService, + remove: removeProxyService, + } as const; + const result = await operations[serviceAction!](); + process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); + if (!result.ok) process.exitCode = 1; + return; + } + if (command === "plugin") { + // Installers read resolveProxyOrigin() (env first) at dispatch time. + // Apply --origin BEFORE handling the subcommand: the generic env + // merge further down runs only on the server path, which this + // branch returns ahead of — without this, a stale ~/.bili/ + // proxy-origin discovery file would silently win over the flag. + if (overrides.BILI_MCP_PROXY !== undefined) + process.env.BILI_MCP_PROXY = overrides.BILI_MCP_PROXY; + if (pluginAction === "list") { + process.stdout.write(renderPluginList(pluginStatusAll())); + return; + } + if (pluginAction === "update") { + // Same updater egress/channel wiring as `bili update` (#609): the + // dsh lane resolves the latest registry version and the global + // check downloads through the same proxy decision as model + // traffic. + for (const [k, v] of Object.entries(overrides)) { + if (v !== undefined) process.env[k] = v; + } + let updaterResolveProxy: + | ((url: string) => string | undefined) + | undefined; + let updateTag: string | undefined; + try { + const o = loadOptions(); + updaterResolveProxy = (url) => + resolveProxy(o.routes, o.proxy, url, o.proxyFallback); + updateTag = o.updateTag; + } catch { + // config unloadable — updater egress goes direct + } + try { + const lines = await pluginUpdate( + pluginAgent ? [pluginAgent] : undefined, + { + packageName: PACKAGE_NAME, + resolveProxy: updaterResolveProxy, + updateTag, + globalCheck: () => + checkForUpdate( + { + packageName: PACKAGE_NAME, + currentVersion: VERSION, + autoUpdate: true, + resolveProxy: updaterResolveProxy, + updateTag, + }, + true, + ), + log: (_level, msg) => console.log(msg), + }, + ); + for (const line of lines) console.log(line); + } catch (error) { + console.error( + `bili plugin: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + } + return; + } + if (pluginAction === "install") { + try { + // #ticket-linux-service: the codex lane installs the per-user + // proxy service alongside its config faces ("installed" must + // mean usable — MCP only discovers a proxy, never starts one). + // Other agents keep the plain synchronous writers. + console.log( + pluginAgent === "codex" + ? await codexInstallWithService() + : pluginInstall(pluginAgent!, { withMcp: pluginWithMcp }), + ); + } catch (error) { + console.error( + `bili plugin: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + } + return; + } + if (pluginAction === "remove") { + try { + // #2155: best-effort note about still-open client windows. + const removed = + pluginAgent === "codex" + ? await codexRemoveWithService() + : pluginRemove(pluginAgent!); + const warn = await warnActivePluginSessions(pluginAgent!); + console.log(warn === "" ? removed : removed + "\n" + warn); + } catch (error) { + console.error( + `bili plugin: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + } + return; + } + } + if (command === "export") { + try { + const text = await exportSession(exportSelector, { + output: exportOutput, + full: exportFull, + jsonl: exportJsonl, + }); + process.stdout.write(text + "\n"); + } catch (error) { + console.error( + `bili export: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + } + return; + } + if (command === "doctor") { + // Read-only lane audit (#1235). Same egress/channel wiring as `bili + // update` so the registry freshness check honors -F and updateTag. + for (const [k, v] of Object.entries(overrides)) { + if (v !== undefined) process.env[k] = v; + } + let updaterResolveProxy: ((url: string) => string | undefined) | undefined; + let updateTag: string | undefined; + let advisoryUrl: string | undefined; + try { + const o = loadOptions(); + updaterResolveProxy = (url) => + resolveProxy(o.routes, o.proxy, url, o.proxyFallback); + updateTag = o.updateTag; + advisoryUrl = o.advisoryUrl; + } catch { + // config unloadable — registry egress goes direct + } + try { + const report = await runDoctor({ + packageName: PACKAGE_NAME, + runningVersion: VERSION, + resolveProxy: updaterResolveProxy, + updateTag, + advisoryUrl, + }); + process.stdout.write( + doctorJson + ? JSON.stringify(report, null, 2) + "\n" + : renderDoctorReport(report), + ); + } catch (error) { + console.error( + `bili doctor: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + } + return; + } + if (command === "update") { + // Manual one-shot update — bypasses the throttle. Apply flag + // overrides first so `-F ` reaches loadOptions; the registry + // and tarball egress then honor the same upstream-proxy decision as + // model traffic (#609), and the configured channel (updateTag) so + // `bili update` follows the same dist-tag as the background + // auto-updater. + for (const [k, v] of Object.entries(overrides)) { + if (v !== undefined) process.env[k] = v; + } + let updaterResolveProxy: ((url: string) => string | undefined) | undefined; + let updateTag: string | undefined; + try { + const o = loadOptions(); + updaterResolveProxy = (url) => + resolveProxy(o.routes, o.proxy, url, o.proxyFallback); + updateTag = o.updateTag; + } catch (e) { + console.error( + `bili update: config load failed (${String(e)}); updater egress goes direct`, + ); + } + await checkForUpdate( + { + packageName: PACKAGE_NAME, + currentVersion: VERSION, + autoUpdate: true, + resolveProxy: updaterResolveProxy, + updateTag, + }, + true, + ); + return; + } + if (command === "test") { + if (client === "pi") { + await runTestPi({ overrides, mitmDomains }); + return; + } + console.error("bili test: only 'pi' supported for now"); + process.exit(2); + } + if (command === "launch") { + await runLaunch({ client: client!, clientArgs, mitmDomains, overrides }); + return; + } - for (const [k, v] of Object.entries(overrides)) { - if (v !== undefined) process.env[k] = v; - } + for (const [k, v] of Object.entries(overrides)) { + if (v !== undefined) process.env[k] = v; + } - // CLI flags override env (which overrides the config file inside - // loadOptions). Merge into process.env so loadOptions picks them up. - // First run: seed a template config so the user has a file to edit rather - // than a bare error. No-op if it already exists. - ensureConfigTemplate(); - const opts = loadOptions(); - // #2833: SQLite engine self-bootstrap — bounded (~10s) and fail-safe; only - // fetches when unified storage is requested AND no builtin/host engine - // exists, so the common case costs nothing. Must complete before the first - // session store opens (the store resolves its engine at construction). - await ensureSqliteEngine({ - resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), - }); - const server = await startServer(opts); + // CLI flags override env (which overrides the config file inside + // loadOptions). Merge into process.env so loadOptions picks them up. + // First run: seed a template config so the user has a file to edit rather + // than a bare error. No-op if it already exists. + ensureConfigTemplate(); + const opts = loadOptions(); + // #2833: SQLite engine self-bootstrap — bounded (~10s) and fail-safe; only + // fetches when unified storage is requested AND no builtin/host engine + // exists, so the common case costs nothing. Must complete before the first + // session store opens (the store resolves its engine at construction). + await ensureSqliteEngine({ + resolveProxy: (url) => + resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), + }); + const server = await startServer(opts); - // Start background auto-update after the server is listening so a slow - // registry check never delays startup or races the listen socket. - if (opts.autoUpdate) { - // Resolver reads opts fields per call, so web-UI hot-reload of proxy - // settings (server.ts mutates opts in place) is picked up live (#609). - startAutoUpdate({ - packageName: PACKAGE_NAME, - currentVersion: VERSION, - autoUpdate: true, - resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), - updateTag: opts.updateTag, - // F2 (review): an advisory whose target cannot be resolved on the - // registry must not stall the normal self-update loop forever — - // advisoryDeferring() goes false while lastError says "cannot resolve". - advisoryActive: advisoryDeferring, - // #1588-A: even when no advisory is active against this machine, - // never install a candidate that falls inside a freshly parsed - // affected range (rollback-form advisories cover latest too). - advisoryBlocksVersion, - onStaleInstall: createAutoRestartHandler({ - enabled: opts.autoRestartOnUpdate ?? false, - packageName: PACKAGE_NAME, - server, - host: opts.host, - portProvider: () => { - const addr = server.address(); - return addr && typeof addr === "object" ? addr.port : opts.port; - }, - log: loggerLog, - destroyLingeringSockets: restartForceCloseOf(server), - }), - }); - } - // #1481: the advisory watcher runs independently of autoUpdate — its whole - // point is to reach installs whose auto-update is off. - if (opts.advisoryCheck) { - startAdvisoryWatcher({ - packageName: PACKAGE_NAME, - currentVersion: VERSION, - advisoryUrl: opts.advisoryUrl, - resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), - onStaleInstall: createAutoRestartHandler({ - enabled: opts.autoRestartOnUpdate ?? false, - packageName: PACKAGE_NAME, - server, - host: opts.host, - portProvider: () => { - const addr = server.address(); - return addr && typeof addr === "object" ? addr.port : opts.port; - }, - log: loggerLog, - destroyLingeringSockets: restartForceCloseOf(server), - }), - }); - } - // #1870 release-notes visibility (#1977 silent by default) — fetch + - // cache only (never installs, never restarts). Runs independently of - // autoUpdate for the same reason as the advisory watcher: installs with - // auto-update off still deserve to learn when a critical-tier fix exists. - if (opts.releaseNotesCheck) { - startReleaseNotesWatcher({ - packageName: PACKAGE_NAME, - currentVersion: VERSION, - releaseNotesUrl: opts.releaseNotesUrl, - resolveProxy: (url) => resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), - }); - } + // Start background auto-update after the server is listening so a slow + // registry check never delays startup or races the listen socket. + if (opts.autoUpdate) { + // Resolver reads opts fields per call, so web-UI hot-reload of proxy + // settings (server.ts mutates opts in place) is picked up live (#609). + startAutoUpdate({ + packageName: PACKAGE_NAME, + currentVersion: VERSION, + autoUpdate: true, + resolveProxy: (url) => + resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), + updateTag: opts.updateTag, + // F2 (review): an advisory whose target cannot be resolved on the + // registry must not stall the normal self-update loop forever — + // advisoryDeferring() goes false while lastError says "cannot resolve". + advisoryActive: advisoryDeferring, + // #1588-A: even when no advisory is active against this machine, + // never install a candidate that falls inside a freshly parsed + // affected range (rollback-form advisories cover latest too). + advisoryBlocksVersion, + onStaleInstall: createAutoRestartHandler({ + enabled: opts.autoRestartOnUpdate ?? false, + packageName: PACKAGE_NAME, + server, + host: opts.host, + portProvider: () => { + const addr = server.address(); + return addr && typeof addr === "object" ? addr.port : opts.port; + }, + log: loggerLog, + destroyLingeringSockets: restartForceCloseOf(server), + }), + }); + } + // #1481: the advisory watcher runs independently of autoUpdate — its whole + // point is to reach installs whose auto-update is off. + if (opts.advisoryCheck) { + startAdvisoryWatcher({ + packageName: PACKAGE_NAME, + currentVersion: VERSION, + advisoryUrl: opts.advisoryUrl, + resolveProxy: (url) => + resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), + onStaleInstall: createAutoRestartHandler({ + enabled: opts.autoRestartOnUpdate ?? false, + packageName: PACKAGE_NAME, + server, + host: opts.host, + portProvider: () => { + const addr = server.address(); + return addr && typeof addr === "object" ? addr.port : opts.port; + }, + log: loggerLog, + destroyLingeringSockets: restartForceCloseOf(server), + }), + }); + } + // #1870 release-notes visibility (#1977 silent by default) — fetch + + // cache only (never installs, never restarts). Runs independently of + // autoUpdate for the same reason as the advisory watcher: installs with + // auto-update off still deserve to learn when a critical-tier fix exists. + if (opts.releaseNotesCheck) { + startReleaseNotesWatcher({ + packageName: PACKAGE_NAME, + currentVersion: VERSION, + releaseNotesUrl: opts.releaseNotesUrl, + resolveProxy: (url) => + resolveProxy(opts.routes, opts.proxy, url, opts.proxyFallback), + }); + } } diff --git a/src/doctor.ts b/src/doctor.ts index 2e339c41ba..b4f3f85e33 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -7,103 +7,166 @@ import fs from "node:fs"; import path from "node:path"; import { isPidAlive, listInstances, procMainScript } from "./instance.js"; -import { PLUGIN_AGENTS, UPDATE_CHANNEL, claudeDesktopPresent, inspectLanePresence, type PluginAgent } from "./plugin-install.js"; -import { findInstallDir, fetchRegistryVersion, hostManagedInstall, isGitWorkingTree, isVersionNewer, lastUpdateCheckTime, normalizeUpdateTag, staleInstallStatus } from "./update.js"; -import { describeAdvisory, evaluateAdvisories, type AdvisoryEvaluation } from "./advisory.js"; +import { + PLUGIN_AGENTS, + UPDATE_CHANNEL, + claudeDesktopPresent, + inspectLanePresence, + type PluginAgent, +} from "./plugin-install.js"; +import { + findInstallDir, + fetchRegistryVersion, + hostManagedInstall, + isGitWorkingTree, + isVersionNewer, + lastUpdateCheckTime, + normalizeUpdateTag, + staleInstallStatus, +} from "./update.js"; +import { + describeAdvisory, + evaluateAdvisories, + type AdvisoryEvaluation, +} from "./advisory.js"; import { claudeRoutingWarningFile } from "./paths.js"; +import { + inspectCodexIntegration, + type CodexIntegrationReport, +} from "./codex-integration/status.js"; +import { + detectCcSwitch, + type CcSwitchDetection, +} from "./codex-integration/cc-switch.js"; +import { + chatGptDesktopCapability, + type ChatGptDesktopCapability, +} from "./codex-integration/chatgpt-capability.js"; type LaneVerdict = "ok" | "stale" | "frozen" | "broken" | "absent"; interface DoctorGlobalInfo { - installDir?: string; - form: "npm" | "checkout" | "host-managed" | "unknown"; - owner?: string; - channel?: string; - diskVersion?: string; - runningVersion: string; - registryVersion?: string; - updateTag: string; - lastCheckTime?: number; - verdict: LaneVerdict; - reason?: string; - /** Read-only advisory evaluation against the on-disk version (#1577). */ - advisory?: AdvisoryEvaluation; + installDir?: string; + form: "npm" | "checkout" | "host-managed" | "unknown"; + owner?: string; + channel?: string; + diskVersion?: string; + runningVersion: string; + registryVersion?: string; + updateTag: string; + lastCheckTime?: number; + verdict: LaneVerdict; + reason?: string; + /** Read-only advisory evaluation against the on-disk version (#1577). */ + advisory?: AdvisoryEvaluation; } export interface DoctorLane { - agent: string; - kind: "reference" | "host-managed"; - installed: boolean; - detail: string; - targetExists?: boolean; - copyVersion?: string; - registryVersion?: string; - channel?: string; - verdict: LaneVerdict; - reason?: string; - /** Advisory notes that do not affect the verdict — e.g. #2290: the claude - * lane is healthy, but a co-installed Claude Desktop will bypass it. */ - warnings?: string[]; + agent: string; + kind: "reference" | "host-managed"; + installed: boolean; + detail: string; + targetExists?: boolean; + copyVersion?: string; + registryVersion?: string; + channel?: string; + verdict: LaneVerdict; + reason?: string; + /** Advisory notes that do not affect the verdict — e.g. #2290: the claude + * lane is healthy, but a co-installed Claude Desktop will bypass it. */ + warnings?: string[]; } export interface DoctorProcess { - instanceId: string; - pid: number; - port: number; - origin: string; - startedAt: number; - alive: boolean; - runningFrom?: string; - staleCopy?: boolean; + instanceId: string; + pid: number; + port: number; + origin: string; + startedAt: number; + alive: boolean; + runningFrom?: string; + staleCopy?: boolean; } export interface DoctorReport { - generatedAt: number; - packageName: string; - global: DoctorGlobalInfo; - lanes: DoctorLane[]; - processes: DoctorProcess[]; + generatedAt: number; + packageName: string; + global: DoctorGlobalInfo; + lanes: DoctorLane[]; + processes: DoctorProcess[]; + codexIntegration: CodexIntegrationReport; + ccSwitch: CcSwitchDetection; + chatGptDesktop: ChatGptDesktopCapability; } interface DoctorOpts { - packageName: string; - runningVersion: string; - resolveProxy?: (url: string) => string | undefined; - updateTag?: string; - advisoryUrl?: string; + packageName: string; + runningVersion: string; + resolveProxy?: (url: string) => string | undefined; + updateTag?: string; + advisoryUrl?: string; } interface LaneCtx { - packageName: string; - global: DoctorGlobalInfo; + packageName: string; + global: DoctorGlobalInfo; } -const REFERENCE_LANES = new Set(["omp", "claude", "codex", "kimi", "zcode", "hermes"]); +const REFERENCE_LANES = new Set([ + "omp", + "claude", + "codex", + "kimi", + "zcode", + "hermes", +]); function pkgVersionAt(rootDir: string): string | undefined { - try { - const v = (JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8")) as { version?: unknown }).version; - return typeof v === "string" ? v : undefined; - } catch { - return undefined; - } + try { + const v = ( + JSON.parse( + fs.readFileSync(path.join(rootDir, "package.json"), "utf8"), + ) as { version?: unknown } + ).version; + return typeof v === "string" ? v : undefined; + } catch { + return undefined; + } } /** Pure verdict logic (#1235): absent < broken < frozen < stale < ok. A * missing target beats a local pin because a dead entry means the host is * currently broken, not merely un-updatable. */ -export function laneVerdict(args: { installed: boolean; targetMissing: boolean; frozen: boolean; copyVersion?: string; registryVersion?: string }): LaneVerdict { - if (!args.installed) return "absent"; - if (args.targetMissing) return "broken"; - if (args.frozen) return "frozen"; - if (args.copyVersion !== undefined && args.registryVersion !== undefined && isVersionNewer(args.registryVersion, args.copyVersion)) return "stale"; - return "ok"; +export function laneVerdict(args: { + installed: boolean; + targetMissing: boolean; + frozen: boolean; + copyVersion?: string; + registryVersion?: string; +}): LaneVerdict { + if (!args.installed) return "absent"; + if (args.targetMissing) return "broken"; + if (args.frozen) return "frozen"; + if ( + args.copyVersion !== undefined && + args.registryVersion !== undefined && + isVersionNewer(args.registryVersion, args.copyVersion) + ) + return "stale"; + return "ok"; } -export function globalVerdict(g: Pick): LaneVerdict { - if (g.form === "checkout") return "frozen"; - if (g.diskVersion !== undefined && g.registryVersion !== undefined && isVersionNewer(g.registryVersion, g.diskVersion)) return "stale"; - return "ok"; +export function globalVerdict( + g: Pick, +): LaneVerdict { + if (g.form === "checkout") return "frozen"; + if ( + g.diskVersion !== undefined && + g.registryVersion !== undefined && + isVersionNewer(g.registryVersion, g.diskVersion) + ) + return "stale"; + return "ok"; } /** #2891 (#953/#1803): dsh resolves bare bundle names installation-anchor-first, so a @@ -111,211 +174,403 @@ export function globalVerdict(g: Pick { - const tag = normalizeUpdateTag(opts.updateTag); - const [installDir, registryVersion, lastCheck] = await Promise.all([ - findInstallDir(opts.packageName), - fetchRegistryVersion({ resolveProxy: opts.resolveProxy, updateTag: tag }, opts.packageName).catch(() => undefined), - lastUpdateCheckTime(), - ]); - const gitTree = installDir !== undefined ? await isGitWorkingTree(installDir) : false; - const managed = installDir !== undefined ? hostManagedInstall(installDir) : undefined; - const diskVersion = installDir !== undefined ? pkgVersionAt(installDir) : undefined; - const form: DoctorGlobalInfo["form"] = installDir === undefined ? "unknown" : gitTree ? "checkout" : managed !== undefined ? "host-managed" : "npm"; - // #1577: read-only advisory check against the on-disk version (what a next - // start would load), independent of the advisoryCheck opt-out — doctor is a - // diagnostic, not the auto-updater. Fail-open: a failed source yields - // { error }, never a throw. - const advisory = await evaluateAdvisories({ - version: diskVersion ?? opts.runningVersion, - advisoryUrl: opts.advisoryUrl, - resolveProxy: opts.resolveProxy, - }); - const g: DoctorGlobalInfo = { - installDir, - form, - owner: managed?.owner, - channel: managed?.channel, - diskVersion, - runningVersion: opts.runningVersion, - registryVersion, - updateTag: tag, - lastCheckTime: lastCheck, - verdict: globalVerdict({ form, diskVersion, registryVersion }), - advisory, - }; - if (g.verdict === "frozen") g.reason = "source checkout — rebuild manually (npm run build); bili refuses to auto-update a working tree (#580)"; - else if (g.verdict === "stale") g.reason = managed !== undefined ? `newer on registry ${tag}: update through ${managed.owner}'s updater` : `newer on registry ${tag}: run 'bili update'`; - else if (form !== "unknown" && staleInstallStatus(diskVersion, opts.runningVersion) === "restart") g.reason = `running process is behind the on-disk install (v${opts.runningVersion} → v${diskVersion}) — restart bili`; - if (registryVersion === undefined) g.reason = g.reason ? `${g.reason}; registry unreachable — freshness unknown` : "registry unreachable — freshness unknown"; + const tag = normalizeUpdateTag(opts.updateTag); + const [installDir, registryVersion, lastCheck] = await Promise.all([ + findInstallDir(opts.packageName), + fetchRegistryVersion( + { resolveProxy: opts.resolveProxy, updateTag: tag }, + opts.packageName, + ).catch(() => undefined), + lastUpdateCheckTime(), + ]); + const gitTree = + installDir !== undefined ? await isGitWorkingTree(installDir) : false; + const managed = + installDir !== undefined ? hostManagedInstall(installDir) : undefined; + const diskVersion = + installDir !== undefined ? pkgVersionAt(installDir) : undefined; + const form: DoctorGlobalInfo["form"] = + installDir === undefined + ? "unknown" + : gitTree + ? "checkout" + : managed !== undefined + ? "host-managed" + : "npm"; + // #1577: read-only advisory check against the on-disk version (what a next + // start would load), independent of the advisoryCheck opt-out — doctor is a + // diagnostic, not the auto-updater. Fail-open: a failed source yields + // { error }, never a throw. + const advisory = await evaluateAdvisories({ + version: diskVersion ?? opts.runningVersion, + advisoryUrl: opts.advisoryUrl, + resolveProxy: opts.resolveProxy, + }); + const g: DoctorGlobalInfo = { + installDir, + form, + owner: managed?.owner, + channel: managed?.channel, + diskVersion, + runningVersion: opts.runningVersion, + registryVersion, + updateTag: tag, + lastCheckTime: lastCheck, + verdict: globalVerdict({ form, diskVersion, registryVersion }), + advisory, + }; + if (g.verdict === "frozen") + g.reason = + "source checkout — rebuild manually (npm run build); bili refuses to auto-update a working tree (#580)"; + else if (g.verdict === "stale") + g.reason = + managed !== undefined + ? `newer on registry ${tag}: update through ${managed.owner}'s updater` + : `newer on registry ${tag}: run 'bili update'`; + else if ( + form !== "unknown" && + staleInstallStatus(diskVersion, opts.runningVersion) === "restart" + ) + g.reason = `running process is behind the on-disk install (v${opts.runningVersion} → v${diskVersion}) — restart bili`; + if (registryVersion === undefined) + g.reason = g.reason + ? `${g.reason}; registry unreachable — freshness unknown` + : "registry unreachable — freshness unknown"; - const lanes: DoctorLane[] = []; - for (const agent of PLUGIN_AGENTS) { - try { - lanes.push(...laneRowsFor(agent, inspectLanePresence(agent), registryVersion, { packageName: opts.packageName, global: g })); - } catch (err) { - lanes.push({ - agent, - kind: REFERENCE_LANES.has(agent) ? "reference" : "host-managed", - installed: false, - detail: `probe failed: ${err instanceof Error ? err.message : String(err)}`, - channel: UPDATE_CHANNEL[agent], - verdict: "broken", - }); - } - } + const lanes: DoctorLane[] = []; + for (const agent of PLUGIN_AGENTS) { + try { + lanes.push( + ...laneRowsFor(agent, inspectLanePresence(agent), registryVersion, { + packageName: opts.packageName, + global: g, + }), + ); + } catch (err) { + lanes.push({ + agent, + kind: REFERENCE_LANES.has(agent) ? "reference" : "host-managed", + installed: false, + detail: `probe failed: ${err instanceof Error ? err.message : String(err)}`, + channel: UPDATE_CHANNEL[agent], + verdict: "broken", + }); + } + } - const processes = listInstances().map((e) => { - const alive = isPidAlive(e.pid); - const runningFrom = alive ? procMainScript(e.pid) : undefined; - return { - instanceId: e.instanceId, - pid: e.pid, - port: e.port, - origin: e.origin, - startedAt: e.startedAt, - alive, - runningFrom, - staleCopy: runningFrom !== undefined && installDir !== undefined && !runningFrom.startsWith(installDir + path.sep), - }; - }); + const processes = listInstances().map((e) => { + const alive = isPidAlive(e.pid); + const runningFrom = alive ? procMainScript(e.pid) : undefined; + return { + instanceId: e.instanceId, + pid: e.pid, + port: e.port, + origin: e.origin, + startedAt: e.startedAt, + alive, + runningFrom, + staleCopy: + runningFrom !== undefined && + installDir !== undefined && + !runningFrom.startsWith(installDir + path.sep), + }; + }); - return { generatedAt: Date.now(), packageName: opts.packageName, global: g, lanes, processes }; + const codexIntegration = await inspectCodexIntegration(); + const ccSwitch = detectCcSwitch(); + return { + generatedAt: Date.now(), + packageName: opts.packageName, + global: g, + lanes, + processes, + codexIntegration, + ccSwitch, + chatGptDesktop: chatGptDesktopCapability, + }; } -function laneRowsFor(agent: PluginAgent, presence: ReturnType, registryVersion: string | undefined, ctx: LaneCtx): DoctorLane[] { - const kind = REFERENCE_LANES.has(agent) ? "reference" : "host-managed"; - const base: Omit = { - kind, - registryVersion, - channel: UPDATE_CHANNEL[agent], - }; - if (agent === "dsh" && presence.profiles !== undefined) { - return presence.profiles.map((p) => { - const missing = p.bundleInstalled && p.copyVersion === undefined; - const row: DoctorLane = { - ...base, - agent: `dsh:${p.name}`, - installed: true, - detail: p.spec !== undefined ? `dep spec: ${p.spec}${p.pinned ? " (local pin — dev lane, manual)" : ""}` : "(no dep spec)", - copyVersion: p.copyVersion, - verdict: laneVerdict({ installed: true, targetMissing: missing, frozen: p.pinned, copyVersion: p.copyVersion, registryVersion }), - }; - if (row.verdict === "frozen") row.reason = "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)"; - else if (row.verdict === "broken") row.reason = "profile depends on billion-context but the bundle copy is missing — rerun 'bili plugin install dsh'"; - const shadow = dshBundleShadowWarning({ packageName: ctx.packageName, globalInstallDir: ctx.global.installDir, globalDiskVersion: ctx.global.diskVersion, profileName: p.name, bundleInstalled: p.bundleInstalled, profileCopyVersion: p.copyVersion }); - if (shadow !== undefined) row.warnings = [...(row.warnings ?? []), shadow]; - return row; - }); - } - const targetsExist = presence.targets.length > 0 ? presence.targets.every((t) => fs.existsSync(t)) : undefined; - const missingTargets = presence.targets.filter((t) => !fs.existsSync(t)); - let detail = presence.pointers.length > 0 ? presence.pointers.join("; ") : presence.installed ? "installed" : "not installed"; - if (agent === "pi" && presence.form === "npm" && presence.targets.length === 0) detail += "; pi materializes the npm copy on next startup"; - const row: DoctorLane = { - ...base, - agent, - installed: presence.installed, - detail, - targetExists: targetsExist, - copyVersion: presence.copyVersion, - verdict: laneVerdict({ installed: presence.installed, targetMissing: missingTargets.length > 0, frozen: false, copyVersion: presence.copyVersion, registryVersion }), - }; - if (row.verdict === "broken") row.reason = missingTargets.map((t) => `target missing: ${t}`).join("; "); - if (agent === "opencode" && presence.installed && presence.form === "npm") { - // #1234/#2199: the cache copy is bili-owned in place (self-updates via its - // own proxy) — show the actual load path + disk version when resolvable so - // the stale verdict below is honest, not "version not resolvable". - const cp = presence.copyVersion !== undefined ? ` v${presence.copyVersion}` : ""; - const p = presence.targets[0] !== undefined ? ` (${presence.targets[0]})` : ""; - row.detail += `; cache copy${p}${cp} is bili-owned and self-updates in place via its own proxy (#1234) — reload/restart OpenCode to activate a disk update`; - } - if (agent === "claude" && presence.installed) { - // #2290: the lane itself is healthy, but a co-installed Claude Desktop - // overrides the managed ANTHROPIC_BASE_URL — desktop sessions then get - // neither bili compression nor native auto-compact. Advisory only: never - // change the verdict. Two sources: standing disk evidence + the last - // hook-detected bypass (its stderr is invisible outside debug mode). - const warnings: string[] = []; - if (claudeDesktopPresent()) { - warnings.push("Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL, so desktop sessions bypass bili entirely AND lose native auto-compact (managed block sets DISABLE_AUTO_COMPACT=1) — #2290"); - } - try { - const rec = JSON.parse(fs.readFileSync(claudeRoutingWarningFile(), "utf8")) as { at?: unknown; reasons?: unknown }; - if (Array.isArray(rec.reasons) && rec.reasons.length > 0 && rec.reasons.every((r) => typeof r === "string")) { - const at = typeof rec.at === "number" ? ` at ${new Date(rec.at).toISOString()}` : ""; - warnings.push(`last SessionStart hook detected a routing bypass${at}: ${(rec.reasons as string[]).join("; ")}`); - } - } catch { - // no marker or unreadable — nothing to surface - } - if (warnings.length > 0) row.warnings = warnings; - } - return [row]; +function laneRowsFor( + agent: PluginAgent, + presence: ReturnType, + registryVersion: string | undefined, + ctx: LaneCtx, +): DoctorLane[] { + const kind = REFERENCE_LANES.has(agent) ? "reference" : "host-managed"; + const base: Omit< + DoctorLane, + | "agent" + | "installed" + | "detail" + | "targetExists" + | "copyVersion" + | "verdict" + | "reason" + > = { + kind, + registryVersion, + channel: UPDATE_CHANNEL[agent], + }; + if (agent === "dsh" && presence.profiles !== undefined) { + return presence.profiles.map((p) => { + const missing = p.bundleInstalled && p.copyVersion === undefined; + const row: DoctorLane = { + ...base, + agent: `dsh:${p.name}`, + installed: true, + detail: + p.spec !== undefined + ? `dep spec: ${p.spec}${p.pinned ? " (local pin — dev lane, manual)" : ""}` + : "(no dep spec)", + copyVersion: p.copyVersion, + verdict: laneVerdict({ + installed: true, + targetMissing: missing, + frozen: p.pinned, + copyVersion: p.copyVersion, + registryVersion, + }), + }; + if (row.verdict === "frozen") + row.reason = + "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)"; + else if (row.verdict === "broken") + row.reason = + "profile depends on billion-context but the bundle copy is missing — rerun 'bili plugin install dsh'"; + const shadow = dshBundleShadowWarning({ + packageName: ctx.packageName, + globalInstallDir: ctx.global.installDir, + globalDiskVersion: ctx.global.diskVersion, + profileName: p.name, + bundleInstalled: p.bundleInstalled, + profileCopyVersion: p.copyVersion, + }); + if (shadow !== undefined) + row.warnings = [...(row.warnings ?? []), shadow]; + return row; + }); + } + const targetsExist = + presence.targets.length > 0 + ? presence.targets.every((t) => fs.existsSync(t)) + : undefined; + const missingTargets = presence.targets.filter((t) => !fs.existsSync(t)); + let detail = + presence.pointers.length > 0 + ? presence.pointers.join("; ") + : presence.installed + ? "installed" + : "not installed"; + if ( + agent === "pi" && + presence.form === "npm" && + presence.targets.length === 0 + ) + detail += "; pi materializes the npm copy on next startup"; + const row: DoctorLane = { + ...base, + agent, + installed: presence.installed, + detail, + targetExists: targetsExist, + copyVersion: presence.copyVersion, + verdict: laneVerdict({ + installed: presence.installed, + targetMissing: missingTargets.length > 0, + frozen: false, + copyVersion: presence.copyVersion, + registryVersion, + }), + }; + if (row.verdict === "broken") + row.reason = missingTargets.map((t) => `target missing: ${t}`).join("; "); + if (agent === "opencode" && presence.installed && presence.form === "npm") { + // #1234/#2199: the cache copy is bili-owned in place (self-updates via its + // own proxy) — show the actual load path + disk version when resolvable so + // the stale verdict below is honest, not "version not resolvable". + const cp = + presence.copyVersion !== undefined ? ` v${presence.copyVersion}` : ""; + const p = + presence.targets[0] !== undefined ? ` (${presence.targets[0]})` : ""; + row.detail += `; cache copy${p}${cp} is bili-owned and self-updates in place via its own proxy (#1234) — reload/restart OpenCode to activate a disk update`; + } + if (agent === "claude" && presence.installed) { + // #2290: the lane itself is healthy, but a co-installed Claude Desktop + // overrides the managed ANTHROPIC_BASE_URL — desktop sessions then get + // neither bili compression nor native auto-compact. Advisory only: never + // change the verdict. Two sources: standing disk evidence + the last + // hook-detected bypass (its stderr is invisible outside debug mode). + const warnings: string[] = []; + if (claudeDesktopPresent()) { + warnings.push( + "Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL, so desktop sessions bypass bili entirely AND lose native auto-compact (managed block sets DISABLE_AUTO_COMPACT=1) — #2290", + ); + } + try { + const rec = JSON.parse( + fs.readFileSync(claudeRoutingWarningFile(), "utf8"), + ) as { at?: unknown; reasons?: unknown }; + if ( + Array.isArray(rec.reasons) && + rec.reasons.length > 0 && + rec.reasons.every((r) => typeof r === "string") + ) { + const at = + typeof rec.at === "number" + ? ` at ${new Date(rec.at).toISOString()}` + : ""; + warnings.push( + `last SessionStart hook detected a routing bypass${at}: ${(rec.reasons as string[]).join("; ")}`, + ); + } + } catch { + // no marker or unreadable — nothing to surface + } + if (warnings.length > 0) row.warnings = warnings; + } + return [row]; } function fmtTime(ts: number): string { - return new Date(ts).toISOString(); + return new Date(ts).toISOString(); } -function verdictText(v: LaneVerdict, row: { oldVersion?: string; registryVersion?: string }): string { - if (v === "stale" && row.oldVersion !== undefined && row.registryVersion !== undefined) return `stale (v${row.oldVersion} → v${row.registryVersion})`; - return v; +function verdictText( + v: LaneVerdict, + row: { oldVersion?: string; registryVersion?: string }, +): string { + if ( + v === "stale" && + row.oldVersion !== undefined && + row.registryVersion !== undefined + ) + return `stale (v${row.oldVersion} → v${row.registryVersion})`; + return v; } export function renderDoctorReport(report: DoctorReport): string { - const lines: string[] = []; - const g = report.global; - lines.push(`bili doctor — ${report.packageName} (running v${g.runningVersion})`); - lines.push(`generated ${fmtTime(report.generatedAt)}`); - lines.push(""); - lines.push("global"); - lines.push(` form ${g.form}${g.owner !== undefined ? ` (owned by ${g.owner})` : ""}${g.installDir !== undefined ? ` — ${g.installDir}` : " — install dir not found"}`); - lines.push(` versions disk ${g.diskVersion ?? "?"} registry[${g.updateTag}] ${g.registryVersion ?? "unreachable"}`); - lines.push(` last check ${g.lastCheckTime !== undefined ? fmtTime(g.lastCheckTime) : "never"}`); - lines.push(` verdict ${verdictText(g.verdict, { oldVersion: g.diskVersion, registryVersion: g.registryVersion })}${g.reason !== undefined ? ` — ${g.reason}` : ""}`); - if (g.advisory?.active !== undefined) lines.push(` advisory ⚠️ ${describeAdvisory(g.advisory.active, g.advisory.error)}`); - else if (g.advisory?.error !== undefined) lines.push(` advisory check failed (${g.advisory.error}) — status unknown`); - else lines.push(` advisory none`); - lines.push(""); - lines.push("lanes"); - for (const lane of report.lanes) { - const head = ` ${lane.agent.padEnd(12)} ${verdictText(lane.verdict, { oldVersion: lane.copyVersion, registryVersion: lane.registryVersion }).padEnd(34)} ${lane.kind}`; - lines.push(head); - lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.detail}`); - if (lane.channel !== undefined && lane.installed) lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} updates via: ${lane.channel}`); - if (lane.reason !== undefined) lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.reason}`); - for (const w of lane.warnings ?? []) lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ⚠️ ${w}`); - } - lines.push(""); - lines.push("processes"); - if (report.processes.length === 0) { - lines.push(" none registered"); - } else { - for (const p of report.processes) { - const state = p.alive ? (p.staleCopy ? "STALE COPY" : "running") : "zombie (process gone, marker left behind)"; - lines.push(` pid ${String(p.pid).padEnd(7)} port ${String(p.port).padEnd(6)} ${p.origin} ${state}`); - if (p.runningFrom !== undefined) lines.push(` ${"".padEnd(12)} runs from ${p.runningFrom}${p.staleCopy ? " (not the current install dir)" : ""}`); - } - } - const counts: Record = { ok: 0, stale: 0, frozen: 0, broken: 0, absent: 0 }; - for (const l of report.lanes) counts[l.verdict]++; - const zombies = report.processes.filter((p) => !p.alive).length; - lines.push(""); - lines.push(`summary: ${counts.ok} ok, ${counts.stale} stale, ${counts.frozen} frozen, ${counts.broken} broken, ${counts.absent} absent; processes: ${report.processes.length - zombies} live, ${zombies} zombie`); - return lines.join("\n") + "\n"; + const lines: string[] = []; + const g = report.global; + lines.push( + `bili doctor — ${report.packageName} (running v${g.runningVersion})`, + ); + lines.push(`generated ${fmtTime(report.generatedAt)}`); + lines.push(""); + lines.push("global"); + lines.push( + ` form ${g.form}${g.owner !== undefined ? ` (owned by ${g.owner})` : ""}${g.installDir !== undefined ? ` — ${g.installDir}` : " — install dir not found"}`, + ); + lines.push( + ` versions disk ${g.diskVersion ?? "?"} registry[${g.updateTag}] ${g.registryVersion ?? "unreachable"}`, + ); + lines.push( + ` last check ${g.lastCheckTime !== undefined ? fmtTime(g.lastCheckTime) : "never"}`, + ); + lines.push( + ` verdict ${verdictText(g.verdict, { oldVersion: g.diskVersion, registryVersion: g.registryVersion })}${g.reason !== undefined ? ` — ${g.reason}` : ""}`, + ); + if (g.advisory?.active !== undefined) + lines.push( + ` advisory ⚠️ ${describeAdvisory(g.advisory.active, g.advisory.error)}`, + ); + else if (g.advisory?.error !== undefined) + lines.push( + ` advisory check failed (${g.advisory.error}) — status unknown`, + ); + else lines.push(` advisory none`); + lines.push(""); + lines.push("lanes"); + for (const lane of report.lanes) { + const head = ` ${lane.agent.padEnd(12)} ${verdictText(lane.verdict, { oldVersion: lane.copyVersion, registryVersion: lane.registryVersion }).padEnd(34)} ${lane.kind}`; + lines.push(head); + lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.detail}`); + if (lane.channel !== undefined && lane.installed) + lines.push( + ` ${"".padEnd(12)} ${"".padEnd(34)} updates via: ${lane.channel}`, + ); + if (lane.reason !== undefined) + lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.reason}`); + for (const w of lane.warnings ?? []) + lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ⚠️ ${w}`); + } + lines.push(""); + lines.push("codex model route"); + lines.push(` state ${report.codexIntegration.state}`); + lines.push(` route ${report.codexIntegration.route}`); + lines.push( + ` proxy ${report.codexIntegration.proxyHealthy ? "healthy" : "not verified"}`, + ); + lines.push( + ` evidence ${report.codexIntegration.observedCodexRequest ? "Codex request observed" : "no Codex model request observed"}`, + ); + lines.push(` detail ${report.codexIntegration.detail}`); + lines.push(""); + lines.push("CC Switch"); + lines.push(` detected ${report.ccSwitch.discovered ? "yes" : "no"}`); + lines.push(` mode ${report.ccSwitch.mode}`); + lines.push(` compatibility ${report.ccSwitch.compatibility}`); + lines.push(` detail ${report.ccSwitch.detail}`); + lines.push(""); + lines.push("ChatGPT subscription / Desktop"); + lines.push(` state ${report.chatGptDesktop.state}`); + lines.push(` credentials ${report.chatGptDesktop.credentials}`); + lines.push(` official login ${report.chatGptDesktop.officialLoginChannels}`); + lines.push(` Desktop MCP ${report.chatGptDesktop.desktopMcp}`); + lines.push(""); + lines.push("processes"); + if (report.processes.length === 0) { + lines.push(" none registered"); + } else { + for (const p of report.processes) { + const state = p.alive + ? p.staleCopy + ? "STALE COPY" + : "running" + : "zombie (process gone, marker left behind)"; + lines.push( + ` pid ${String(p.pid).padEnd(7)} port ${String(p.port).padEnd(6)} ${p.origin} ${state}`, + ); + if (p.runningFrom !== undefined) + lines.push( + ` ${"".padEnd(12)} runs from ${p.runningFrom}${p.staleCopy ? " (not the current install dir)" : ""}`, + ); + } + } + const counts: Record = { + ok: 0, + stale: 0, + frozen: 0, + broken: 0, + absent: 0, + }; + for (const l of report.lanes) counts[l.verdict]++; + const zombies = report.processes.filter((p) => !p.alive).length; + lines.push(""); + lines.push( + `summary: ${counts.ok} ok, ${counts.stale} stale, ${counts.frozen} frozen, ${counts.broken} broken, ${counts.absent} absent; processes: ${report.processes.length - zombies} live, ${zombies} zombie`, + ); + return lines.join("\n") + "\n"; } diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 675a204c38..490f5ad204 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -6,7 +6,6 @@ // pi ~/.pi/agent/settings.json packages: [] // omp ~/.omp/agent/config.yml extensions: [/dist/agent/omp-native.js] // claude `claude mcp add` (user scope; writes ~/.claude.json) -// codex ~/.codex/config.toml [mcp_servers.bili] // opencode /opencode.json{c}|config.json (highest-precedence existing; #927) // mcp.bili + native plugin dir + compaction.auto=false // (plugin entry #925: bare "billion-context" for npm installs — opencode @@ -15,6 +14,14 @@ // dsh no file of its own — drives dsh's own plugin channel per profile // (`dsh plugin --profile add|remove`, #966); profile copies // follow global self-updates via dsh-channel.refreshDshProfileBundles +// codex ~/.codex/config.toml [mcp_servers.bili] (stdio MCP) + the +// bili-owned model route (top-level `openai_base_url`, or the active +// provider's `base_url` under CC Switch Direct; sidecar-recorded +// ownership), + a [hooks.SessionStart] entry running +// dist/codex/bootstrap-hook.js (#ticket 08), + the ACP skill written +// to ~/.codex/skills/bili/SKILL.md. MCP, route, hook and skill are +// reported SEPARATELY: MCP proves tools, never that model traffic is +// compressed. // kimi $KIMI_CODE_HOME/plugins/managed/billion-context/kimi.plugin.json // + installed.json record (stdio MCP + SessionStart hook; config.toml // routing happens per-session, see src/kimi/) @@ -34,17 +41,69 @@ import path from "node:path"; import os from "node:os"; import crypto from "node:crypto"; import { execFileSync, spawnSync } from "node:child_process"; -import { fileURLToPath, pathToFileURL } from "node:url"; -import { applyEdits, modify as jsoncModify, parse as jsoncParse, type ParseError } from "jsonc-parser"; -import { resolveDshHome, resolveHermesHome, resolveKimiHome, resolvePiHome } from "./client-config.js"; +import { fileURLToPath } from "node:url"; +import { + applyEdits, + modify as jsoncModify, + parse as jsoncParse, + type ParseError, +} from "jsonc-parser"; +import { + parseCodexToml, + resolveDshHome, + resolveHermesHome, + resolveKimiHome, + resolvePiHome, +} from "./client-config.js"; import { resolveClaudeNativePort } from "./config.js"; import { lanePreferredPort, readProxyInstanceFile } from "./instance.js"; -import { DSH_PACKAGE, dshBundleInstalled, dshHasLegacyManagedBlock, dshProfileDependsOnBili, dshProfileDepSpec, dshProfileDirs, isRegistryDepSpec, planDshSpawn, refreshDshProfileBundles, runDshPlugin, stripLegacyManagedBlock } from "./dsh-channel.js"; +import { + DSH_PACKAGE, + dshBundleInstalled, + dshHasLegacyManagedBlock, + dshProfileDependsOnBili, + dshProfileDepSpec, + dshProfileDirs, + isRegistryDepSpec, + planDshSpawn, + refreshDshProfileBundles, + runDshPlugin, + stripLegacyManagedBlock, +} from "./dsh-channel.js"; import { piNpmCopyRoot } from "./pi-channel.js"; import { clearOwnerLaneBackoff, fetchRegistryVersion } from "./update.js"; +import { detectCcSwitch } from "./codex-integration/cc-switch.js"; +import { + assertCodexConfigLoads, + codexHooksEnabledNote, + findBiliCodexHook, + planCodexHook, + stripCodexHook, +} from "./codex-integration/hooks.js"; +import { + codexSkillFile, + codexSkillStatus, + installCodexSkill, + removeCodexSkill, +} from "./codex-integration/skill.js"; +import { + codexRouteOrigin, + desiredCodexRoute, + planCodexRoute, + readCodexRoute, + readCodexRouteRecord, + removeCodexRouteRecord, + restoreCodexRoute, + codexRouteRecordPath, + writeCodexRouteRecord, +} from "./codex-integration/route.js"; import { restoreKimiBackup, unrouteKimi } from "./kimi/native.js"; import { inspectZcodeRouting, resolveZcodeDataDir } from "./zcode/json-edit.js"; import { restoreZcodeBackup, unrouteZcode } from "./zcode/native.js"; +import { + installProxyService, + removeProxyService, +} from "./proxy-service/service.js"; /** Build a SessionStart hook command line that parses in every shell the * supported agents run hooks through. Two Windows traps, both measured on @@ -77,26 +136,40 @@ import { restoreZcodeBackup, unrouteZcode } from "./zcode/native.js"; * the hook later inherits). The `&` fallback below stays for hypothetical * spaced-head callers, but no shipped hook uses it. Exported for tests. */ export function portableHookCommand(exe: string, args: string[] = []): string { - const fwd = (p: string): string => p.replaceAll("\\", "/"); - const quoteArg = (p: string): string => (/\s/.test(p) ? `"${p}"` : p); - const head = fwd(exe); - const tail = args.map((a) => quoteArg(fwd(a))); - return /\s/.test(head) ? [`& "${head}"`, ...tail].join(" ") : [head, ...tail].join(" "); -} - -export const PLUGIN_AGENTS = ["pi", "omp", "claude", "codex", "opencode", "dsh", "kimi", "hermes", "zcode"] as const; + const fwd = (p: string): string => p.replaceAll("\\", "/"); + const quoteArg = (p: string): string => (/\s/.test(p) ? `"${p}"` : p); + const head = fwd(exe); + const tail = args.map((a) => quoteArg(fwd(a))); + return /\s/.test(head) + ? [`& "${head}"`, ...tail].join(" ") + : [head, ...tail].join(" "); +} + +export const PLUGIN_AGENTS = [ + "pi", + "omp", + "claude", + "codex", + "opencode", + "dsh", + "kimi", + "hermes", + "zcode", +] as const; export type PluginAgent = (typeof PLUGIN_AGENTS)[number]; export function selfPackageRoot(): string { - // dist/plugin-install.js -> package root two levels up. - const here = fileURLToPath(import.meta.url); - return path.resolve(path.dirname(here), ".."); + // dist/plugin-install.js -> package root two levels up. + const here = fileURLToPath(import.meta.url); + return path.resolve(path.dirname(here), ".."); } function homeFile(rel: string, envOverride?: string): string { - const raw = (envOverride !== undefined ? process.env[envOverride] : undefined)?.trim(); - const base = raw && raw.length > 0 ? raw : os.homedir(); - return path.join(base, rel); + const raw = ( + envOverride !== undefined ? process.env[envOverride] : undefined + )?.trim(); + const base = raw && raw.length > 0 ? raw : os.homedir(); + return path.join(base, rel); } // #1002: backup = the state before bili's LATEST write, but only when the @@ -108,72 +181,78 @@ function homeFile(rel: string, envOverride?: string): string { // `.bili-last` carries the hash of what bili last wrote; "unchanged" // means the on-disk bytes still hash to that value. function hashText(text: string): string { - return crypto.createHash("sha256").update(text).digest("hex"); + return crypto.createHash("sha256").update(text).digest("hex"); } function backupBeforeWrite(file: string): void { - if (!fs.existsSync(file)) return; - const bak = `${file}.bili-bak`; - let cur: string; - try { - cur = hashText(fs.readFileSync(file, "utf8")); - } catch { - return; - } - let prev: string | undefined; - try { - prev = fs.readFileSync(`${file}.bili-last`, "utf8").trim(); - } catch {} - if (prev === cur && fs.existsSync(bak)) return; - fs.copyFileSync(file, bak); + if (!fs.existsSync(file)) return; + const bak = `${file}.bili-bak`; + let cur: string; + try { + cur = hashText(fs.readFileSync(file, "utf8")); + } catch { + return; + } + let prev: string | undefined; + try { + prev = fs.readFileSync(`${file}.bili-last`, "utf8").trim(); + } catch {} + if (prev === cur && fs.existsSync(bak)) return; + fs.copyFileSync(file, bak); } // One writer discipline for every config write bili performs: snapshot per // backupBeforeWrite above, write, then record what we wrote so the NEXT // write can tell bili's own output apart from a user edit. function writeConfigText(file: string, text: string): void { - fs.mkdirSync(path.dirname(file), { recursive: true }); - backupBeforeWrite(file); - fs.writeFileSync(file, text); - try { - fs.writeFileSync(`${file}.bili-last`, `${hashText(text)}\n`); - } catch {} + fs.mkdirSync(path.dirname(file), { recursive: true }); + backupBeforeWrite(file); + fs.writeFileSync(file, text); + try { + fs.writeFileSync(`${file}.bili-last`, `${hashText(text)}\n`); + } catch {} } function readJson(file: string): Record { - let text: string; - try { - text = fs.readFileSync(file, "utf8"); - } catch (err) { - if ((err as { code?: string }).code === "ENOENT") return {}; - throw err; - } - let parsed: unknown; - try { - parsed = JSON.parse(text); - } catch (err) { - throw new Error(`${file}: not valid JSON (${err instanceof Error ? err.message : String(err)}) — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`); - } - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { - throw new Error(`${file}: expected a JSON object at top level, refusing to overwrite`); - } - return parsed as Record; + let text: string; + try { + text = fs.readFileSync(file, "utf8"); + } catch (err) { + if ((err as { code?: string }).code === "ENOENT") return {}; + throw err; + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (err) { + throw new Error( + `${file}: not valid JSON (${err instanceof Error ? err.message : String(err)}) — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`, + ); + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error( + `${file}: expected a JSON object at top level, refusing to overwrite`, + ); + } + return parsed as Record; } function writeJson(file: string, data: unknown): void { - writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); + writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); } function requireDistFile(file: string): void { - if (!fs.existsSync(file)) { - process.stderr.write(`bili plugin: warning: ${file} does not exist yet (run \`npm run build\` in ${selfPackageRoot()}) — the entry will be dead until built\n`); - } + if (!fs.existsSync(file)) { + process.stderr.write( + `bili plugin: warning: ${file} does not exist yet (run \`npm run build\` in ${selfPackageRoot()}) — the entry will be dead until built\n`, + ); + } } // — pi ———————————————————————————————————————————————————————————————— function piSettingsFile(): string { - return path.join(resolvePiHome(process.env), "settings.json"); + return path.join(resolvePiHome(process.env), "settings.json"); } // A packages entry is "ours" if it points at THIS install's package root, @@ -183,10 +262,12 @@ function piSettingsFile(): string { // plugin moved into billion-context itself). install() replaces every match // so exactly one bili plugin is live after `bili plugin install pi`. export function isPiEntry(entry: string, root: string): boolean { - return entry === root - || /^npm:billion-context(-pi)?(@|$)/.test(entry) - || /(^|[/\\])node_modules[/\\]billion-context(-pi)?([\/\\]|$)/.test(entry) - || /(^|[/\\])billion-context(-pi)?$/.test(entry); + return ( + entry === root || + /^npm:billion-context(-pi)?(@|$)/.test(entry) || + /(^|[/\\])node_modules[/\\]billion-context(-pi)?([/\\]|$)/.test(entry) || + /(^|[/\\])billion-context(-pi)?$/.test(entry) + ); } // Entries that load THIS package's pi plugin (billion-context proper). @@ -195,10 +276,12 @@ export function isPiEntry(entry: string, root: string): boolean { // BILLION_CONTEXT_PROXY — so treating it as "installed" wrongly suppressed // the launcher's `-e` fallback and left pi with no plugin at all. export function isBiliPiEntry(entry: string, root: string): boolean { - return entry === root - || /^npm:billion-context(@|$)/.test(entry) - || /(^|[/\\])node_modules[/\\]billion-context([\/\\]|$)/.test(entry) - || /(^|[/\\])billion-context$/.test(entry); + return ( + entry === root || + /^npm:billion-context(@|$)/.test(entry) || + /(^|[/\\])node_modules[/\\]billion-context([/\\]|$)/.test(entry) || + /(^|[/\\])billion-context$/.test(entry) + ); } // #925 pi form of the npm-standard entry: for npm installs (package root @@ -210,54 +293,67 @@ export function isBiliPiEntry(entry: string, root: string): boolean { export const PI_NPM_ENTRY = "npm:billion-context"; export function piEntryFor(root: string): string { - return isNpmInstallForm(root) ? PI_NPM_ENTRY : root; + return isNpmInstallForm(root) ? PI_NPM_ENTRY : root; } function piInstall(): string { - const root = selfPackageRoot(); - const file = piSettingsFile(); - const settings = readJson(file); - const packages = Array.isArray(settings.packages) ? (settings.packages as unknown[]).map(String) : []; - const entry = piEntryFor(root); - if (packages.some((p) => p === entry)) return `pi: already installed (${file})`; - const removed = packages.filter((p) => isPiEntry(p, root)); - const kept = packages.filter((p) => !isPiEntry(p, root)); - kept.push(entry); - settings.packages = kept; - writeJson(file, settings); - // #788: dropped entries must be visible — silently replacing a documented - // setup (npm:billion-context-pi) left users with no compression and no - // idea their config changed. Project-scope reminder mirrors the opencode - // installer's LOCAL-scope note: a `pi install -l` entry lives in - // /.pi/settings.json, which this global strip never touches. - const note = removed.length > 0 - ? `\npi: replaced existing entries: ${removed.join(", ")}` - + "\npi: also check /.pi/settings.json — a project-scope billion-context-pi entry (pi install -l) lives there, not in this global settings" - : ""; - const form = entry === PI_NPM_ENTRY ? " (pi-managed — pi installs it; the proxy self-refreshes it via `pi update --extension npm:billion-context`, or run that manually)" : ""; - return `pi: installed -> ${file} packages += ${entry}${form}${note}`; + const root = selfPackageRoot(); + const file = piSettingsFile(); + const settings = readJson(file); + const packages = Array.isArray(settings.packages) + ? (settings.packages as unknown[]).map(String) + : []; + const entry = piEntryFor(root); + if (packages.some((p) => p === entry)) + return `pi: already installed (${file})`; + const removed = packages.filter((p) => isPiEntry(p, root)); + const kept = packages.filter((p) => !isPiEntry(p, root)); + kept.push(entry); + settings.packages = kept; + writeJson(file, settings); + // #788: dropped entries must be visible — silently replacing a documented + // setup (npm:billion-context-pi) left users with no compression and no + // idea their config changed. Project-scope reminder mirrors the opencode + // installer's LOCAL-scope note: a `pi install -l` entry lives in + // /.pi/settings.json, which this global strip never touches. + const note = + removed.length > 0 + ? `\npi: replaced existing entries: ${removed.join(", ")}` + + "\npi: also check /.pi/settings.json — a project-scope billion-context-pi entry (pi install -l) lives there, not in this global settings" + : ""; + const form = + entry === PI_NPM_ENTRY + ? " (pi-managed — pi installs it; the proxy self-refreshes it via `pi update --extension npm:billion-context`, or run that manually)" + : ""; + return `pi: installed -> ${file} packages += ${entry}${form}${note}`; } function piRemove(): string { - const root = selfPackageRoot(); - const file = piSettingsFile(); - const settings = readJson(file); - const packages = Array.isArray(settings.packages) ? (settings.packages as unknown[]).map(String) : []; - const removed = packages.filter((p) => isPiEntry(p, root)); - if (removed.length === 0) return `pi: not installed (${file})`; - settings.packages = packages.filter((p) => !isPiEntry(p, root)); - writeJson(file, settings); - // #788: same visibility rule as install — removed entries are reported. - return `pi: removed from ${file}\npi: removed entries: ${removed.join(", ")}`; + const root = selfPackageRoot(); + const file = piSettingsFile(); + const settings = readJson(file); + const packages = Array.isArray(settings.packages) + ? (settings.packages as unknown[]).map(String) + : []; + const removed = packages.filter((p) => isPiEntry(p, root)); + if (removed.length === 0) return `pi: not installed (${file})`; + settings.packages = packages.filter((p) => !isPiEntry(p, root)); + writeJson(file, settings); + // #788: same visibility rule as install — removed entries are reported. + return `pi: removed from ${file}\npi: removed entries: ${removed.join(", ")}`; } function piStatus(): string { - const root = selfPackageRoot(); - const packages = readJson(piSettingsFile()).packages; - const list = Array.isArray(packages) ? (packages as unknown[]).map(String) : []; - // Any entry that loads THIS package's plugin counts (npm: form or abs - // root); the legacy billion-context-pi package deliberately does not. - return list.some((p) => isBiliPiEntry(p, root) || p === piEntryFor(root)) ? "installed" : "not installed"; + const root = selfPackageRoot(); + const packages = readJson(piSettingsFile()).packages; + const list = Array.isArray(packages) + ? (packages as unknown[]).map(String) + : []; + // Any entry that loads THIS package's plugin counts (npm: form or abs + // root); the legacy billion-context-pi package deliberately does not. + return list.some((p) => isBiliPiEntry(p, root) || p === piEntryFor(root)) + ? "installed" + : "not installed"; } // — omp ——————————————————————————————————————————————————————————————— @@ -276,23 +372,23 @@ const OMP_ENTRY_RE = /[\\/]dist[\\/]agent[\\/]omp(-native)?\.js$/; // to guess). Matching is scoped to this block, so a same-valued line under // any other key is never counted as installed and never removed. function ompExtensionItemLines(text: string): number[] { - const lines = text.split("\n"); - let keyIdx = -1; - for (let i = 0; i < lines.length; i++) { - if (/^extensions:(\s+(#.*)?)?$/.test(lines[i]!)) { - if (keyIdx !== -1) return []; - keyIdx = i; - } - } - if (keyIdx === -1) return []; - const items: number[] = []; - for (let i = keyIdx + 1; i < lines.length; i++) { - const t = lines[i]!.trimStart(); - if (t === "" || t.startsWith("#")) continue; - if (t === "-" || t.startsWith("- ")) items.push(i); - else break; - } - return items; + const lines = text.split("\n"); + let keyIdx = -1; + for (let i = 0; i < lines.length; i++) { + if (/^extensions:(\s+(#.*)?)?$/.test(lines[i]!)) { + if (keyIdx !== -1) return []; + keyIdx = i; + } + } + if (keyIdx === -1) return []; + const items: number[] = []; + for (let i = keyIdx + 1; i < lines.length; i++) { + const t = lines[i]!.trimStart(); + if (t === "" || t.startsWith("#")) continue; + if (t === "-" || t.startsWith("- ")) items.push(i); + else break; + } + return items; } // The config.yml the plugin commands read/write. When PI_CODING_AGENT_DIR @@ -302,125 +398,144 @@ function ompExtensionItemLines(text: string): number[] { // would silently miss the real config. A note is printed so the user sees // which file was actually touched. function ompConfigFile(): string { - const raw = process.env.PI_CODING_AGENT_DIR?.trim(); - if (raw && raw.length > 0) { - if (raw.endsWith("-bili") && raw.length > "-bili".length) { - const realHome = raw.slice(0, -"-bili".length); - process.stderr.write( - `bili plugin: PI_CODING_AGENT_DIR points at the bili overlay ${raw} — operating on the real omp home ${realHome} instead\n`, - ); - return path.join(realHome, "config.yml"); - } - return path.join(raw, "config.yml"); - } - return path.join(os.homedir(), ".omp", "agent", "config.yml"); + const raw = process.env.PI_CODING_AGENT_DIR?.trim(); + if (raw && raw.length > 0) { + if (raw.endsWith("-bili") && raw.length > "-bili".length) { + const realHome = raw.slice(0, -"-bili".length); + process.stderr.write( + `bili plugin: PI_CODING_AGENT_DIR points at the bili overlay ${raw} — operating on the real omp home ${realHome} instead\n`, + ); + return path.join(realHome, "config.yml"); + } + return path.join(raw, "config.yml"); + } + return path.join(os.homedir(), ".omp", "agent", "config.yml"); } function ompExtensionPath(): string { - return path.join(selfPackageRoot(), "dist", "agent", "omp-native.js"); + return path.join(selfPackageRoot(), "dist", "agent", "omp-native.js"); } function ompEntryValue(line: string): string { - return line.replace(/#.*$/, "").trim().replace(/^-\s*/, "").replace(/^["']|["']$/g, "").trim(); + return line + .replace(/#.*$/, "") + .trim() + .replace(/^-\s*/, "") + .replace(/^["']|["']$/g, "") + .trim(); } // A bili omp entry that actually loads: matches our entry shape AND the target // file exists on disk (stale entries from a moved install don't count). function ompEntryLoadable(value: string): boolean { - return OMP_ENTRY_RE.test(value) && fs.existsSync(value); + return OMP_ENTRY_RE.test(value) && fs.existsSync(value); } function ompRemove(): string { - const file = ompConfigFile(); - if (!fs.existsSync(file)) return `omp: not installed (${file})`; - const text = fs.readFileSync(file, "utf8"); - const lines = text.split("\n"); - const drop = new Set( - ompExtensionItemLines(text).filter((i) => OMP_ENTRY_RE.test(ompEntryValue(lines[i]!))), - ); - if (drop.size === 0) return `omp: not installed (${file})`; - const cleaned = lines.filter((_, i) => !drop.has(i)).join("\n"); - writeConfigText(file, cleaned); - return `omp: removed from ${file}`; + const file = ompConfigFile(); + if (!fs.existsSync(file)) return `omp: not installed (${file})`; + const text = fs.readFileSync(file, "utf8"); + const lines = text.split("\n"); + const drop = new Set( + ompExtensionItemLines(text).filter((i) => + OMP_ENTRY_RE.test(ompEntryValue(lines[i]!)), + ), + ); + if (drop.size === 0) return `omp: not installed (${file})`; + const cleaned = lines.filter((_, i) => !drop.has(i)).join("\n"); + writeConfigText(file, cleaned); + return `omp: removed from ${file}`; } function ompInstall(): string { - const file = ompConfigFile(); - const entry = ompExtensionPath(); - requireDistFile(entry); - fs.mkdirSync(path.dirname(file), { recursive: true }); - let text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; - // Exactly one bili owner after install (#957): a lone native entry → done. - // Any other bili entry — pre-#957 thin dist/agent/omp.js installs or stale - // duplicates — is dropped and replaced by the insert below, so an old - // install upgrades to native mode on re-install. - let replaced: string[] = []; - { - const lines = text.split("\n"); - const ours = new Set(); - for (const i of ompExtensionItemLines(text)) { - const v = ompEntryValue(lines[i]!); - if (!OMP_ENTRY_RE.test(v)) continue; - ours.add(i); - if (v !== entry) replaced.push(v); - } - if (ours.size === 1 && [...ours].every((i) => ompEntryValue(lines[i]!) === entry)) { - return `omp: already installed (${file})`; - } - if (ours.size > 0) text = lines.filter((_, i) => !ours.has(i)).join("\n"); - } - const keyCount = (text.match(/^extensions:/gm) ?? []).length; - if (keyCount > 1) throw new Error(`${file}: multiple \`extensions:\` keys — fix the file first, refusing to edit`); - if (/^extensions:\s*\S/m.test(text) && !/^extensions:\s*$/m.test(text)) { - throw new Error(`${file}: \`extensions:\` uses flow style or an inline value; convert it to a block list first, refusing to edit`); - } - let out: string; - const extMatch = /^extensions:\s*$/m.exec(text); - if (extMatch !== null) { - const afterKey = text.indexOf("\n", extMatch.index); - const rest = afterKey < 0 ? "" : text.slice(afterKey + 1); - const firstNonList = rest.search(/^(?!\s*-\s)\S/m); - const existingIndent = /^(\s*)-\s\S/m.exec(rest)?.[1] ?? " "; - let head: string; - let tail: string; - if (firstNonList >= 0) { - head = text.slice(0, afterKey + 1 + firstNonList); - tail = text.slice(afterKey + 1 + firstNonList); - } else { - head = text.length === 0 || text.endsWith("\n") ? text : text + "\n"; - tail = ""; - } - out = `${head}${existingIndent}- ${entry}\n${tail}`; - } else { - out = text.endsWith("\n") || text.length === 0 ? text : text + "\n"; - out += `extensions:\n - ${entry}\n`; - } - const outLines = out.split("\n"); - const occurrences = ompExtensionItemLines(out).filter((i) => ompEntryValue(outLines[i]!) === entry).length; - if (occurrences !== 1) { - throw new Error(`${file}: edit would leave ${occurrences} copies of the entry — aborting without writing`); - } - backupBeforeWrite(file); - fs.writeFileSync(file, out); - try { - fs.writeFileSync(`${file}.bili-last`, `${hashText(out)}\n`); - } catch {} - const note = replaced.length > 0 ? ` (replaced ${replaced.join(", ")})` : ""; - return `omp: installed -> ${file} extensions += ${entry}${note}`; + const file = ompConfigFile(); + const entry = ompExtensionPath(); + requireDistFile(entry); + fs.mkdirSync(path.dirname(file), { recursive: true }); + let text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + // Exactly one bili owner after install (#957): a lone native entry → done. + // Any other bili entry — pre-#957 thin dist/agent/omp.js installs or stale + // duplicates — is dropped and replaced by the insert below, so an old + // install upgrades to native mode on re-install. + const replaced: string[] = []; + { + const lines = text.split("\n"); + const ours = new Set(); + for (const i of ompExtensionItemLines(text)) { + const v = ompEntryValue(lines[i]!); + if (!OMP_ENTRY_RE.test(v)) continue; + ours.add(i); + if (v !== entry) replaced.push(v); + } + if ( + ours.size === 1 && + [...ours].every((i) => ompEntryValue(lines[i]!) === entry) + ) { + return `omp: already installed (${file})`; + } + if (ours.size > 0) text = lines.filter((_, i) => !ours.has(i)).join("\n"); + } + const keyCount = (text.match(/^extensions:/gm) ?? []).length; + if (keyCount > 1) + throw new Error( + `${file}: multiple \`extensions:\` keys — fix the file first, refusing to edit`, + ); + if (/^extensions:\s*\S/m.test(text) && !/^extensions:\s*$/m.test(text)) { + throw new Error( + `${file}: \`extensions:\` uses flow style or an inline value; convert it to a block list first, refusing to edit`, + ); + } + let out: string; + const extMatch = /^extensions:\s*$/m.exec(text); + if (extMatch !== null) { + const afterKey = text.indexOf("\n", extMatch.index); + const rest = afterKey < 0 ? "" : text.slice(afterKey + 1); + const firstNonList = rest.search(/^(?!\s*-\s)\S/m); + const existingIndent = /^(\s*)-\s\S/m.exec(rest)?.[1] ?? " "; + let head: string; + let tail: string; + if (firstNonList >= 0) { + head = text.slice(0, afterKey + 1 + firstNonList); + tail = text.slice(afterKey + 1 + firstNonList); + } else { + head = text.length === 0 || text.endsWith("\n") ? text : text + "\n"; + tail = ""; + } + out = `${head}${existingIndent}- ${entry}\n${tail}`; + } else { + out = text.endsWith("\n") || text.length === 0 ? text : text + "\n"; + out += `extensions:\n - ${entry}\n`; + } + const outLines = out.split("\n"); + const occurrences = ompExtensionItemLines(out).filter( + (i) => ompEntryValue(outLines[i]!) === entry, + ).length; + if (occurrences !== 1) { + throw new Error( + `${file}: edit would leave ${occurrences} copies of the entry — aborting without writing`, + ); + } + backupBeforeWrite(file); + fs.writeFileSync(file, out); + try { + fs.writeFileSync(`${file}.bili-last`, `${hashText(out)}\n`); + } catch {} + const note = replaced.length > 0 ? ` (replaced ${replaced.join(", ")})` : ""; + return `omp: installed -> ${file} extensions += ${entry}${note}`; } function ompStatus(): string { - const file = ompConfigFile(); - const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; - const lines = text.split("\n"); - let broken = false; - for (const i of ompExtensionItemLines(text)) { - const v = ompEntryValue(lines[i]!); - if (!OMP_ENTRY_RE.test(v)) continue; - if (fs.existsSync(v)) return "installed"; - broken = true; - } - return broken ? "broken" : "not installed"; + const file = ompConfigFile(); + const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + const lines = text.split("\n"); + let broken = false; + for (const i of ompExtensionItemLines(text)) { + const v = ompEntryValue(lines[i]!); + if (!OMP_ENTRY_RE.test(v)) continue; + if (fs.existsSync(v)) return "installed"; + broken = true; + } + return broken ? "broken" : "not installed"; } /** True when the given omp home's config.yml carries a bili plugin entry @@ -431,13 +546,15 @@ function ompStatus(): string { * install paths (file gone) don't count: omp fails to load those, so the * launcher must supply the working plugin itself. */ export function ompPluginLoadedFrom(ompHome: string): boolean { - try { - const text = fs.readFileSync(path.join(ompHome, "config.yml"), "utf8"); - const lines = text.split("\n"); - return ompExtensionItemLines(text).some((i) => ompEntryLoadable(ompEntryValue(lines[i]!))); - } catch { - return false; - } + try { + const text = fs.readFileSync(path.join(ompHome, "config.yml"), "utf8"); + const lines = text.split("\n"); + return ompExtensionItemLines(text).some((i) => + ompEntryLoadable(ompEntryValue(lines[i]!)), + ); + } catch { + return false; + } } // — claude ————————————————————————————————————————————————————————————— @@ -445,17 +562,19 @@ export function ompPluginLoadedFrom(ompHome: string): boolean { const CLAUDE_EXEC_TIMEOUT_MS = 15000; function claudeMcpJson(): string { - return homeFile(".claude.json", "CLAUDE_CONFIG_DIR"); + return homeFile(".claude.json", "CLAUDE_CONFIG_DIR"); } /** ~/.claude/settings.json honoring CLAUDE_CONFIG_DIR (claude replaces the * whole ~/.claude directory when it is set). The #964 managed block lives * here — env.ANTHROPIC_BASE_URL / env.DISABLE_AUTO_COMPACT / * hooks.SessionStart. */ -export function claudeSettingsFile(env: NodeJS.ProcessEnv = process.env): string { - const raw = env.CLAUDE_CONFIG_DIR?.trim(); - const base = raw && raw.length > 0 ? raw : path.join(os.homedir(), ".claude"); - return path.join(base, "settings.json"); +export function claudeSettingsFile( + env: NodeJS.ProcessEnv = process.env, +): string { + const raw = env.CLAUDE_CONFIG_DIR?.trim(); + const base = raw && raw.length > 0 ? raw : path.join(os.homedir(), ".claude"); + return path.join(base, "settings.json"); } // #1146: /acp-cache for claude. Claude Code has no in-process command API — @@ -474,16 +593,22 @@ Arguments: $ARGUMENTS /** /commands/acp-cache.md (claude replaces the * whole directory when CLAUDE_CONFIG_DIR is set — same rule as settings.json). */ -export function claudeAcpCacheCommandFile(env: NodeJS.ProcessEnv = process.env): string { - return path.join(path.dirname(claudeSettingsFile(env)), "commands", "acp-cache.md"); +export function claudeAcpCacheCommandFile( + env: NodeJS.ProcessEnv = process.env, +): string { + return path.join( + path.dirname(claudeSettingsFile(env)), + "commands", + "acp-cache.md", + ); } /** True for an ANTHROPIC_BASE_URL value written by a bili managed block: * loopback /bili/-wrapped upstream. Any port matches — an older install's * port differs from the current one, and both are ours to rewrite. */ export function isBiliClaudeBaseUrl(value: unknown): boolean { - if (typeof value !== "string") return false; - return /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/https?:\/\//.test(value); + if (typeof value !== "string") return false; + return /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/https?:\/\//.test(value); } /** Disk evidence that the Claude Desktop app is installed — the host whose @@ -493,24 +618,35 @@ export function isBiliClaudeBaseUrl(value: unknown): boolean { * install locations only (portable installs exist), so callers treat a hit * as an advisory input and a miss as absence-of-evidence, never an error. * Injectable for tests. */ -export function claudeDesktopPresent(opts: { platform?: string; localAppData?: string; home?: string; appRoots?: string[] } = {}): boolean { - const platform = opts.platform ?? process.platform; - const home = opts.home ?? os.homedir(); - if (platform === "win32") { - const lad = opts.localAppData ?? process.env.LOCALAPPDATA; - if (lad === undefined || lad.length === 0) return false; - return fs.existsSync(path.join(lad, "Programs", "Claude")); - } - if (platform === "darwin") { - const roots = opts.appRoots ?? ["/Applications"]; - return [...roots, path.join(home, "Applications")].some((r) => fs.existsSync(path.join(r, "Claude.app"))); - } - return false; -} - -export function claudeNativeBaseUrl(env: NodeJS.ProcessEnv = process.env): string { - const origin = `http://127.0.0.1:${resolveClaudeNativePort(env) ?? lanePreferredPort("claude", env)}`; - return claudeNativeBaseUrlForOrigin(origin, undefined, env); +export function claudeDesktopPresent( + opts: { + platform?: string; + localAppData?: string; + home?: string; + appRoots?: string[]; + } = {}, +): boolean { + const platform = opts.platform ?? process.platform; + const home = opts.home ?? os.homedir(); + if (platform === "win32") { + const lad = opts.localAppData ?? process.env.LOCALAPPDATA; + if (lad === undefined || lad.length === 0) return false; + return fs.existsSync(path.join(lad, "Programs", "Claude")); + } + if (platform === "darwin") { + const roots = opts.appRoots ?? ["/Applications"]; + return [...roots, path.join(home, "Applications")].some((r) => + fs.existsSync(path.join(r, "Claude.app")), + ); + } + return false; +} + +export function claudeNativeBaseUrl( + env: NodeJS.ProcessEnv = process.env, +): string { + const origin = `http://127.0.0.1:${resolveClaudeNativePort(env) ?? lanePreferredPort("claude", env)}`; + return claudeNativeBaseUrlForOrigin(origin, undefined, env); } /** #1660: the wrapped base URL for an arbitrary live origin — the @@ -519,22 +655,30 @@ export function claudeNativeBaseUrl(env: NodeJS.ProcessEnv = process.env): strin * resolution (BILI_CLAUDE_UPSTREAM > https://api.anthropic.com) — pass the * UNWRAPPED value of the current settings URL to preserve a relay an * earlier install baked in. */ -export function claudeNativeBaseUrlForOrigin(origin: string, upstream: string | undefined, env: NodeJS.ProcessEnv = process.env): string { - const relay = env.BILI_CLAUDE_UPSTREAM?.trim(); - const base = (upstream !== undefined && upstream.length > 0 - ? upstream - : relay && relay.length > 0 - ? relay - : "https://api.anthropic.com").replace(/\/+$/, ""); - const prefix = origin.replace(/\/+$/, "") + "/bili/"; - return base.startsWith(prefix) ? base : prefix + base; +export function claudeNativeBaseUrlForOrigin( + origin: string, + upstream: string | undefined, + env: NodeJS.ProcessEnv = process.env, +): string { + const relay = env.BILI_CLAUDE_UPSTREAM?.trim(); + const base = ( + upstream !== undefined && upstream.length > 0 + ? upstream + : relay && relay.length > 0 + ? relay + : "https://api.anthropic.com" + ).replace(/\/+$/, ""); + const prefix = origin.replace(/\/+$/, "") + "/bili/"; + return base.startsWith(prefix) ? base : prefix + base; } /** The inverse of the wrap: strip a bili wrapper (any loopback port) from a * base URL. Returns undefined for anything not written by us. */ export function unwrapBiliBaseUrl(value: string): string | undefined { - const m = /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/(https?:\/\/.+)$/.exec(value); - return m ? m[1] : undefined; + const m = /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/(https?:\/\/.+)$/.exec( + value, + ); + return m ? m[1] : undefined; } /** #1660: SessionStart drift-repair — repin the managed block's @@ -545,64 +689,105 @@ export function unwrapBiliBaseUrl(value: string): string | undefined { * install). Also upserts the SessionStart hook, keeping a stale command * fresh across upgrades. Returns the change notes for the hook's log; * never throws, and writes only when the file actually changes. */ -export function repinClaudeManagedBaseUrl(origin: string, env: NodeJS.ProcessEnv = process.env): string[] { - const file = claudeSettingsFile(env); - const settings = readJson(file); - const cur = (settings.env as Record | undefined)?.ANTHROPIC_BASE_URL; - const baseUrl = claudeNativeBaseUrlForOrigin(origin, typeof cur === "string" ? unwrapBiliBaseUrl(cur) : undefined, env); - // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. - const hookCommand = portableHookCommand("node", [path.join(selfPackageRoot(), "dist", "claude-native-bootstrap.js")]); - const { data, notes } = applyClaudeManagedBlock(settings, { baseUrl, hookCommand }); - if (JSON.stringify(data) !== JSON.stringify(settings)) writeJson(file, data); - return notes; +export function repinClaudeManagedBaseUrl( + origin: string, + env: NodeJS.ProcessEnv = process.env, +): string[] { + const file = claudeSettingsFile(env); + const settings = readJson(file); + const cur = (settings.env as Record | undefined) + ?.ANTHROPIC_BASE_URL; + const baseUrl = claudeNativeBaseUrlForOrigin( + origin, + typeof cur === "string" ? unwrapBiliBaseUrl(cur) : undefined, + env, + ); + // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. + const hookCommand = portableHookCommand("node", [ + path.join(selfPackageRoot(), "dist", "claude-native-bootstrap.js"), + ]); + const { data, notes } = applyClaudeManagedBlock(settings, { + baseUrl, + hookCommand, + }); + if (JSON.stringify(data) !== JSON.stringify(settings)) writeJson(file, data); + return notes; } /** Pure merge of the #964 managed block into parsed settings (install path). * Never clobbers user keys: a foreign ANTHROPIC_BASE_URL or a non-"1" * DISABLE_AUTO_COMPACT is reported and skipped, not overwritten. Returns the * mutated copy plus human notes. Exported for tests. */ -export function applyClaudeManagedBlock(settings: Record, opts: { baseUrl: string; hookCommand: string }): { data: Record; notes: string[] } { - const data = structuredClone(settings); - const notes: string[] = []; - const env = (data.env !== null && typeof data.env === "object" && !Array.isArray(data.env) ? data.env : {}) as Record; - const cur = env.ANTHROPIC_BASE_URL; - if (cur === undefined || cur === null || isBiliClaudeBaseUrl(cur)) { - if (cur !== opts.baseUrl) { - env.ANTHROPIC_BASE_URL = opts.baseUrl; - notes.push("env.ANTHROPIC_BASE_URL pinned to the bili proxy"); - } - } else { - notes.push(`env.ANTHROPIC_BASE_URL left untouched (foreign value ${JSON.stringify(cur)} — unset it or set BILI_CLAUDE_UPSTREAM, then reinstall)`); - } - const dac = env.DISABLE_AUTO_COMPACT; - if (dac === undefined || dac === null || dac === "1") { - if (dac !== "1") { - env.DISABLE_AUTO_COMPACT = "1"; - notes.push("env.DISABLE_AUTO_COMPACT=1 (bili owns compression; manual /compact survives)"); - } - } else { - notes.push(`env.DISABLE_AUTO_COMPACT left untouched (foreign value ${JSON.stringify(dac)})`); - } - if (Object.keys(env).length > 0) data.env = env; - - const hooks = (data.hooks !== null && typeof data.hooks === "object" && !Array.isArray(data.hooks) ? data.hooks : {}) as Record; - const sessionStart = Array.isArray(hooks.SessionStart) ? hooks.SessionStart : []; - if (!sessionStart.some(isOursSessionStartEntry)) { - sessionStart.push({ hooks: [{ type: "command", command: opts.hookCommand }] }); - hooks.SessionStart = sessionStart; - data.hooks = hooks; - notes.push("hooks.SessionStart += bili proxy bootstrap"); - } else if (refreshOurHookCommands(sessionStart, opts.hookCommand)) { - data.hooks = hooks; - notes.push("hooks.SessionStart refreshed to the current hook command"); - } - return { data, notes }; +export function applyClaudeManagedBlock( + settings: Record, + opts: { baseUrl: string; hookCommand: string }, +): { data: Record; notes: string[] } { + const data = structuredClone(settings); + const notes: string[] = []; + const env = ( + data.env !== null && + typeof data.env === "object" && + !Array.isArray(data.env) + ? data.env + : {} + ) as Record; + const cur = env.ANTHROPIC_BASE_URL; + if (cur === undefined || cur === null || isBiliClaudeBaseUrl(cur)) { + if (cur !== opts.baseUrl) { + env.ANTHROPIC_BASE_URL = opts.baseUrl; + notes.push("env.ANTHROPIC_BASE_URL pinned to the bili proxy"); + } + } else { + notes.push( + `env.ANTHROPIC_BASE_URL left untouched (foreign value ${JSON.stringify(cur)} — unset it or set BILI_CLAUDE_UPSTREAM, then reinstall)`, + ); + } + const dac = env.DISABLE_AUTO_COMPACT; + if (dac === undefined || dac === null || dac === "1") { + if (dac !== "1") { + env.DISABLE_AUTO_COMPACT = "1"; + notes.push( + "env.DISABLE_AUTO_COMPACT=1 (bili owns compression; manual /compact survives)", + ); + } + } else { + notes.push( + `env.DISABLE_AUTO_COMPACT left untouched (foreign value ${JSON.stringify(dac)})`, + ); + } + if (Object.keys(env).length > 0) data.env = env; + + const hooks = ( + data.hooks !== null && + typeof data.hooks === "object" && + !Array.isArray(data.hooks) + ? data.hooks + : {} + ) as Record; + const sessionStart = Array.isArray(hooks.SessionStart) + ? hooks.SessionStart + : []; + if (!sessionStart.some(isOursSessionStartEntry)) { + sessionStart.push({ + hooks: [{ type: "command", command: opts.hookCommand }], + }); + hooks.SessionStart = sessionStart; + data.hooks = hooks; + notes.push("hooks.SessionStart += bili proxy bootstrap"); + } else if (refreshOurHookCommands(sessionStart, opts.hookCommand)) { + data.hooks = hooks; + notes.push("hooks.SessionStart refreshed to the current hook command"); + } + return { data, notes }; } /** A hook command naming our bootstrap script. Match on the script name * rather than the whole string: the emitted form changes across releases. */ function isOurHookCommand(command: unknown): command is string { - return typeof command === "string" && /claude-native-bootstrap\.(?:js|mjs|ts)["']?$/.test(command); + return ( + typeof command === "string" && + /claude-native-bootstrap\.(?:js|mjs|ts)["']?$/.test(command) + ); } /** Rewrite every hook command we own to `command`, in place; true if any @@ -610,72 +795,104 @@ function isOurHookCommand(command: unknown): command is string { * so without this a settings file written by an older release keeps its old * command forever — and a command a client shell cannot run hangs every * session with no log to say why. */ -function refreshOurHookCommands(sessionStart: unknown[], command: string): boolean { - let changed = false; - for (const entry of sessionStart) { - if (!isOursSessionStartEntry(entry)) continue; - for (const h of (entry as { hooks: unknown[] }).hooks) { - const hook = h as { command?: unknown }; - const cur = hook.command; - if (isOurHookCommand(cur) && cur !== command) { - hook.command = command; - changed = true; - } - } - } - return changed; +function refreshOurHookCommands( + sessionStart: unknown[], + command: string, +): boolean { + let changed = false; + for (const entry of sessionStart) { + if (!isOursSessionStartEntry(entry)) continue; + for (const h of (entry as { hooks: unknown[] }).hooks) { + const hook = h as { command?: unknown }; + const cur = hook.command; + if (isOurHookCommand(cur) && cur !== command) { + hook.command = command; + changed = true; + } + } + } + return changed; } /** A SessionStart entry we wrote: any hook command naming our bootstrap * script (path may differ across installs/upgrades). */ export function isOursSessionStartEntry(entry: unknown): boolean { - const hooks = (entry !== null && typeof entry === "object" && !Array.isArray(entry) ? (entry as { hooks?: unknown }).hooks : undefined); - if (!Array.isArray(hooks)) return false; - return hooks.some((h) => h !== null && typeof h === "object" && isOurHookCommand((h as { command?: unknown }).command)); + const hooks = + entry !== null && typeof entry === "object" && !Array.isArray(entry) + ? (entry as { hooks?: unknown }).hooks + : undefined; + if (!Array.isArray(hooks)) return false; + return hooks.some( + (h) => + h !== null && + typeof h === "object" && + isOurHookCommand((h as { command?: unknown }).command), + ); } /** Pure strip of the managed block (remove path) — returns the cleaned copy * and what was removed. DISABLE_AUTO_COMPACT is dropped only when it is the * value we wrote ("1"); a .bili-bak with a pre-install value restores it in * the caller. Exported for tests. */ -export function stripClaudeManagedBlock(settings: Record): { data: Record; removed: string[] } { - const data = structuredClone(settings); - const removed: string[] = []; - const env = (data.env !== null && typeof data.env === "object" && !Array.isArray(data.env) ? data.env : undefined) as Record | undefined; - if (env !== undefined) { - if (isBiliClaudeBaseUrl(env.ANTHROPIC_BASE_URL)) { - delete env.ANTHROPIC_BASE_URL; - removed.push("env.ANTHROPIC_BASE_URL"); - } - if (env.DISABLE_AUTO_COMPACT === "1") { - delete env.DISABLE_AUTO_COMPACT; - removed.push("env.DISABLE_AUTO_COMPACT"); - } - if (Object.keys(env).length === 0) delete data.env; - } - const hooks = (data.hooks !== null && typeof data.hooks === "object" && !Array.isArray(data.hooks) ? data.hooks : undefined) as Record | undefined; - if (hooks !== undefined && Array.isArray(hooks.SessionStart)) { - const kept = (hooks.SessionStart as unknown[]).filter((e) => !isOursSessionStartEntry(e)); - if (kept.length !== (hooks.SessionStart as unknown[]).length) { - removed.push("hooks.SessionStart entry"); - if (kept.length > 0) hooks.SessionStart = kept; - else delete hooks.SessionStart; - if (Object.keys(hooks).length === 0) delete data.hooks; - } - } - return { data, removed }; +export function stripClaudeManagedBlock(settings: Record): { + data: Record; + removed: string[]; +} { + const data = structuredClone(settings); + const removed: string[] = []; + const env = ( + data.env !== null && + typeof data.env === "object" && + !Array.isArray(data.env) + ? data.env + : undefined + ) as Record | undefined; + if (env !== undefined) { + if (isBiliClaudeBaseUrl(env.ANTHROPIC_BASE_URL)) { + delete env.ANTHROPIC_BASE_URL; + removed.push("env.ANTHROPIC_BASE_URL"); + } + if (env.DISABLE_AUTO_COMPACT === "1") { + delete env.DISABLE_AUTO_COMPACT; + removed.push("env.DISABLE_AUTO_COMPACT"); + } + if (Object.keys(env).length === 0) delete data.env; + } + const hooks = ( + data.hooks !== null && + typeof data.hooks === "object" && + !Array.isArray(data.hooks) + ? data.hooks + : undefined + ) as Record | undefined; + if (hooks !== undefined && Array.isArray(hooks.SessionStart)) { + const kept = (hooks.SessionStart as unknown[]).filter( + (e) => !isOursSessionStartEntry(e), + ); + if (kept.length !== (hooks.SessionStart as unknown[]).length) { + removed.push("hooks.SessionStart entry"); + if (kept.length > 0) hooks.SessionStart = kept; + else delete hooks.SessionStart; + if (Object.keys(hooks).length === 0) delete data.hooks; + } + } + return { data, removed }; } /** True when the managed settings block (the static ANTHROPIC_BASE_URL) is * present — the `bili claude` launcher consults this to override the static * URL with its own ephemeral proxy (coexistence, #964 item 5). */ -export function claudeNativeInstalled(env: NodeJS.ProcessEnv = process.env): boolean { - try { - const data = readJson(claudeSettingsFile(env)); - return isBiliClaudeBaseUrl((data.env as Record | undefined)?.ANTHROPIC_BASE_URL); - } catch { - return false; - } +export function claudeNativeInstalled( + env: NodeJS.ProcessEnv = process.env, +): boolean { + try { + const data = readJson(claudeSettingsFile(env)); + return isBiliClaudeBaseUrl( + (data.env as Record | undefined)?.ANTHROPIC_BASE_URL, + ); + } catch { + return false; + } } // Windows: npm global shims are .cmd/.bat — direct spawn is EINVAL, so @@ -683,12 +900,21 @@ export function claudeNativeInstalled(env: NodeJS.ProcessEnv = process.env): boo // detectOpencodeMajor below). % is doubled because cmd.exe still expands // env vars inside quoted tokens. function runClaudeCli(claude: string, args: string[]): void { - if (process.platform === "win32" && /\.(cmd|bat)$/i.test(claude)) { - const q = (s: string) => `"${s.replaceAll("%", "%%")}"`; - execFileSync([claude, ...args].map(q).join(" "), { shell: true, stdio: ["ignore", "pipe", "pipe"], timeout: CLAUDE_EXEC_TIMEOUT_MS, windowsHide: true }); - } else { - execFileSync(claude, args, { stdio: ["ignore", "pipe", "pipe"], timeout: CLAUDE_EXEC_TIMEOUT_MS, windowsHide: true }); - } + if (process.platform === "win32" && /\.(cmd|bat)$/i.test(claude)) { + const q = (s: string) => `"${s.replaceAll("%", "%%")}"`; + execFileSync([claude, ...args].map(q).join(" "), { + shell: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: CLAUDE_EXEC_TIMEOUT_MS, + windowsHide: true, + }); + } else { + execFileSync(claude, args, { + stdio: ["ignore", "pipe", "pipe"], + timeout: CLAUDE_EXEC_TIMEOUT_MS, + windowsHide: true, + }); + } } // CLAUDE overrides the claude binary path (absolute path for sandboxed @@ -708,251 +934,621 @@ function runClaudeCli(claude: string, args: string[]): void { * PATH order first, PATHEXT order within each directory. When nothing * carries a PATHEXT extension the old first-hit behavior stands. */ export function resolveClaudeCli( - claude: string, - where?: (name: string) => { stdout: string | null }, - pathext?: string, + claude: string, + where?: (name: string) => { stdout: string | null }, + pathext?: string, ): string { - if (/[\\/]/.test(claude) || /\.[a-z]+$/i.test(claude)) return claude; - const run = where ?? (process.platform === "win32" ? defaultWhereRunner : undefined); - if (!run) return claude; - try { - const hits = (run(claude).stdout ?? "").split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0); - if (hits.length === 0) return claude; - const exts = (pathext ?? process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") - .split(";") - .map((e) => e.trim().toLowerCase()) - .filter((e) => e.startsWith(".")); - const dirs = new Map(); - for (const hit of hits) { - const base = /[^\\/]+$/.exec(hit)?.[0] ?? hit; - const dir = hit.slice(0, hit.length - base.length); - const list = dirs.get(dir) ?? []; - list.push(hit); - dirs.set(dir, list); - } - for (const perDir of dirs.values()) { - for (const ext of exts) { - const hit = perDir.find((h) => h.toLowerCase().endsWith(ext)); - if (hit) return hit; - } - } - return hits[0]; - } catch { - return claude; - } + if (/[\\/]/.test(claude) || /\.[a-z]+$/i.test(claude)) return claude; + const run = + where ?? (process.platform === "win32" ? defaultWhereRunner : undefined); + if (!run) return claude; + try { + const hits = (run(claude).stdout ?? "") + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => l.length > 0); + if (hits.length === 0) return claude; + const exts = (pathext ?? process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") + .split(";") + .map((e) => e.trim().toLowerCase()) + .filter((e) => e.startsWith(".")); + const dirs = new Map(); + for (const hit of hits) { + const base = /[^\\/]+$/.exec(hit)?.[0] ?? hit; + const dir = hit.slice(0, hit.length - base.length); + const list = dirs.get(dir) ?? []; + list.push(hit); + dirs.set(dir, list); + } + for (const perDir of dirs.values()) { + for (const ext of exts) { + const hit = perDir.find((h) => h.toLowerCase().endsWith(ext)); + if (hit) return hit; + } + } + return hits[0]; + } catch { + return claude; + } } function defaultWhereRunner(name: string): { stdout: string | null } { - const r = spawnSync("where.exe", [name], { stdio: ["ignore", "pipe", "ignore"], timeout: 5000, encoding: "utf8", windowsHide: true }); - return { stdout: r.stdout ?? null }; + const r = spawnSync("where.exe", [name], { + stdio: ["ignore", "pipe", "ignore"], + timeout: 5000, + encoding: "utf8", + windowsHide: true, + }); + return { stdout: r.stdout ?? null }; } function claudeInstall(): string { - if (process.env.BILI_NATIVE_CLAUDE === "0") { - throw new Error("claude: install refused — BILI_NATIVE_CLAUDE=0 is set (clear it to install the native posture)"); - } - const root = selfPackageRoot(); - const mcpJs = path.join(root, "dist", "mcp.js"); - const bootstrapJs = path.join(root, "dist", "claude-native-bootstrap.js"); - requireDistFile(mcpJs); - requireDistFile(bootstrapJs); - - // Managed block first: the static URL + bootstrap hook + compaction off. - // #964/#1660: the baked URL uses the explicit override - // (BILI_CLAUDE_NATIVE_PORT / claude.nativePort) when set — which also - // makes every later hook launch strict-port — else the current zone - // preference (sticky record > 18787 base). An explicit env-driven port - // can no longer desync from the hook: both resolve through - // resolveClaudeNativePort(), and the SessionStart hook's repin pass - // rewrites the baked URL to the live origin anyway (#1660). - const nativePort = resolveClaudeNativePort() ?? lanePreferredPort("claude"); - const file = claudeSettingsFile(); - const settings = readJson(file); - // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. - const hookCommand = portableHookCommand("node", [bootstrapJs]); - const { data, notes } = applyClaudeManagedBlock(settings, { - baseUrl: claudeNativeBaseUrl(), - hookCommand, - }); - writeJson(file, data); - - // MCP face: same registration path as before, but pinned to the STABLE - // port the hook brings up — never proxyOriginForInstall() (an ephemeral - // launcher proxy would go stale in this static config). - const stableOrigin = `http://127.0.0.1:${nativePort}`; - const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); - try { - runClaudeCli(claude, ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${stableOrigin}`, "--", process.execPath, mcpJs]); - } catch (err) { - const stderr = err instanceof Error && "stderr" in err ? String((err as { stderr?: Buffer | string }).stderr ?? "") : ""; - throw new Error(`claude: MCP registration failed (${stderr.trim() || (err instanceof Error ? err.message : String(err))}) — is the claude CLI on PATH? (the managed settings block at ${file} was written; rerun after fixing the CLI to complete the MCP face)`); - } - - let cmdNote: string; - const cmdFile = claudeAcpCacheCommandFile(); - try { - fs.mkdirSync(path.dirname(cmdFile), { recursive: true }); - const existing = fs.existsSync(cmdFile) ? fs.readFileSync(cmdFile, "utf8") : undefined; - if (existing === undefined || existing.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd()) { - fs.writeFileSync(cmdFile, CLAUDE_ACP_CACHE_COMMAND); - cmdNote = `written`; - } else { - cmdNote = `left untouched (foreign content)`; - } - } catch (err) { - throw new Error(`claude: /acp-cache command write failed (${err instanceof Error ? err.message : String(err)}) — the managed settings block at ${file} and the MCP face were written; fix the permissions and rerun`); - } - return `claude: managed block -> ${file} (${notes.join("; ")}); /acp-cache command -> ${cmdFile} (${cmdNote}); MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin}) — restart claude to activate`; + if (process.env.BILI_NATIVE_CLAUDE === "0") { + throw new Error( + "claude: install refused — BILI_NATIVE_CLAUDE=0 is set (clear it to install the native posture)", + ); + } + const root = selfPackageRoot(); + const mcpJs = path.join(root, "dist", "mcp.js"); + const bootstrapJs = path.join(root, "dist", "claude-native-bootstrap.js"); + requireDistFile(mcpJs); + requireDistFile(bootstrapJs); + + // Managed block first: the static URL + bootstrap hook + compaction off. + // #964/#1660: the baked URL uses the explicit override + // (BILI_CLAUDE_NATIVE_PORT / claude.nativePort) when set — which also + // makes every later hook launch strict-port — else the current zone + // preference (sticky record > 18787 base). An explicit env-driven port + // can no longer desync from the hook: both resolve through + // resolveClaudeNativePort(), and the SessionStart hook's repin pass + // rewrites the baked URL to the live origin anyway (#1660). + const nativePort = resolveClaudeNativePort() ?? lanePreferredPort("claude"); + const file = claudeSettingsFile(); + const settings = readJson(file); + // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. + const hookCommand = portableHookCommand("node", [bootstrapJs]); + const { data, notes } = applyClaudeManagedBlock(settings, { + baseUrl: claudeNativeBaseUrl(), + hookCommand, + }); + writeJson(file, data); + + // MCP face: same registration path as before, but pinned to the STABLE + // port the hook brings up — never proxyOriginForInstall() (an ephemeral + // launcher proxy would go stale in this static config). + const stableOrigin = `http://127.0.0.1:${nativePort}`; + const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); + try { + runClaudeCli(claude, [ + "mcp", + "add", + "bili", + "--scope", + "user", + "-e", + `BILI_MCP_PROXY=${stableOrigin}`, + "--", + process.execPath, + mcpJs, + ]); + } catch (err) { + const stderr = + err instanceof Error && "stderr" in err + ? String((err as { stderr?: Buffer | string }).stderr ?? "") + : ""; + throw new Error( + `claude: MCP registration failed (${stderr.trim() || (err instanceof Error ? err.message : String(err))}) — is the claude CLI on PATH? (the managed settings block at ${file} was written; rerun after fixing the CLI to complete the MCP face)`, + ); + } + + let cmdNote: string; + const cmdFile = claudeAcpCacheCommandFile(); + try { + fs.mkdirSync(path.dirname(cmdFile), { recursive: true }); + const existing = fs.existsSync(cmdFile) + ? fs.readFileSync(cmdFile, "utf8") + : undefined; + if ( + existing === undefined || + existing.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd() + ) { + fs.writeFileSync(cmdFile, CLAUDE_ACP_CACHE_COMMAND); + cmdNote = `written`; + } else { + cmdNote = `left untouched (foreign content)`; + } + } catch (err) { + throw new Error( + `claude: /acp-cache command write failed (${err instanceof Error ? err.message : String(err)}) — the managed settings block at ${file} and the MCP face were written; fix the permissions and rerun`, + ); + } + return `claude: managed block -> ${file} (${notes.join("; ")}); /acp-cache command -> ${cmdFile} (${cmdNote}); MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin}) — restart claude to activate`; } function claudeRemove(): string { - const parts: string[] = []; - const file = claudeSettingsFile(); - const settings = readJson(file); - const { data, removed } = stripClaudeManagedBlock(settings); - if (removed.length > 0) { - // Restore a pre-install DISABLE_AUTO_COMPACT when the backup holds - // one (writeJson snapshotted the pristine file on first install). - const bak = `${file}.bili-bak`; - try { - if (fs.existsSync(bak)) { - const bakData = readJson(bak) as { env?: Record }; - const bakDac = bakData.env?.DISABLE_AUTO_COMPACT; - if (removed.includes("env.DISABLE_AUTO_COMPACT") && bakDac !== undefined) { - const env = ((data.env !== null && typeof data.env === "object" && !Array.isArray(data.env) ? data.env : {}) as Record); - env.DISABLE_AUTO_COMPACT = bakDac; - data.env = env; - } - } - } catch { - // unreadable backup — the value is simply dropped - } - writeJson(file, data); - parts.push(`managed block removed from ${file} (${removed.join(", ")})`); - } - if (claudeMcpInstalled()) { - const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); - try { - runClaudeCli(claude, ["mcp", "remove", "bili", "--scope", "user"]); - parts.push("MCP face removed"); - } catch (err) { - throw new Error(`claude: MCP removal failed (${err instanceof Error ? err.message : String(err)})${parts.length > 0 ? ` — ${parts.join("; ")} succeeded first` : ""}`); - } - } - const cmdFile = claudeAcpCacheCommandFile(); - try { - if (fs.existsSync(cmdFile)) { - const content = fs.readFileSync(cmdFile, "utf8"); - if (content.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd()) { - fs.unlinkSync(cmdFile); - parts.push("/acp-cache command removed"); - } else { - parts.push(`/acp-cache command left untouched (${cmdFile} holds foreign content)`); - } - } - } catch (err) { - parts.push(`/acp-cache command removal skipped (${err instanceof Error ? err.message : String(err)})`); - } - return parts.length > 0 ? `claude: ${parts.join("; ")}` : `claude: not installed (${file} / ${claudeMcpJson()})`; + const parts: string[] = []; + const file = claudeSettingsFile(); + const settings = readJson(file); + const { data, removed } = stripClaudeManagedBlock(settings); + if (removed.length > 0) { + // Restore a pre-install DISABLE_AUTO_COMPACT when the backup holds + // one (writeJson snapshotted the pristine file on first install). + const bak = `${file}.bili-bak`; + try { + if (fs.existsSync(bak)) { + const bakData = readJson(bak) as { env?: Record }; + const bakDac = bakData.env?.DISABLE_AUTO_COMPACT; + if ( + removed.includes("env.DISABLE_AUTO_COMPACT") && + bakDac !== undefined + ) { + const env = ( + data.env !== null && + typeof data.env === "object" && + !Array.isArray(data.env) + ? data.env + : {} + ) as Record; + env.DISABLE_AUTO_COMPACT = bakDac; + data.env = env; + } + } + } catch { + // unreadable backup — the value is simply dropped + } + writeJson(file, data); + parts.push(`managed block removed from ${file} (${removed.join(", ")})`); + } + if (claudeMcpInstalled()) { + const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); + try { + runClaudeCli(claude, ["mcp", "remove", "bili", "--scope", "user"]); + parts.push("MCP face removed"); + } catch (err) { + throw new Error( + `claude: MCP removal failed (${err instanceof Error ? err.message : String(err)})${parts.length > 0 ? ` — ${parts.join("; ")} succeeded first` : ""}`, + ); + } + } + const cmdFile = claudeAcpCacheCommandFile(); + try { + if (fs.existsSync(cmdFile)) { + const content = fs.readFileSync(cmdFile, "utf8"); + if (content.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd()) { + fs.unlinkSync(cmdFile); + parts.push("/acp-cache command removed"); + } else { + parts.push( + `/acp-cache command left untouched (${cmdFile} holds foreign content)`, + ); + } + } + } catch (err) { + parts.push( + `/acp-cache command removal skipped (${err instanceof Error ? err.message : String(err)})`, + ); + } + return parts.length > 0 + ? `claude: ${parts.join("; ")}` + : `claude: not installed (${file} / ${claudeMcpJson()})`; } function claudeMcpInstalled(): boolean { - const data = readJson(claudeMcpJson()) as { mcpServers?: Record }; - return isPlainMcpObject(data.mcpServers) && "bili" in data.mcpServers; + const data = readJson(claudeMcpJson()) as { + mcpServers?: Record; + }; + return isPlainMcpObject(data.mcpServers) && "bili" in data.mcpServers; } function claudeStatus(): string { - let block = false; - try { - const data = readJson(claudeSettingsFile()); - block = isBiliClaudeBaseUrl((data.env as Record | undefined)?.ANTHROPIC_BASE_URL); - } catch { - block = false; - } - const mcp = (() => { - try { - return claudeMcpInstalled(); - } catch { - return false; - } - })(); - if (block && mcp) return "installed (managed settings block + MCP)"; - if (block) return "installed (managed settings block; MCP face missing — rerun install)"; - if (mcp) return "installed (MCP only — legacy companion posture; rerun install for the native block)"; - return "not installed"; + let block = false; + try { + const data = readJson(claudeSettingsFile()); + block = isBiliClaudeBaseUrl( + (data.env as Record | undefined)?.ANTHROPIC_BASE_URL, + ); + } catch { + block = false; + } + const mcp = (() => { + try { + return claudeMcpInstalled(); + } catch { + return false; + } + })(); + if (block && mcp) return "installed (managed settings block + MCP)"; + if (block) + return "installed (managed settings block; MCP face missing — rerun install)"; + if (mcp) + return "installed (MCP only — legacy companion posture; rerun install for the native block)"; + return "not installed"; } // — codex —————————————————————————————————————————————————————————————— function codexToml(): string { - const raw = process.env.CODEX_HOME?.trim(); - if (raw && raw.length > 0) return path.join(raw, "config.toml"); - return homeFile(".codex/config.toml"); + const raw = process.env.CODEX_HOME?.trim(); + if (raw && raw.length > 0) return path.join(raw, "config.toml"); + return homeFile(".codex/config.toml"); } function codexBlock(): string { - // #1660: no baked origin — the MCP shell discovers the live proxy at - // startup (env > live instance file > 8787 user-zone default), so the - // block never goes stale when the proxy's port drifts or the machine - // reboots. BILI_MCP_PROXY in the user's environment still wins. - return `\n[mcp_servers.bili]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(path.join(selfPackageRoot(), "dist", "mcp.js"))}]\n`; + // #1660: no baked origin — the MCP shell discovers the live proxy at + // startup (env > live instance file > 8787 user-zone default), so the + // block never goes stale when the proxy's port drifts or the machine + // reboots. BILI_MCP_PROXY in the user's environment still wins. + return `\n[mcp_servers.bili]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(path.join(selfPackageRoot(), "dist", "mcp.js"))}]\n`; +} + +/** Force every line ending in `text` to the convention `reference` already + * uses. The individual renderers (codexBlock, codexHookTable) emit `\n`, so + * without this a CRLF config — the norm on Windows — would come back with a + * mixed-ending bili block spliced into it. Follows the repo convention + * (src/kimi/toml-edit.ts:21, src/launcher.ts:2466): never convert the user's + * file, never mix endings into it. */ +function normalizeCodexEol(text: string, reference: string): string { + const lf = text.replace(/\r\n/g, "\n"); + return reference.includes("\r\n") ? lf.replace(/\n/g, "\r\n") : lf; } function malformedCodexArgs(block: string): boolean { - return /^[ \t]*args[ \t]*=[ \t]*["']/m.test(block); + return /^[ \t]*args[ \t]*=[ \t]*["']/m.test(block); +} + +/** The model-route face of the codex lane (ticket 01). Distinct from the MCP + * face above and reported separately: `[mcp_servers.bili]` proves TOOLS, + * never that model traffic reaches bili. Ownership is content-based + * (codex-integration/route.ts) so a user- or CC-Switch-owned + * `openai_base_url` is never overwritten — a conflict is REPORTED instead. */ +function codexRouteSync( + text: string, + file: string, +): { + text: string; + note: string; + conflicted: boolean; + record?: ReturnType; +} { + const recordPath = codexRouteRecordPath(file); + const previous = readCodexRouteRecord(recordPath); + const defaultHomeConfig = + path.resolve(file).toLowerCase() === + path + .resolve(path.join(os.homedir(), ".codex", "config.toml")) + .toLowerCase(); + const ccSwitchMode = defaultHomeConfig ? detectCcSwitch().mode : "unknown"; + const plan = planCodexRoute(text, { + origin: codexRouteOrigin(process.env), + ownedValue: previous?.writtenValue, + ownedRecord: previous, + ccSwitchMode, + }); + if (plan.action === "keep") + return { + text, + note: `model route: ${plan.note}`, + conflicted: false, + record: previous, + }; + if (plan.action === "conflict") + return { + text, + note: `model route: ${plan.note}`, + conflicted: true, + record: previous, + }; + const value = plan.value!; + const route = value.slice(value.indexOf("/bili/") + "/bili/".length); + const target = plan.target ?? { kind: "top-level" as const }; + const previousTarget = previous?.target ?? { kind: "top-level" as const }; + const targetMatches = + previousTarget.kind === target.kind && + (target.kind === "top-level" || + (previousTarget.kind === "provider" && + previousTarget.provider === target.provider)); + const previousValue = targetMatches + ? (previous?.previousValue ?? null) + : target.kind === "provider" + ? (parseCodexToml(text).providers?.[target.provider]?.baseUrl ?? null) + : (parseCodexToml(text).openaiBaseUrl ?? null); + return { + text: plan.text, + note: `model route: ${plan.note}`, + conflicted: false, + record: { + schemaVersion: 1, + writtenValue: value, + previousValue, + upstream: route, + target, + }, + }; +} + +/** The SessionStart-hook face of the codex lane (ticket 08). Codex reads + * `[[hooks.SessionStart]]` entries from config.toml and gates them behind + * `[features] hooks`; bili owns exactly one entry identified by its command + * (codex-integration/hooks.ts). A foreign hook table is REPORTED, never + * rewritten — same ownership rule as the model route. */ +function codexHookSync( + text: string, + warn: (message: string) => void, +): { text: string; note: string; changed: boolean } { + const root = selfPackageRoot(); + const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); + if (!fs.existsSync(hookScript)) { + warn( + `codex: hook script missing at ${hookScript} — skipping the SessionStart hook face (rebuild bili)`, + ); + return { + text, + note: "hook: skipped (dist/codex/bootstrap-hook.js missing)", + changed: false, + }; + } + const command = portableHookCommand("node", [hookScript]); + const plan = planCodexHook(text, command); + const shape = assertCodexConfigLoads(plan.text); + if (shape !== undefined) { + warn(`codex: ${shape} — SessionStart hook NOT written`); + return { + text, + note: `hook: skipped (${shape})`, + changed: false, + }; + } + const featureNote = codexHooksEnabledNote(plan.text); + if (featureNote !== "" && plan.action !== "keep") + warn( + `codex: SessionStart hook written, but hook execution is not enabled — ${featureNote}`, + ); + const note = + featureNote === "" + ? `hook: ${plan.note}` + : `hook: ${plan.note} — ${featureNote}`; + return { + text: plan.text, + note, + changed: plan.action !== "keep", + }; +} + +/** The ACP-skill face of the codex lane (ticket 08): `/skills/bili/ + * SKILL.md`, Codex's own discovered-skill extension point. Reported as a + * THIRD face next to mcp/hook, because a skill changes what the model does, + * not whether traffic is compressed. */ +function codexSkillSync(warn: (message: string) => void): { + note: string; + changed: boolean; +} { + const result = installCodexSkill(process.env); + if (result.state === "foreign") warn(`codex: ${result.note}`); + return { note: `skill: ${result.note}`, changed: result.written }; +} + +/** Best-effort service hook for `bili plugin install|remove `. + * + * "Installed" must mean USABLE: the MCP face only DISCOVERS a proxy + * (resolveProxyOrigin in src/mcp.ts) and never starts one, so an install that + * leaves no proxy running produces `bili proxy unreachable` on the first tool + * call. Registering the per-user service (Windows Task Scheduler task / + * Linux systemd user unit) closes that gap. + * + * Deliberately FAIL-SOFT and never throwing: a host that cannot register a + * service (no systemd user bus, an unprivileged/container session, a policy + * that bans scheduled tasks) must still have a complete, working config — the + * caller degrades to a printed hint and the user starts the proxy by hand. + * That keeps this hook from turning a successful config install into a + * reported failure. */ +async function serviceSync( + action: "install" | "remove", +): Promise<{ note: string; warning?: string }> { + try { + const result = + action === "install" + ? await installProxyService() + : await removeProxyService(); + if (result.ok) + return { + note: + result.action === "already-installed" + ? "service: already registered" + : action === "install" + ? "service: registered for logon + started" + : "service: removed", + }; + if (result.action === "already-absent") + return { note: "service: none registered" }; + if (result.action === "unsupported") + return { + note: "service: not applicable", + warning: `${result.message}; start the proxy yourself with \`bili start\``, + }; + return { + note: "service: NOT registered", + warning: `${result.message}; start the proxy yourself with \`bili start\``, + }; + } catch (error) { + return { + note: "service: NOT registered", + warning: `service registration failed (${error instanceof Error ? error.message : String(error)}); start the proxy yourself with \`bili start\``, + }; + } +} + +/** `bili plugin install codex`: the config faces PLUS the service face. + * Kept as a wrapper so the synchronous config writers above stay synchronous + * (and unit-testable without a live scheduler/bus); the CLI layer awaits this + * one and prints a single line. */ +export async function codexInstallWithService(): Promise { + const base = codexInstall(); + const service = await serviceSync("install"); + return service.warning !== undefined + ? `${base}; ${service.note}\n ! ${service.warning}` + : `${base}; ${service.note}`; +} + +/** `bili plugin remove codex`: config faces plus service teardown, so an + * uninstall does not leave a proxy running behind the user's back. */ +export async function codexRemoveWithService(): Promise { + const base = codexRemove(); + const service = await serviceSync("remove"); + return service.warning !== undefined + ? `${base}; ${service.note}\n ! ${service.warning}` + : `${base}; ${service.note}`; } function codexInstall(): string { - const file = codexToml(); - const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; - const existing = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text); - if (existing !== null) { - // End the block at the next TABLE header line (optional indent + `[`), - // matching codexRemove. A plain indexOf("\n[") misses an indented next - // table and lets the block run to EOF, deleting everything after it. - const after = text.slice(existing.index); - const firstNewline = after.indexOf("\n"); - const nextTable = firstNewline < 0 ? -1 : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); - const blockEnd = nextTable >= 0 ? existing.index + firstNewline + 1 + nextTable : text.length; - const block = text.slice(existing.index, blockEnd); - const canonical = codexBlock().replace(/^\n/, ""); - if (block.trimEnd() === canonical.trimEnd()) return `codex: already installed (${file})`; - const refreshed = text.slice(0, existing.index) + canonical + text.slice(existing.index + block.length); - writeConfigText(file, refreshed); - const healed = malformedCodexArgs(block) ? " (repaired args: was not an array)" : ""; - return `codex: refreshed [mcp_servers.bili] -> ${file}${healed}`; - } - fs.mkdirSync(path.dirname(file), { recursive: true }); - backupBeforeWrite(file); - fs.writeFileSync(file, text + (text.endsWith("\n") || text.length === 0 ? "" : "\n") + codexBlock()); - try { - fs.writeFileSync(`${file}.bili-last`, `${hashText(fs.readFileSync(file, "utf8"))}\n`); - } catch {} - return `codex: installed -> ${file} [mcp_servers.bili]`; + const file = codexToml(); + const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + const warnings: string[] = []; + const warn = (message: string): void => { + warnings.push(message); + }; + const existing = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text); + let next = text; + let mcpNote: string; + if (existing !== null) { + // End the block at the next TABLE header line (optional indent + `[`), + // matching codexRemove. A plain indexOf("\n[") misses an indented next + // table and lets the block run to EOF, deleting everything after it. + const after = text.slice(existing.index); + const firstNewline = after.indexOf("\n"); + const nextTable = + firstNewline < 0 + ? -1 + : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); + const blockEnd = + nextTable >= 0 + ? existing.index + firstNewline + 1 + nextTable + : text.length; + const block = text.slice(existing.index, blockEnd); + const canonical = codexBlock().replace(/^\n/, ""); + if (block.trimEnd() === canonical.trimEnd()) { + mcpNote = "mcp: already installed"; + } else { + next = + text.slice(0, existing.index) + + canonical + + text.slice(existing.index + block.length); + mcpNote = `mcp: refreshed [mcp_servers.bili]${malformedCodexArgs(block) ? " (repaired args: was not an array)" : ""}`; + } + } else { + fs.mkdirSync(path.dirname(file), { recursive: true }); + next = + text + + (text.endsWith("\n") || text.length === 0 ? "" : "\n") + + codexBlock(); + mcpNote = "mcp: installed [mcp_servers.bili]"; + } + const route = codexRouteSync(next, file); + next = route.text; + const hook = codexHookSync(next, warn); + next = hook.text; + const skill = codexSkillSync(warn); + // Single write exit: every renderer above emits "\n", so normalize once + // against the file we started from. Without this a CRLF config (the norm on + // Windows) came back with a mixed-ending bili block spliced in. + const finalText = normalizeCodexEol(next, text); + if ( + finalText === text && + existing !== null && + mcpNote === "mcp: already installed" && + !hook.changed && + !skill.changed + ) { + return `codex: already installed (${file}) — ${mcpNote}; ${route.note}; ${hook.note}; ${skill.note}`; + } + writeConfigText(file, finalText); + if (route.record !== undefined) + writeCodexRouteRecord(codexRouteRecordPath(file), route.record); + const conflictNote = route.conflicted ? " (NOT routed — see note)" : ""; + const detail = `${mcpNote}; ${route.note}${conflictNote}; ${hook.note}; ${skill.note}`; + const tail = + warnings.length > 0 + ? `\n${warnings.map((w) => ` ! ${w}`).join("\n")}` + : ""; + if (mcpNote.startsWith("mcp: refreshed")) + return `codex: refreshed [mcp_servers.bili] -> ${file} — ${detail}${tail}`; + if (mcpNote.startsWith("mcp: installed")) + return `codex: installed -> ${file} — ${detail}${tail}`; + return `codex: refreshed -> ${file} — ${detail}${tail}`; } function codexRemove(): string { - const file = codexToml(); - if (!fs.existsSync(file)) return `codex: not installed (${file})`; - const text = fs.readFileSync(file, "utf8"); - const start = (() => { - const m = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text); - return m === null ? -1 : m.index; - })(); - if (start < 0) return `codex: not installed (${file})`; - const lineStart = text.lastIndexOf("\n", start - 1) + 1; - const after = text.slice(start); - const firstNewline = after.indexOf("\n"); - const nextTable = firstNewline < 0 ? -1 : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); - const end = nextTable >= 0 ? start + firstNewline + 1 + nextTable : text.length; - const cleaned = (text.slice(0, lineStart).replace(/\n+$/, "\n") + text.slice(end)).replace(/^\n+/, ""); - writeConfigText(file, cleaned); - return `codex: removed from ${file}`; + const file = codexToml(); + const skill = removeCodexSkill(process.env); + if (!fs.existsSync(file)) + return `codex: not installed (${file}) — skill: ${skill.note}`; + const text = fs.readFileSync(file, "utf8"); + const routeRecordPath = codexRouteRecordPath(file); + const routeRecord = readCodexRouteRecord(routeRecordPath); + const restoredRoute = restoreCodexRoute(text, routeRecord); + const hook = stripCodexHook(restoredRoute.text); + const stripped = hook.text; + const start = (() => { + const m = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(stripped); + return m === null ? -1 : m.index; + })(); + const faces = [ + hook.removed ? "hook removed" : "no hook", + `skill: ${skill.removed ? "removed" : skill.note}`, + ]; + if (start < 0) { + if (stripped === text) + return `codex: not installed (${file}) — ${faces.join("; ")}`; + writeConfigText(file, stripped); + removeCodexRouteRecord(routeRecordPath); + return `codex: model route restored from ${file} (no MCP block present) — ${faces.join("; ")}`; + } + const lineStart = stripped.lastIndexOf("\n", start - 1) + 1; + const after = stripped.slice(start); + const firstNewline = after.indexOf("\n"); + const nextTable = + firstNewline < 0 ? -1 : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); + const end = + nextTable >= 0 ? start + firstNewline + 1 + nextTable : stripped.length; + const cleaned = ( + stripped.slice(0, lineStart).replace(/\n+$/, "\n") + stripped.slice(end) + ).replace(/^\n+/, ""); + writeConfigText(file, cleaned); + removeCodexRouteRecord(routeRecordPath); + return `codex: removed from ${file} — ${faces.join("; ")}`; } function codexStatus(): string { - const text = fs.existsSync(codexToml()) ? fs.readFileSync(codexToml(), "utf8") : ""; - return /^\[mcp_servers\.bili\]\s*$/m.test(text) ? "installed" : "not installed"; + const file = codexToml(); + const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + const mcp = /^\[mcp_servers\.bili\]\s*$/m.test(text); + const owned = readCodexRouteRecord(codexRouteRecordPath(file)); + const route = readCodexRoute(text, owned); + const routeText = + route.conflict !== undefined + ? `route blocked (${route.conflict.kind})` + : route.routed + ? route.value === desiredCodexRoute(text, codexRouteOrigin(process.env)) + ? "route installed" + : `route drifted (${route.value})` + : "route not installed"; + const hookInstalled = findBiliCodexHook(text) !== undefined; + const hookText = hookInstalled + ? codexHooksEnabledNote(text) === "" + ? "hook installed" + : `hook installed but disabled (${codexHooksEnabledNote(text)})` + : "hook not installed"; + const skillState = codexSkillStatus(process.env); + const skillText = + skillState === "installed" + ? "skill installed" + : skillState === "outdated" + ? "skill outdated (rerun install)" + : skillState === "foreign" + ? "skill not ours (left untouched)" + : "skill not installed"; + if (!mcp && !route.routed && !hookInstalled && skillState !== "installed") + return "not installed"; + return `${mcp ? "mcp installed" : "mcp missing"}; ${routeText}; ${hookText}; ${skillText}`; } // — opencode ———————————————————————————————————————————————————————————— @@ -964,7 +1560,7 @@ function codexStatus(): string { // back to major 1, whose key (`plugin`) 2.x still honors as a legacy alias, // so degradation can never write a dead config line. export function pickPluginKey(major: number): "plugin" | "plugins" { - return major >= 2 ? "plugins" : "plugin"; + return major >= 2 ? "plugins" : "plugin"; } const PLUGIN_KEYS = ["plugin", "plugins"] as const; @@ -974,30 +1570,47 @@ const ocMajorCache = new Map(); /** Host major version via ` --version` (probe failure → 1). Same * contract as the launcher's probe; honors the BILI_CLIENT_BIN override. */ export function detectOpencodeMajor(): number { - const command = process.env.BILI_CLIENT_BIN?.trim() || "opencode"; - const hit = ocMajorCache.get(command); - if (hit !== undefined) return hit; - let major = 1; - try { - // Windows: npm global shims are .cmd/.bat — execFileSync cannot spawn - // those directly (EINVAL), so route through the shell with explicit - // quoting. Plain exes and POSIX shebang scripts go straight through. - const viaShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(command); - const out = viaShell - ? execFileSync(`"${command}" --version`, { shell: true, timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }) - : execFileSync(command, ["--version"], { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }); - const m = /(\d+)\s*\./.exec(out); - if (m) major = parseInt(m[1], 10); - } catch {} - ocMajorCache.set(command, major); - return major; + const command = process.env.BILI_CLIENT_BIN?.trim() || "opencode"; + const hit = ocMajorCache.get(command); + if (hit !== undefined) return hit; + let major = 1; + try { + // Windows: npm global shims are .cmd/.bat — execFileSync cannot spawn + // those directly (EINVAL), so route through the shell with explicit + // quoting. Plain exes and POSIX shebang scripts go straight through. + const viaShell = + process.platform === "win32" && /\.(cmd|bat)$/i.test(command); + const out = viaShell + ? execFileSync(`"${command}" --version`, { + shell: true, + timeout: 5000, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }) + : execFileSync(command, ["--version"], { + timeout: 5000, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }); + const m = /(\d+)\s*\./.exec(out); + if (m) major = parseInt(m[1], 10); + } catch (error) { + // Version probing is advisory; the caller falls back to the conservative major. + void error; + } + ocMajorCache.set(command, major); + return major; } function pluginEntries(data: Record, key: string): string[] { - const v = data[key]; - if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string"); - if (v !== null && typeof v === "object") return Object.keys(v as Record); - return []; + const v = data[key]; + if (Array.isArray(v)) + return v.filter((x): x is string => typeof x === "string"); + if (v !== null && typeof v === "object") + return Object.keys(v as Record); + return []; } // #927: write target = explicit OPENCODE_CONFIG override, else the @@ -1006,38 +1619,41 @@ function pluginEntries(data: Record, key: string): string[] { // opencode.json. Never spawn a second file next to an existing config — that // splits one logical config across files (#927). function opencodeTargetFile(): string { - const raw = process.env.OPENCODE_CONFIG?.trim(); - if (raw && raw.length > 0) return raw; - const xdg = process.env.XDG_CONFIG_HOME?.trim(); - const dir = xdg && xdg.length > 0 ? path.join(xdg, "opencode") : path.join(os.homedir(), ".config", "opencode"); - for (const name of ["opencode.jsonc", "opencode.json", "config.json"]) { - const p = path.join(dir, name); - if (fs.existsSync(p)) return p; - } - return path.join(dir, "opencode.json"); + const raw = process.env.OPENCODE_CONFIG?.trim(); + if (raw && raw.length > 0) return raw; + const xdg = process.env.XDG_CONFIG_HOME?.trim(); + const dir = + xdg && xdg.length > 0 + ? path.join(xdg, "opencode") + : path.join(os.homedir(), ".config", "opencode"); + for (const name of ["opencode.jsonc", "opencode.json", "config.json"]) { + const p = path.join(dir, name); + if (fs.existsSync(p)) return p; + } + return path.join(dir, "opencode.json"); } // #820 native mode: OpenCode 2.x rejects bare FILE paths in `plugin` — the // entry must be a DIRECTORY whose index.js is the entrypoint (#754 probe). The // wrapper directory lives next to the config so it survives config moves. function opencodePluginDir(configFile: string): string { - return path.join(path.dirname(configFile), "plugins", "billion-context"); + return path.join(path.dirname(configFile), "plugins", "billion-context"); } // #809/N4: opencode.json may carry a non-object `mcp` (e.g. a bare string); // `"bili" in ` throws TypeError. Guard so install/remove/status // degrade gracefully instead of crashing (a crashing remove leaves no cleanup). function isPlainMcpObject(v: unknown): v is Record { - return v !== null && typeof v === "object" && !Array.isArray(v); + return v !== null && typeof v === "object" && !Array.isArray(v); } function readOriginalText(file: string): string { - try { - return fs.readFileSync(file, "utf8"); - } catch (err) { - if ((err as { code?: string }).code === "ENOENT") return ""; - throw err; - } + try { + return fs.readFileSync(file, "utf8"); + } catch (err) { + if ((err as { code?: string }).code === "ENOENT") return ""; + throw err; + } } // JSONC-tolerant parse: the target may be an opencode.jsonc carrying comments @@ -1045,49 +1661,75 @@ function readOriginalText(file: string): string { // stringify round-trip would wash the comments away on write-back. Tolerance // is bounded: ANY diagnostic beyond comments/trailing commas means the file // is broken, and a broken config is never overwritten (§7.3). -function parseOpencodeConfig(text: string, file: string): Record { - const errors: ParseError[] = []; - const parsed = jsoncParse(text, errors, { allowTrailingComma: true }); - if (errors.length > 0 || parsed === undefined) { - const first = errors[0]; - const detail = first ? ` (offset ${first.offset})` : ""; - throw new Error(`${file}: not valid JSON${detail} — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`); - } - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { - throw new Error(`${file}: expected a JSON object at top level, refusing to overwrite`); - } - return parsed as Record; -} - -function loadOpencodeConfig(file: string): { original: string; data: Record } { - const original = readOriginalText(file); - return { original, data: original === "" ? {} : parseOpencodeConfig(original, file) }; +function parseOpencodeConfig( + text: string, + file: string, +): Record { + const errors: ParseError[] = []; + const parsed = jsoncParse(text, errors, { allowTrailingComma: true }); + if (errors.length > 0 || parsed === undefined) { + const first = errors[0]; + const detail = first ? ` (offset ${first.offset})` : ""; + throw new Error( + `${file}: not valid JSON${detail} — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`, + ); + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error( + `${file}: expected a JSON object at top level, refusing to overwrite`, + ); + } + return parsed as Record; +} + +function loadOpencodeConfig(file: string): { + original: string; + data: Record; +} { + const original = readOriginalText(file); + return { + original, + data: original === "" ? {} : parseOpencodeConfig(original, file), + }; } // Write back preserving everything bili did not touch: a missing or plain-JSON // target is serialized whole (the historical behavior); a JSONC target gets // surgical top-level-key edits so comments and formatting elsewhere survive // byte-for-byte (#927). A no-op run (nothing touched) leaves the file alone. -function writeOpencodeConfig(file: string, original: string, data: Record, touched: ReadonlySet): void { - if (touched.size === 0) return; - if (original === "") { - writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); - return; - } - let strict = false; - try { - JSON.parse(original); - strict = true; - } catch {} - if (strict) { - writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); - return; - } - let text = original; - for (const key of touched) { - text = applyEdits(text, jsoncModify(text, [key], data[key], { formattingOptions: { tabSize: 2, insertSpaces: true } })); - } - writeConfigText(file, text); +function writeOpencodeConfig( + file: string, + original: string, + data: Record, + touched: ReadonlySet, +): void { + if (touched.size === 0) return; + if (original === "") { + writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); + return; + } + let strict = false; + try { + JSON.parse(original); + strict = true; + } catch (error) { + // JSONC is expected here; preserve it with targeted edits instead. + void error; + } + if (strict) { + writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); + return; + } + let text = original; + for (const key of touched) { + text = applyEdits( + text, + jsoncModify(text, [key], data[key], { + formattingOptions: { tabSize: 2, insertSpaces: true }, + }), + ); + } + writeConfigText(file, text); } // Legacy opencode-acp plugin entries — both config shapes v1 accepts: @@ -1098,57 +1740,68 @@ function writeOpencodeConfig(file: string, original: string, data: Record s.length > 0); - // Any path segment naming the package identifies an acp install — covers - // dir specs, /index.js, and deeper entry paths like dist/index.js. - return segments.some((s) => s === "opencode-acp" || s.startsWith("opencode-acp@")); -} - -function stripLegacyOpencodeAcp(data: Record, notes: string[], touched: Set): void { - const removed: string[] = []; - for (const key of PLUGIN_KEYS) { - const v = data[key]; - let dropped = 0; - if (Array.isArray(v)) { - const survivors: unknown[] = []; - for (const entry of v) { - if (typeof entry === "string" && isLegacyOpencodeAcpEntry(entry)) { - removed.push(entry); - dropped++; - continue; - } - survivors.push(entry); - } - if (dropped > 0) { - if (survivors.length === 0) delete data[key]; - else data[key] = survivors; - touched.add(key); - } - } else if (v !== null && typeof v === "object") { - const map = v as Record; - for (const k of Object.keys(map)) { - if (isLegacyOpencodeAcpEntry(k)) { - delete map[k]; - removed.push(k); - dropped++; - } - } - if (dropped > 0) { - if (Object.keys(map).length === 0) delete data[key]; - touched.add(key); - } - } - } - if (removed.length > 0) { - notes.push(`replaced opencode-acp plugin entries (${removed.join(", ")}) — single compression owner; restore from the .bili-bak backup if that was intended`); - notes.push("also check /.opencode/opencode.json — a LOCAL-scope opencode-acp install (opencode plugin opencode-acp) lives there, not in this global config"); - } + if (entry === "opencode-acp" || entry.startsWith("opencode-acp@")) + return true; + if (entry.startsWith("npm:")) { + const rest = entry.slice(4); + return rest === "opencode-acp" || rest.startsWith("opencode-acp@"); + } + const normalized = entry.replace(/\\/g, "/"); + const segments = normalized.split("/").filter((s) => s.length > 0); + // Any path segment naming the package identifies an acp install — covers + // dir specs, /index.js, and deeper entry paths like dist/index.js. + return segments.some( + (s) => s === "opencode-acp" || s.startsWith("opencode-acp@"), + ); +} + +function stripLegacyOpencodeAcp( + data: Record, + notes: string[], + touched: Set, +): void { + const removed: string[] = []; + for (const key of PLUGIN_KEYS) { + const v = data[key]; + let dropped = 0; + if (Array.isArray(v)) { + const survivors: unknown[] = []; + for (const entry of v) { + if (typeof entry === "string" && isLegacyOpencodeAcpEntry(entry)) { + removed.push(entry); + dropped++; + continue; + } + survivors.push(entry); + } + if (dropped > 0) { + if (survivors.length === 0) delete data[key]; + else data[key] = survivors; + touched.add(key); + } + } else if (v !== null && typeof v === "object") { + const map = v as Record; + for (const k of Object.keys(map)) { + if (isLegacyOpencodeAcpEntry(k)) { + delete map[k]; + removed.push(k); + dropped++; + } + } + if (dropped > 0) { + if (Object.keys(map).length === 0) delete data[key]; + touched.add(key); + } + } + } + if (removed.length > 0) { + notes.push( + `replaced opencode-acp plugin entries (${removed.join(", ")}) — single compression owner; restore from the .bili-bak backup if that was intended`, + ); + notes.push( + "also check /.opencode/opencode.json — a LOCAL-scope opencode-acp install (opencode plugin opencode-acp) lives there, not in this global config", + ); + } } // #925: how THIS bili was installed decides which plugin entry install can @@ -1158,12 +1811,13 @@ function stripLegacyOpencodeAcp(data: Record, notes: string[], // Npm.add machinery (host-managed install + upgrade, portable config). Any // other form (git checkout / dev build) has no published entry — local shim dir. export function isNpmInstallForm(root: string): boolean { - return /(^|[/\\])node_modules[/\\]/.test(root); + return /(^|[/\\])node_modules[/\\]/.test(root); } export const OPENCODE_NPM_ENTRY = "billion-context"; -const DEV_FORM_NOTE = "dev form: machine-local shim, not portable across machines — an npm install writes the bare package name instead"; +const DEV_FORM_NOTE = + "dev form: machine-local shim, not portable across machines — an npm install writes the bare package name instead"; // #925: pick + apply the plugin entry for this install form. Replaces any // existing entry of either form (single owner), returns note(s). #927: the @@ -1175,223 +1829,284 @@ const DEV_FORM_NOTE = "dev form: machine-local shim, not portable across machine // scalars) are preserved verbatim in form and position. A strings-only // projection must never be written back, and "plugin present" must mean // the key was left untouched (no rewrite of the surrounding file either). -export function applyOpencodePluginEntry(args: { data: Record; root: string; shimDir: string; agentJs: string; key?: "plugin" | "plugins"; touched?: Set }): string[] { - const { data, root, shimDir, agentJs } = args; - const key = args.key ?? "plugin"; - const touched = args.touched ?? new Set(); - const ours = [OPENCODE_NPM_ENTRY, shimDir]; - const npmForm = isNpmInstallForm(root); - const entry = npmForm ? OPENCODE_NPM_ENTRY : shimDir; - const isOurs = (x: unknown): boolean => typeof x === "string" && ours.includes(x); - const raw = data[key]; - const oursIn = (): string[] => { - if (Array.isArray(raw)) return raw.filter((x): x is string => isOurs(x)); - if (raw !== null && typeof raw === "object") return Object.keys(raw as Record).filter((k) => isOurs(k)); - return []; - }; - const replaced = oursIn(); - if (npmForm && replaced.includes(shimDir)) fs.rmSync(shimDir, { recursive: true, force: true }); - if (!npmForm) { - fs.mkdirSync(shimDir, { recursive: true }); - fs.writeFileSync(path.join(shimDir, "index.js"), `export { default } from ${JSON.stringify(agentJs)};\n`); - } - // Exactly our one entry, already the right form — nothing to migrate: - // leave the key (and the file) untouched. - if (replaced.length === 1 && replaced[0] === entry) return [`${key} present`]; - if (Array.isArray(raw)) { - data[key] = [...raw.filter((x) => !isOurs(x)), entry]; - } else if (raw !== null && typeof raw === "object") { - const map = raw as Record; - for (const k of Object.keys(map)) if (isOurs(k)) delete map[k]; - map[entry] = true; - data[key] = map; - } else { - data[key] = [entry]; - } - touched.add(key); - if (npmForm) { - if (replaced.length === 0) return [`plugin -> ${OPENCODE_NPM_ENTRY}`]; - return [`plugin -> ${OPENCODE_NPM_ENTRY} (replaced ${replaced.join(", ")})`]; - } - if (replaced.length === 0) return [`plugin -> ${shimDir}`, DEV_FORM_NOTE]; - return [`plugin -> ${shimDir} (replaced ${replaced.join(", ")})`, DEV_FORM_NOTE]; +export function applyOpencodePluginEntry(args: { + data: Record; + root: string; + shimDir: string; + agentJs: string; + key?: "plugin" | "plugins"; + touched?: Set; +}): string[] { + const { data, root, shimDir, agentJs } = args; + const key = args.key ?? "plugin"; + const touched = args.touched ?? new Set(); + const ours = [OPENCODE_NPM_ENTRY, shimDir]; + const npmForm = isNpmInstallForm(root); + const entry = npmForm ? OPENCODE_NPM_ENTRY : shimDir; + const isOurs = (x: unknown): boolean => + typeof x === "string" && ours.includes(x); + const raw = data[key]; + const oursIn = (): string[] => { + if (Array.isArray(raw)) return raw.filter((x): x is string => isOurs(x)); + if (raw !== null && typeof raw === "object") + return Object.keys(raw as Record).filter((k) => + isOurs(k), + ); + return []; + }; + const replaced = oursIn(); + if (npmForm && replaced.includes(shimDir)) + fs.rmSync(shimDir, { recursive: true, force: true }); + if (!npmForm) { + fs.mkdirSync(shimDir, { recursive: true }); + fs.writeFileSync( + path.join(shimDir, "index.js"), + `export { default } from ${JSON.stringify(agentJs)};\n`, + ); + } + // Exactly our one entry, already the right form — nothing to migrate: + // leave the key (and the file) untouched. + if (replaced.length === 1 && replaced[0] === entry) return [`${key} present`]; + if (Array.isArray(raw)) { + data[key] = [...raw.filter((x) => !isOurs(x)), entry]; + } else if (raw !== null && typeof raw === "object") { + const map = raw as Record; + for (const k of Object.keys(map)) if (isOurs(k)) delete map[k]; + map[entry] = true; + data[key] = map; + } else { + data[key] = [entry]; + } + touched.add(key); + if (npmForm) { + if (replaced.length === 0) return [`plugin -> ${OPENCODE_NPM_ENTRY}`]; + return [ + `plugin -> ${OPENCODE_NPM_ENTRY} (replaced ${replaced.join(", ")})`, + ]; + } + if (replaced.length === 0) return [`plugin -> ${shimDir}`, DEV_FORM_NOTE]; + return [ + `plugin -> ${shimDir} (replaced ${replaced.join(", ")})`, + DEV_FORM_NOTE, + ]; } function opencodeInstall(withMcp = false): string { - const file = opencodeTargetFile(); - const { original, data } = loadOpencodeConfig(file); - const notes: string[] = []; - const touched = new Set(); - - // #926: the native plugin below registers the bili tools itself (auto - // session-bound), so opencode gets NO mcp.bili by default — a frozen - // BILI_MCP_PROXY there goes stale the moment the plugin's - // ephemeral-port proxy restarts. Default heals any entry an older - // install froze in. --with-mcp opts in; the entry then carries no origin - // pin (dist/mcp.js discovers the live proxy via the instance file at - // call time) unless BILI_MCP_PROXY is set for this install. - if (!withMcp) { - const rawMcp = data.mcp; - if (isPlainMcpObject(rawMcp) && "bili" in rawMcp) { - delete rawMcp.bili; - if (Object.keys(rawMcp).length === 0) delete data.mcp; - touched.add("mcp"); - notes.push("mcp.bili removed (stale second tool face — the native plugin provides the bili tools; install with --with-mcp to keep an MCP face)"); - } else { - notes.push("mcp.bili not written (the native plugin provides the bili tools; --with-mcp adds an MCP face)"); - } - } else { - try { - const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js"); - requireDistFile(mcpJs); - const rawMcp = data.mcp; - if (rawMcp != null && !isPlainMcpObject(rawMcp)) { - notes.push('mcp.bili skipped ("mcp" is not an object)'); - } else { - const mcp = (rawMcp as Record | undefined) ?? {}; - const explicit = process.env.BILI_MCP_PROXY?.trim(); - const bili = mcp.bili; - if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { - const env = (bili as Record).environment; - const envObj = env !== null && typeof env === "object" && !Array.isArray(env) ? (env as Record) : undefined; - if (envObj?.BILI_MCP_PROXY !== undefined && explicit === undefined) { - delete envObj.BILI_MCP_PROXY; - if (Object.keys(envObj).length === 0) delete (bili as Record).environment; - touched.add("mcp"); - notes.push("mcp.bili present (stale BILI_MCP_PROXY pin removed — live discovery takes over)"); - } else { - notes.push("mcp.bili present"); - } - } else { - const entry: Record = { type: "local", command: [process.execPath, mcpJs], enabled: true }; - if (explicit !== undefined) entry.environment = { BILI_MCP_PROXY: explicit }; - mcp.bili = entry; - data.mcp = mcp; - touched.add("mcp"); - notes.push(explicit !== undefined ? `mcp.bili written (BILI_MCP_PROXY=${explicit})` : "mcp.bili written (no origin pin — live discovery via instance file)"); - } - } - } catch (err) { - notes.push(`mcp.bili skipped (${err instanceof Error ? err.message : String(err)})`); - } - } - - // Native plugin (#820/#925): self-spawned proxy + http.request URL rewrite. - // Entry form depends on how THIS bili was installed — npm → bare package - // name (exports["./server"], host-managed), checkout/dev → local shim dir. - const root = selfPackageRoot(); - const agentJs = path.join(root, "dist", "agent", "opencode-native.js"); - requireDistFile(agentJs); - // Single compression owner FIRST: drop any opencode-acp entry before - // adding ours, so both never load armed in one host (#918). The write - // below snapshots the original config to .bili-bak (first write only). - stripLegacyOpencodeAcp(data, notes, touched); - // #927 entry key for this host + #925 entry form for this install form. - notes.push(...applyOpencodePluginEntry({ data, root, shimDir: opencodePluginDir(file), agentJs, key: pickPluginKey(detectOpencodeMajor()), touched })); - - // Single compression owner: with the native plugin installed, ACP owns - // compression — disable host auto-compaction (merge-preserving; the key is - // ignored on OpenCode 1.x). Restored from the pre-install backup on - // remove. #927: skip when the target already says auto:false — the user - // wrote it themselves, so one file carries the fact exactly once. - const curCompaction = data.compaction; - const curObj = curCompaction !== null && typeof curCompaction === "object" && !Array.isArray(curCompaction) ? curCompaction as Record : undefined; - if (curObj?.auto === false) { - notes.push("compaction.auto already disabled"); - } else { - data.compaction = { ...(curObj ?? {}), auto: false }; - touched.add("compaction"); - notes.push("compaction.auto set to false"); - } - - writeOpencodeConfig(file, original, data, touched); - return `opencode: installed -> ${file} (${notes.join("; ")})`; + const file = opencodeTargetFile(); + const { original, data } = loadOpencodeConfig(file); + const notes: string[] = []; + const touched = new Set(); + + // #926: the native plugin below registers the bili tools itself (auto + // session-bound), so opencode gets NO mcp.bili by default — a frozen + // BILI_MCP_PROXY there goes stale the moment the plugin's + // ephemeral-port proxy restarts. Default heals any entry an older + // install froze in. --with-mcp opts in; the entry then carries no origin + // pin (dist/mcp.js discovers the live proxy via the instance file at + // call time) unless BILI_MCP_PROXY is set for this install. + if (!withMcp) { + const rawMcp = data.mcp; + if (isPlainMcpObject(rawMcp) && "bili" in rawMcp) { + delete rawMcp.bili; + if (Object.keys(rawMcp).length === 0) delete data.mcp; + touched.add("mcp"); + notes.push( + "mcp.bili removed (stale second tool face — the native plugin provides the bili tools; install with --with-mcp to keep an MCP face)", + ); + } else { + notes.push( + "mcp.bili not written (the native plugin provides the bili tools; --with-mcp adds an MCP face)", + ); + } + } else { + try { + const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js"); + requireDistFile(mcpJs); + const rawMcp = data.mcp; + if (rawMcp != null && !isPlainMcpObject(rawMcp)) { + notes.push('mcp.bili skipped ("mcp" is not an object)'); + } else { + const mcp = (rawMcp as Record | undefined) ?? {}; + const explicit = process.env.BILI_MCP_PROXY?.trim(); + const bili = mcp.bili; + if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { + const env = (bili as Record).environment; + const envObj = + env !== null && typeof env === "object" && !Array.isArray(env) + ? (env as Record) + : undefined; + if (envObj?.BILI_MCP_PROXY !== undefined && explicit === undefined) { + delete envObj.BILI_MCP_PROXY; + if (Object.keys(envObj).length === 0) + delete (bili as Record).environment; + touched.add("mcp"); + notes.push( + "mcp.bili present (stale BILI_MCP_PROXY pin removed — live discovery takes over)", + ); + } else { + notes.push("mcp.bili present"); + } + } else { + const entry: Record = { + type: "local", + command: [process.execPath, mcpJs], + enabled: true, + }; + if (explicit !== undefined) + entry.environment = { BILI_MCP_PROXY: explicit }; + mcp.bili = entry; + data.mcp = mcp; + touched.add("mcp"); + notes.push( + explicit !== undefined + ? `mcp.bili written (BILI_MCP_PROXY=${explicit})` + : "mcp.bili written (no origin pin — live discovery via instance file)", + ); + } + } + } catch (err) { + notes.push( + `mcp.bili skipped (${err instanceof Error ? err.message : String(err)})`, + ); + } + } + + // Native plugin (#820/#925): self-spawned proxy + http.request URL rewrite. + // Entry form depends on how THIS bili was installed — npm → bare package + // name (exports["./server"], host-managed), checkout/dev → local shim dir. + const root = selfPackageRoot(); + const agentJs = path.join(root, "dist", "agent", "opencode-native.js"); + requireDistFile(agentJs); + // Single compression owner FIRST: drop any opencode-acp entry before + // adding ours, so both never load armed in one host (#918). The write + // below snapshots the original config to .bili-bak (first write only). + stripLegacyOpencodeAcp(data, notes, touched); + // #927 entry key for this host + #925 entry form for this install form. + notes.push( + ...applyOpencodePluginEntry({ + data, + root, + shimDir: opencodePluginDir(file), + agentJs, + key: pickPluginKey(detectOpencodeMajor()), + touched, + }), + ); + + // Single compression owner: with the native plugin installed, ACP owns + // compression — disable host auto-compaction (merge-preserving; the key is + // ignored on OpenCode 1.x). Restored from the pre-install backup on + // remove. #927: skip when the target already says auto:false — the user + // wrote it themselves, so one file carries the fact exactly once. + const curCompaction = data.compaction; + const curObj = + curCompaction !== null && + typeof curCompaction === "object" && + !Array.isArray(curCompaction) + ? (curCompaction as Record) + : undefined; + if (curObj?.auto === false) { + notes.push("compaction.auto already disabled"); + } else { + data.compaction = { ...(curObj ?? {}), auto: false }; + touched.add("compaction"); + notes.push("compaction.auto set to false"); + } + + writeOpencodeConfig(file, original, data, touched); + return `opencode: installed -> ${file} (${notes.join("; ")})`; } function opencodeRemove(): string { - const file = opencodeTargetFile(); - const { original, data } = loadOpencodeConfig(file); - const notes: string[] = []; - const touched = new Set(); - - const mcp = data.mcp; - if (isPlainMcpObject(mcp) && "bili" in mcp) { - delete mcp.bili; - if (Object.keys(mcp).length === 0) delete data.mcp; - touched.add("mcp"); - notes.push("mcp.bili removed"); - } - - // #927: clean our entry out of whichever key spelling carries it; the - // entry may be either form (#925) — bare npm name or shim dir. #1002: - // the key dies only when NOTHING raw survives — foreign object entries - // and map-form options are preserved verbatim, never collapsed. - const dir = opencodePluginDir(file); - const removed: string[] = []; - for (const key of PLUGIN_KEYS) { - const v = data[key]; - const hit = (x: string): boolean => x === OPENCODE_NPM_ENTRY || x === dir; - if (Array.isArray(v)) { - const survivors = v.filter((x) => !(typeof x === "string" && hit(x))); - if (survivors.length === v.length) continue; - for (const x of v) if (typeof x === "string" && hit(x)) removed.push(x); - if (survivors.length === 0) delete data[key]; - else data[key] = survivors; - touched.add(key); - } else if (v !== null && typeof v === "object") { - const map = v as Record; - const hits = Object.keys(map).filter(hit); - if (hits.length === 0) continue; - for (const k of hits) { - delete map[k]; - removed.push(k); - } - if (Object.keys(map).length === 0) delete data[key]; - else data[key] = map; - touched.add(key); - } - } - if (removed.length > 0) { - if (removed.includes(dir)) fs.rmSync(dir, { recursive: true, force: true }); - notes.push(`plugin removed (${removed.join(", ")})`); - } - - if (notes.length > 0) { - const cur = data.compaction as Record | undefined; - if (cur && cur.auto === false) { - const bak = `${file}.bili-bak`; - if (fs.existsSync(bak)) { - try { - const bakData = loadOpencodeConfig(bak).data; - if (bakData.compaction === undefined) delete data.compaction; - else data.compaction = bakData.compaction; - touched.add("compaction"); - notes.push("compaction restored from backup"); - } catch { - // unreadable backup — leave current settings untouched - } - } else if (Object.keys(cur).length === 1) { - // no pre-install config existed, so our {auto:false} is the entire - // key — dropping it restores the pre-install state exactly; with - // extra keys present we can't tell user edits apart, so leave them - delete data.compaction; - touched.add("compaction"); - notes.push("compaction removed (no prior config)"); - } - } - } - - writeOpencodeConfig(file, original, data, touched); - return notes.length > 0 ? `opencode: removed from ${file} (${notes.join("; ")})` : `opencode: not installed (${file})`; + const file = opencodeTargetFile(); + const { original, data } = loadOpencodeConfig(file); + const notes: string[] = []; + const touched = new Set(); + + const mcp = data.mcp; + if (isPlainMcpObject(mcp) && "bili" in mcp) { + delete mcp.bili; + if (Object.keys(mcp).length === 0) delete data.mcp; + touched.add("mcp"); + notes.push("mcp.bili removed"); + } + + // #927: clean our entry out of whichever key spelling carries it; the + // entry may be either form (#925) — bare npm name or shim dir. #1002: + // the key dies only when NOTHING raw survives — foreign object entries + // and map-form options are preserved verbatim, never collapsed. + const dir = opencodePluginDir(file); + const removed: string[] = []; + for (const key of PLUGIN_KEYS) { + const v = data[key]; + const hit = (x: string): boolean => x === OPENCODE_NPM_ENTRY || x === dir; + if (Array.isArray(v)) { + const survivors = v.filter((x) => !(typeof x === "string" && hit(x))); + if (survivors.length === v.length) continue; + for (const x of v) if (typeof x === "string" && hit(x)) removed.push(x); + if (survivors.length === 0) delete data[key]; + else data[key] = survivors; + touched.add(key); + } else if (v !== null && typeof v === "object") { + const map = v as Record; + const hits = Object.keys(map).filter(hit); + if (hits.length === 0) continue; + for (const k of hits) { + delete map[k]; + removed.push(k); + } + if (Object.keys(map).length === 0) delete data[key]; + else data[key] = map; + touched.add(key); + } + } + if (removed.length > 0) { + if (removed.includes(dir)) fs.rmSync(dir, { recursive: true, force: true }); + notes.push(`plugin removed (${removed.join(", ")})`); + } + + if (notes.length > 0) { + const cur = data.compaction as Record | undefined; + if (cur && cur.auto === false) { + const bak = `${file}.bili-bak`; + if (fs.existsSync(bak)) { + try { + const bakData = loadOpencodeConfig(bak).data; + if (bakData.compaction === undefined) delete data.compaction; + else data.compaction = bakData.compaction; + touched.add("compaction"); + notes.push("compaction restored from backup"); + } catch { + // unreadable backup — leave current settings untouched + } + } else if (Object.keys(cur).length === 1) { + // no pre-install config existed, so our {auto:false} is the entire + // key — dropping it restores the pre-install state exactly; with + // extra keys present we can't tell user edits apart, so leave them + delete data.compaction; + touched.add("compaction"); + notes.push("compaction removed (no prior config)"); + } + } + } + + writeOpencodeConfig(file, original, data, touched); + return notes.length > 0 + ? `opencode: removed from ${file} (${notes.join("; ")})` + : `opencode: not installed (${file})`; } function opencodeStatus(): string { - const file = opencodeTargetFile(); - const { data } = loadOpencodeConfig(file); - const mcp = data.mcp; - const dir = opencodePluginDir(file); - const listed = PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY || p === dir)); - return (isPlainMcpObject(mcp) && "bili" in mcp) || listed ? "installed" : "not installed"; + const file = opencodeTargetFile(); + const { data } = loadOpencodeConfig(file); + const mcp = data.mcp; + const dir = opencodePluginDir(file); + const listed = PLUGIN_KEYS.some((k) => + pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY || p === dir), + ); + return (isPlainMcpObject(mcp) && "bili" in mcp) || listed + ? "installed" + : "not installed"; } // — dsh ———————————————————————————————————————————————————————————————— @@ -1407,48 +2122,54 @@ function opencodeStatus(): string { // checkout/dev → absolute path (pnpm link:, tracks the live source). function dshInstall(): string { - const root = selfPackageRoot(); - requireDistFile(path.join(root, "dist", "agent", "dsh-native.js")); - const dirs = dshProfileDirs(); - const notes: string[] = []; - for (const dir of dirs) { - if (stripLegacyManagedBlock(dir)) notes.push(`${path.basename(dir)}: legacy managed block stripped`); - } - const spec = isNpmInstallForm(root) ? DSH_PACKAGE : path.resolve(root); - for (const dir of dirs) { - runDshPlugin(["plugin", "--profile", path.basename(dir), "add", spec]); - } - return `installed ${DSH_PACKAGE} into ${dirs.length} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} via 'dsh plugin --profile add ${spec}'${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — restart dsh to load it`; + const root = selfPackageRoot(); + requireDistFile(path.join(root, "dist", "agent", "dsh-native.js")); + const dirs = dshProfileDirs(); + const notes: string[] = []; + for (const dir of dirs) { + if (stripLegacyManagedBlock(dir)) + notes.push(`${path.basename(dir)}: legacy managed block stripped`); + } + const spec = isNpmInstallForm(root) ? DSH_PACKAGE : path.resolve(root); + for (const dir of dirs) { + runDshPlugin(["plugin", "--profile", path.basename(dir), "add", spec]); + } + return `installed ${DSH_PACKAGE} into ${dirs.length} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} via 'dsh plugin --profile add ${spec}'${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — restart dsh to load it`; } function dshRemove(): string { - const notes: string[] = []; - const touched = new Set(); - for (const dir of dshProfileDirs()) { - const name = path.basename(dir); - if (dshProfileDependsOnBili(dir)) { - runDshPlugin(["plugin", "--profile", name, "remove", DSH_PACKAGE]); - touched.add(name); - notes.push(`${name}: uninstalled via the dsh plugin channel`); - } - if (stripLegacyManagedBlock(dir)) { - touched.add(name); - notes.push(`${name}: legacy managed block stripped`); - } - } - if (touched.size === 0) return "nothing to remove — no dsh profile carries billion-context"; - return `removed bili from ${touched.size} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} (${notes.join("; ")}) — restart dsh to finish`; + const notes: string[] = []; + const touched = new Set(); + for (const dir of dshProfileDirs()) { + const name = path.basename(dir); + if (dshProfileDependsOnBili(dir)) { + runDshPlugin(["plugin", "--profile", name, "remove", DSH_PACKAGE]); + touched.add(name); + notes.push(`${name}: uninstalled via the dsh plugin channel`); + } + if (stripLegacyManagedBlock(dir)) { + touched.add(name); + notes.push(`${name}: legacy managed block stripped`); + } + } + if (touched.size === 0) + return "nothing to remove — no dsh profile carries billion-context"; + return `removed bili from ${touched.size} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} (${notes.join("; ")}) — restart dsh to finish`; } function dshStatus(): string { - const dirs = dshProfileDirs(); - const bundle = dirs.filter((dir) => dshBundleInstalled(dir)); - const withBlock = dirs.filter((dir) => dshHasLegacyManagedBlock(dir)); - if (bundle.length === dirs.length && dirs.length > 0) return `installed (dsh bundle in all ${dirs.length} profiles)`; - if (bundle.length > 0) return `installed as a dsh bundle in ${bundle.length}/${dirs.length} profiles`; - if (withBlock.length === dirs.length && dirs.length > 0) return "installed (legacy managed block — rerun 'bili plugin install dsh' to migrate to the dsh bundle channel)"; - if (withBlock.length > 0) return `legacy managed block in ${withBlock.length}/${dirs.length} profiles — rerun 'bili plugin install dsh' to migrate`; - return "not installed"; + const dirs = dshProfileDirs(); + const bundle = dirs.filter((dir) => dshBundleInstalled(dir)); + const withBlock = dirs.filter((dir) => dshHasLegacyManagedBlock(dir)); + if (bundle.length === dirs.length && dirs.length > 0) + return `installed (dsh bundle in all ${dirs.length} profiles)`; + if (bundle.length > 0) + return `installed as a dsh bundle in ${bundle.length}/${dirs.length} profiles`; + if (withBlock.length === dirs.length && dirs.length > 0) + return "installed (legacy managed block — rerun 'bili plugin install dsh' to migrate to the dsh bundle channel)"; + if (withBlock.length > 0) + return `legacy managed block in ${withBlock.length}/${dirs.length} profiles — rerun 'bili plugin install dsh' to migrate`; + return "not installed"; } /** True when any profile carries the persistent native install — either the @@ -1457,14 +2178,18 @@ function dshStatus(): string { * rejects duplicate loader entry ids across layers, so a second * `id: bili-native` insert would hard-fail dsh boot whenever the persistent * install is present. */ -export function dshNativeInstalled(env: NodeJS.ProcessEnv = process.env): boolean { - let dirs: string[]; - try { - dirs = dshProfileDirs(env); - } catch { - return false; - } - return dirs.some((dir) => dshBundleInstalled(dir) || dshHasLegacyManagedBlock(dir)); +export function dshNativeInstalled( + env: NodeJS.ProcessEnv = process.env, +): boolean { + let dirs: string[]; + try { + dirs = dshProfileDirs(env); + } catch { + return false; + } + return dirs.some( + (dir) => dshBundleInstalled(dir) || dshHasLegacyManagedBlock(dir), + ); } // — kimi ———————————————————————————————————————————————————————————————— @@ -1480,47 +2205,65 @@ export function dshNativeInstalled(env: NodeJS.ProcessEnv = process.env): boolea const KIMI_PLUGIN_ID = "billion-context"; function kimiHome(): string { - return resolveKimiHome(process.env); + return resolveKimiHome(process.env); } function kimiManagedDir(): string { - return path.join(kimiHome(), "plugins", "managed", KIMI_PLUGIN_ID); + return path.join(kimiHome(), "plugins", "managed", KIMI_PLUGIN_ID); } function kimiRegistryFile(): string { - return path.join(kimiHome(), "plugins", "installed.json"); + return path.join(kimiHome(), "plugins", "installed.json"); } interface KimiInstalledRecord { - id: string; - root: string; - source: "local-path"; - enabled: boolean; - installedAt: string; - updatedAt?: string; + id: string; + root: string; + source: "local-path"; + enabled: boolean; + installedAt: string; + updatedAt?: string; } /** installed.json is machine-managed (kimi's own store writes it too) but is * not user-authored prose — a corrupt registry is surfaced loudly instead of * being silently re-created (§7.3). */ -function readKimiInstalledRegistry(file: string): { version: number; plugins: KimiInstalledRecord[] } { - let text: string; - try { - text = fs.readFileSync(file, "utf8"); - } catch (err) { - if ((err as { code?: string }).code === "ENOENT") return { version: 1, plugins: [] }; - throw err; - } - const parsed = JSON.parse(text) as { version?: unknown; plugins?: unknown }; - if (!Array.isArray(parsed.plugins)) throw new Error(`${file} is corrupt (no plugins array) — fix or remove it, then retry`); - return { version: typeof parsed.version === "number" ? parsed.version : 1, plugins: parsed.plugins as KimiInstalledRecord[] }; +function readKimiInstalledRegistry(file: string): { + version: number; + plugins: KimiInstalledRecord[]; +} { + let text: string; + try { + text = fs.readFileSync(file, "utf8"); + } catch (err) { + if ((err as { code?: string }).code === "ENOENT") + return { version: 1, plugins: [] }; + throw err; + } + let parsed: { version?: unknown; plugins?: unknown }; + try { + parsed = JSON.parse(text) as { version?: unknown; plugins?: unknown }; + } catch (err) { + throw new Error( + `${file} is corrupt (invalid JSON) — fix or remove it, then retry`, + { cause: err }, + ); + } + if (!Array.isArray(parsed.plugins)) + throw new Error( + `${file} is corrupt (no plugins array) — fix or remove it, then retry`, + ); + return { + version: typeof parsed.version === "number" ? parsed.version : 1, + plugins: parsed.plugins as KimiInstalledRecord[], + }; } function writeJsonAtomic(file: string, data: unknown): void { - fs.mkdirSync(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; - fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`); - fs.renameSync(tmp, file); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}`; + fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`); + fs.renameSync(tmp, file); } /** Kimi Code v2 floor: the plugin system (managed plugins + hooks + stdio MCP @@ -1528,91 +2271,158 @@ function writeJsonAtomic(file: string, data: unknown): void { * an old one throws with launcher-mode guidance rather than writing a dead * manifest. */ function detectKimiVersion(env: NodeJS.ProcessEnv = process.env): string { - const candidates: Array<{ cmd: string; viaShell: boolean }> = process.platform === "win32" - ? [{ cmd: "kimi --version", viaShell: true }] - : [{ cmd: "kimi", viaShell: false }, { cmd: path.join(resolveKimiHome(env), "bin", "kimi"), viaShell: false }]; - let out: string | undefined; - for (const c of candidates) { - try { - out = c.viaShell - ? execFileSync(c.cmd, { shell: true, timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }) - : execFileSync(c.cmd, ["--version"], { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }); - break; - } catch {} - } - if (out === undefined) throw new Error("kimi CLI not found on PATH or in $KIMI_CODE_HOME/bin — install Kimi Code first (`npm i -g @moonshot-ai/kimi-code`)"); - const m = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(out); - if (m && parseInt(m[1], 10) < 2) { - throw new Error(`Kimi Code ${m[0]} is too old for native mode (needs >= 2.0.0) — upgrade with \`npm i -g @moonshot-ai/kimi-code@latest\` and retry; \`bili kimi\` launcher mode still works`); - } - return m ? m[0] : out.trim(); + const candidates: Array<{ cmd: string; viaShell: boolean }> = + process.platform === "win32" + ? [{ cmd: "kimi --version", viaShell: true }] + : [ + { cmd: "kimi", viaShell: false }, + { + cmd: path.join(resolveKimiHome(env), "bin", "kimi"), + viaShell: false, + }, + ]; + let out: string | undefined; + for (const c of candidates) { + try { + out = c.viaShell + ? execFileSync(c.cmd, { + shell: true, + timeout: 5000, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }) + : execFileSync(c.cmd, ["--version"], { + timeout: 5000, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }); + break; + } catch {} + } + if (out === undefined) + throw new Error( + "kimi CLI not found on PATH or in $KIMI_CODE_HOME/bin — install Kimi Code first (`npm i -g @moonshot-ai/kimi-code`)", + ); + const m = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(out); + if (m && parseInt(m[1], 10) < 2) { + throw new Error( + `Kimi Code ${m[0]} is too old for native mode (needs >= 2.0.0) — upgrade with \`npm i -g @moonshot-ai/kimi-code@latest\` and retry; \`bili kimi\` launcher mode still works`, + ); + } + return m ? m[0] : out.trim(); } function selfVersion(): string { - try { - return (JSON.parse(fs.readFileSync(path.join(selfPackageRoot(), "package.json"), "utf8")) as { version?: string }).version ?? "0.0.0"; - } catch { - return "0.0.0"; - } + try { + return ( + ( + JSON.parse( + fs.readFileSync(path.join(selfPackageRoot(), "package.json"), "utf8"), + ) as { version?: string } + ).version ?? "0.0.0" + ); + } catch { + return "0.0.0"; + } } function kimiPluginManifest(root: string): Record { - return { - name: KIMI_PLUGIN_ID, - version: selfVersion(), - description: "billion-context: ACP context-compression proxy (native mode)", - mcpServers: { bili: { command: "node", args: [path.join(root, "dist", "kimi", "native-mcp.js")], cwd: "./" } }, - hooks: [{ event: "SessionStart", command: portableHookCommand("node", [path.join(root, "dist", "kimi", "bootstrap-hook.js")]), timeout: 30 }], - }; + return { + name: KIMI_PLUGIN_ID, + version: selfVersion(), + description: "billion-context: ACP context-compression proxy (native mode)", + mcpServers: { + bili: { + command: "node", + args: [path.join(root, "dist", "kimi", "native-mcp.js")], + cwd: "./", + }, + }, + hooks: [ + { + event: "SessionStart", + command: portableHookCommand("node", [ + path.join(root, "dist", "kimi", "bootstrap-hook.js"), + ]), + timeout: 30, + }, + ], + }; } function kimiInstall(): string { - const root = selfPackageRoot(); - requireDistFile(path.join(root, "dist", "kimi", "native-mcp.js")); - requireDistFile(path.join(root, "dist", "kimi", "bootstrap-hook.js")); - const version = detectKimiVersion(); - const dir = kimiManagedDir(); - fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync(path.join(dir, "kimi.plugin.json"), `${JSON.stringify(kimiPluginManifest(root), null, 2)}\n`); - const file = kimiRegistryFile(); - backupBeforeWrite(file); - const reg = readKimiInstalledRegistry(file); - const now = new Date().toISOString(); - const existing = reg.plugins.find((p) => p.id === KIMI_PLUGIN_ID); - const record: KimiInstalledRecord = { id: KIMI_PLUGIN_ID, root: dir, source: "local-path", enabled: true, installedAt: existing?.installedAt ?? now, updatedAt: now }; - reg.plugins = existing ? reg.plugins.map((p) => (p.id === KIMI_PLUGIN_ID ? record : p)) : [...reg.plugins, record]; - writeJsonAtomic(file, reg); - return `wrote the billion-context plugin into ${dir} (kimi ${version}) — start a new Kimi Code session to activate`; + const root = selfPackageRoot(); + requireDistFile(path.join(root, "dist", "kimi", "native-mcp.js")); + requireDistFile(path.join(root, "dist", "kimi", "bootstrap-hook.js")); + const version = detectKimiVersion(); + const dir = kimiManagedDir(); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, "kimi.plugin.json"), + `${JSON.stringify(kimiPluginManifest(root), null, 2)}\n`, + ); + const file = kimiRegistryFile(); + backupBeforeWrite(file); + const reg = readKimiInstalledRegistry(file); + const now = new Date().toISOString(); + const existing = reg.plugins.find((p) => p.id === KIMI_PLUGIN_ID); + const record: KimiInstalledRecord = { + id: KIMI_PLUGIN_ID, + root: dir, + source: "local-path", + enabled: true, + installedAt: existing?.installedAt ?? now, + updatedAt: now, + }; + reg.plugins = existing + ? reg.plugins.map((p) => (p.id === KIMI_PLUGIN_ID ? record : p)) + : [...reg.plugins, record]; + writeJsonAtomic(file, reg); + return `wrote the billion-context plugin into ${dir} (kimi ${version}) — start a new Kimi Code session to activate`; } function kimiRemove(): string { - const notes: string[] = []; - let removed = false; - const dir = kimiManagedDir(); - if (fs.existsSync(dir)) { - fs.rmSync(dir, { recursive: true, force: true }); - removed = true; - } - try { - const reg = readKimiInstalledRegistry(kimiRegistryFile()); - const rest = reg.plugins.filter((p) => p.id !== KIMI_PLUGIN_ID); - if (rest.length !== reg.plugins.length) writeJsonAtomic(kimiRegistryFile(), { version: reg.version, plugins: rest }); - } catch {} - const restored = restoreKimiBackup({ log: (msg) => notes.push(msg) }); - if (restored.restored) notes.push("restored config.toml from the pre-install snapshot"); - else unrouteKimi({ log: (msg) => notes.push(msg) }); - return removed ? `removed the billion-context plugin${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new Kimi Code session to finish` : "not installed"; + const notes: string[] = []; + let removed = false; + const dir = kimiManagedDir(); + if (fs.existsSync(dir)) { + fs.rmSync(dir, { recursive: true, force: true }); + removed = true; + } + try { + const reg = readKimiInstalledRegistry(kimiRegistryFile()); + const rest = reg.plugins.filter((p) => p.id !== KIMI_PLUGIN_ID); + if (rest.length !== reg.plugins.length) + writeJsonAtomic(kimiRegistryFile(), { + version: reg.version, + plugins: rest, + }); + } catch {} + const restored = restoreKimiBackup({ log: (msg) => notes.push(msg) }); + if (restored.restored) + notes.push("restored config.toml from the pre-install snapshot"); + else unrouteKimi({ log: (msg) => notes.push(msg) }); + return removed + ? `removed the billion-context plugin${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new Kimi Code session to finish` + : "not installed"; } function kimiStatus(): string { - const manifestOk = fs.existsSync(path.join(kimiManagedDir(), "kimi.plugin.json")); - let registered = false; - try { - registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some((p) => p.id === KIMI_PLUGIN_ID); - } catch {} - if (manifestOk && registered) return "installed"; - if (manifestOk || registered) return "partially installed — rerun 'bili plugin install kimi' to fix"; - return "not installed"; + const manifestOk = fs.existsSync( + path.join(kimiManagedDir(), "kimi.plugin.json"), + ); + let registered = false; + try { + registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some( + (p) => p.id === KIMI_PLUGIN_ID, + ); + } catch {} + if (manifestOk && registered) return "installed"; + if (manifestOk || registered) + return "partially installed — rerun 'bili plugin install kimi' to fix"; + return "not installed"; } // — hermes (#958) —————————————————————————————————————————————————————————————— @@ -1625,77 +2435,114 @@ function kimiStatus(): string { const HERMES_PLUGIN_ID = "billion-context"; // cmd.exe's canonical "command missing" line (its exit code is not reliably // 9009 when spawned via CreateProcess — CI-verified). -const CMD_NOT_FOUND_RE = /is not recognized as an internal or external command/i; +const CMD_NOT_FOUND_RE = + /is not recognized as an internal or external command/i; function hermesPluginDir(): string { - return path.join(resolveHermesHome(process.env), "plugins", HERMES_PLUGIN_ID); + return path.join(resolveHermesHome(process.env), "plugins", HERMES_PLUGIN_ID); } interface HermesSidecar { - proxyScript: string; - nodePath: string; -} - -function runHermesCli(args: string[]): { ok: true } | { ok: false; reason: string } { - try { - // #679 spawn rules: on Windows a bare `hermes` name or a .cmd shim needs the - // comspec wrap — a plain execFileSync("hermes") ENOENTs there. planDshSpawn - // is the generic host-CLI planner (dsh-named for historical reasons). - const plan = planDshSpawn("hermes", args); - const res = spawnSync(plan.command, plan.args, { - timeout: 15_000, - encoding: "utf8", - stdio: ["ignore", "pipe", "pipe"], - windowsVerbatimArguments: plan.windowsVerbatimArguments, - windowsHide: true, - }); - if (res.error) return { ok: false, reason: (res.error as NodeJS.ErrnoException).code === "ENOENT" ? "not-found" : String(res.error) }; - if (res.status === 0) return { ok: true }; - if (process.platform === "win32" && (res.status === 9009 || CMD_NOT_FOUND_RE.test(res.stderr ?? ""))) return { ok: false, reason: "not-found" }; - const detail = (res.stderr ?? "").trim(); - return { ok: false, reason: detail || `exit ${res.status}` }; - } catch (err) { - return { ok: false, reason: err instanceof Error ? err.message : String(err) }; - } + proxyScript: string; + nodePath: string; +} + +function runHermesCli( + args: string[], +): { ok: true } | { ok: false; reason: string } { + try { + // #679 spawn rules: on Windows a bare `hermes` name or a .cmd shim needs the + // comspec wrap — a plain execFileSync("hermes") ENOENTs there. planDshSpawn + // is the generic host-CLI planner (dsh-named for historical reasons). + const plan = planDshSpawn("hermes", args); + const res = spawnSync(plan.command, plan.args, { + timeout: 15_000, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + windowsVerbatimArguments: plan.windowsVerbatimArguments, + windowsHide: true, + }); + if (res.error) + return { + ok: false, + reason: + (res.error as NodeJS.ErrnoException).code === "ENOENT" + ? "not-found" + : String(res.error), + }; + if (res.status === 0) return { ok: true }; + if ( + process.platform === "win32" && + (res.status === 9009 || CMD_NOT_FOUND_RE.test(res.stderr ?? "")) + ) + return { ok: false, reason: "not-found" }; + const detail = (res.stderr ?? "").trim(); + return { ok: false, reason: detail || `exit ${res.status}` }; + } catch (err) { + return { + ok: false, + reason: err instanceof Error ? err.message : String(err), + }; + } } function hermesInstallCore(): void { - const root = selfPackageRoot(); - const initSrc = fs.readFileSync(path.join(root, "hermes-plugin", "__init__.py"), "utf8"); - const yamlSrc = fs.readFileSync(path.join(root, "hermes-plugin", "plugin.yaml"), "utf8"); - requireDistFile(path.join(root, "dist", "index.js")); - const dir = hermesPluginDir(); - fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync(path.join(dir, "__init__.py"), initSrc); - fs.writeFileSync(path.join(dir, "plugin.yaml"), yamlSrc.replace(/^version:.*/m, `version: "${selfVersion()}"`)); - const sidecar: HermesSidecar = { proxyScript: path.join(root, "dist", "index.js"), nodePath: process.execPath }; - fs.writeFileSync(path.join(dir, "bili.json"), `${JSON.stringify(sidecar, null, 2)}\n`); + const root = selfPackageRoot(); + const initSrc = fs.readFileSync( + path.join(root, "hermes-plugin", "__init__.py"), + "utf8", + ); + const yamlSrc = fs.readFileSync( + path.join(root, "hermes-plugin", "plugin.yaml"), + "utf8", + ); + requireDistFile(path.join(root, "dist", "index.js")); + const dir = hermesPluginDir(); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, "__init__.py"), initSrc); + fs.writeFileSync( + path.join(dir, "plugin.yaml"), + yamlSrc.replace(/^version:.*/m, `version: "${selfVersion()}"`), + ); + const sidecar: HermesSidecar = { + proxyScript: path.join(root, "dist", "index.js"), + nodePath: process.execPath, + }; + fs.writeFileSync( + path.join(dir, "bili.json"), + `${JSON.stringify(sidecar, null, 2)}\n`, + ); } function hermesInstall(): string { - hermesInstallCore(); - const dir = hermesPluginDir(); - const enable = runHermesCli(["plugins", "enable", HERMES_PLUGIN_ID]); - if (enable.ok) return `wrote the billion-context plugin into ${dir} and enabled it — start a new hermes session to activate`; - const hint = enable.reason === "not-found" - ? "the hermes CLI was not found on PATH — enable it manually: hermes plugins enable billion-context" - : `enabling via the hermes CLI failed (${enable.reason}) — enable it manually: hermes plugins enable billion-context`; - return `wrote the billion-context plugin into ${dir}; ${hint}`; + hermesInstallCore(); + const dir = hermesPluginDir(); + const enable = runHermesCli(["plugins", "enable", HERMES_PLUGIN_ID]); + if (enable.ok) + return `wrote the billion-context plugin into ${dir} and enabled it — start a new hermes session to activate`; + const hint = + enable.reason === "not-found" + ? "the hermes CLI was not found on PATH — enable it manually: hermes plugins enable billion-context" + : `enabling via the hermes CLI failed (${enable.reason}) — enable it manually: hermes plugins enable billion-context`; + return `wrote the billion-context plugin into ${dir}; ${hint}`; } function hermesRemove(): string { - const dir = hermesPluginDir(); - if (!fs.existsSync(dir)) return "not installed"; - fs.rmSync(dir, { recursive: true, force: true }); - const disable = runHermesCli(["plugins", "disable", HERMES_PLUGIN_ID]); - return disable.ok - ? `removed the billion-context plugin (${dir}) and disabled it — start a new hermes session to finish` - : `removed the billion-context plugin (${dir}); if hermes still lists it, disable it manually: hermes plugins disable billion-context`; + const dir = hermesPluginDir(); + if (!fs.existsSync(dir)) return "not installed"; + fs.rmSync(dir, { recursive: true, force: true }); + const disable = runHermesCli(["plugins", "disable", HERMES_PLUGIN_ID]); + return disable.ok + ? `removed the billion-context plugin (${dir}) and disabled it — start a new hermes session to finish` + : `removed the billion-context plugin (${dir}); if hermes still lists it, disable it manually: hermes plugins disable billion-context`; } function hermesStatus(): string { - const dir = hermesPluginDir(); - return fs.existsSync(path.join(dir, "__init__.py")) && fs.existsSync(path.join(dir, "bili.json")) ? "installed" : "not installed"; + const dir = hermesPluginDir(); + return fs.existsSync(path.join(dir, "__init__.py")) && + fs.existsSync(path.join(dir, "bili.json")) + ? "installed" + : "not installed"; } // — dispatch ———————————————————————————————————————————————————————————— @@ -1709,144 +2556,191 @@ const ZCODE_HOOK_ENTRY_RE = /(?:^|[\\/])zcode[\\/]bootstrap-hook\.(?:js|ts)$/; const ZCODE_MCP_ENTRY_RE = /(?:^|[\\/])zcode[\\/]mcp-entry\.(?:js|ts)$/; function zcodeUserConfigFile(): string { - return path.join(os.homedir(), ".zcode", "cli", "config.json"); + return path.join(os.homedir(), ".zcode", "cli", "config.json"); } function zcodeAsPlain(value: unknown): Record | undefined { - return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record) : undefined; + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; } function zcodeArgsMatch(args: unknown, re: RegExp): boolean { - return Array.isArray(args) && args.some((a) => typeof a === "string" && re.test(a)); + return ( + Array.isArray(args) && args.some((a) => typeof a === "string" && re.test(a)) + ); } function isOursZcodeHookEntry(entry: unknown): boolean { - const hooks = zcodeAsPlain(entry)?.hooks; - if (!Array.isArray(hooks)) return false; - return hooks.some((h) => zcodeArgsMatch(zcodeAsPlain(h)?.args, ZCODE_HOOK_ENTRY_RE)); + const hooks = zcodeAsPlain(entry)?.hooks; + if (!Array.isArray(hooks)) return false; + return hooks.some((h) => + zcodeArgsMatch(zcodeAsPlain(h)?.args, ZCODE_HOOK_ENTRY_RE), + ); } function isOursZcodeMcpServer(server: unknown): boolean { - const s = zcodeAsPlain(server); - return !!s && s.type === "stdio" && zcodeArgsMatch(s.args, ZCODE_MCP_ENTRY_RE); + const s = zcodeAsPlain(server); + return ( + !!s && s.type === "stdio" && zcodeArgsMatch(s.args, ZCODE_MCP_ENTRY_RE) + ); } /** Managed-block apply for ~/.zcode/cli/config.json (#1145). Pure over the * parsed doc: enables hooks, upserts our SessionStart entry, and owns ONLY * mcp.servers.bili when it already points at our dist — a user's own "bili" * server throws instead of being clobbered (§7.3). */ -function applyZcodeManagedConfig(doc: Record, opts: { hookEntry: string; mcpEntry: string }): { data: Record; notes: string[] } { - const data = structuredClone(doc); - const notes: string[] = []; - const hooks = zcodeAsPlain(data.hooks) ?? {}; - if (hooks.enabled !== true) { - hooks.enabled = true; - notes.push("enabled hooks (hooks.enabled was off)"); - } - const events = zcodeAsPlain(hooks.events) ?? {}; - const sessionStart = Array.isArray(events.SessionStart) ? [...(events.SessionStart as unknown[])] : []; - const kept = sessionStart.filter((e) => !isOursZcodeHookEntry(e)); - if (kept.length !== sessionStart.length) notes.push("replaced a previous bili SessionStart entry"); - kept.push({ hooks: [{ type: "process", command: "node", args: [opts.hookEntry] }] }); - events.SessionStart = kept; - hooks.events = events; - data.hooks = hooks; - const mcp = zcodeAsPlain(data.mcp) ?? {}; - const servers = zcodeAsPlain(mcp.servers) ?? {}; - if (servers.bili !== undefined && !isOursZcodeMcpServer(servers.bili)) { - throw new Error(`${zcodeUserConfigFile()} already defines mcp.servers.bili owned by something else — rename or remove it first; refusing to overwrite`); - } - servers.bili = { type: "stdio", command: "node", args: [opts.mcpEntry] }; - mcp.servers = servers; - data.mcp = mcp; - return { data, notes }; -} - -function stripZcodeManagedConfig(doc: Record): { data: Record; removed: string[] } { - const data = structuredClone(doc); - const removed: string[] = []; - const hooks = zcodeAsPlain(data.hooks); - if (hooks) { - const events = zcodeAsPlain(hooks.events); - if (events && Array.isArray(events.SessionStart)) { - const kept = (events.SessionStart as unknown[]).filter((e) => !isOursZcodeHookEntry(e)); - if (kept.length !== (events.SessionStart as unknown[]).length) { - removed.push("hooks.events.SessionStart entry"); - if (kept.length > 0) events.SessionStart = kept; - else delete events.SessionStart; - if (Object.keys(events).length === 0) delete hooks.events; - if (Object.keys(hooks).length === 0) delete data.hooks; - } - } - } - const mcp = zcodeAsPlain(data.mcp); - if (mcp) { - const servers = zcodeAsPlain(mcp.servers); - if (servers && servers.bili !== undefined && isOursZcodeMcpServer(servers.bili)) { - removed.push("mcp.servers.bili"); - delete servers.bili; - if (Object.keys(servers).length === 0) delete mcp.servers; - if (Object.keys(mcp).length === 0) delete data.mcp; - } - } - return { data, removed }; +function applyZcodeManagedConfig( + doc: Record, + opts: { hookEntry: string; mcpEntry: string }, +): { data: Record; notes: string[] } { + const data = structuredClone(doc); + const notes: string[] = []; + const hooks = zcodeAsPlain(data.hooks) ?? {}; + if (hooks.enabled !== true) { + hooks.enabled = true; + notes.push("enabled hooks (hooks.enabled was off)"); + } + const events = zcodeAsPlain(hooks.events) ?? {}; + const sessionStart = Array.isArray(events.SessionStart) + ? [...(events.SessionStart as unknown[])] + : []; + const kept = sessionStart.filter((e) => !isOursZcodeHookEntry(e)); + if (kept.length !== sessionStart.length) + notes.push("replaced a previous bili SessionStart entry"); + kept.push({ + hooks: [{ type: "process", command: "node", args: [opts.hookEntry] }], + }); + events.SessionStart = kept; + hooks.events = events; + data.hooks = hooks; + const mcp = zcodeAsPlain(data.mcp) ?? {}; + const servers = zcodeAsPlain(mcp.servers) ?? {}; + if (servers.bili !== undefined && !isOursZcodeMcpServer(servers.bili)) { + throw new Error( + `${zcodeUserConfigFile()} already defines mcp.servers.bili owned by something else — rename or remove it first; refusing to overwrite`, + ); + } + servers.bili = { type: "stdio", command: "node", args: [opts.mcpEntry] }; + mcp.servers = servers; + data.mcp = mcp; + return { data, notes }; +} + +function stripZcodeManagedConfig(doc: Record): { + data: Record; + removed: string[]; +} { + const data = structuredClone(doc); + const removed: string[] = []; + const hooks = zcodeAsPlain(data.hooks); + if (hooks) { + const events = zcodeAsPlain(hooks.events); + if (events && Array.isArray(events.SessionStart)) { + const kept = (events.SessionStart as unknown[]).filter( + (e) => !isOursZcodeHookEntry(e), + ); + if (kept.length !== (events.SessionStart as unknown[]).length) { + removed.push("hooks.events.SessionStart entry"); + if (kept.length > 0) events.SessionStart = kept; + else delete events.SessionStart; + if (Object.keys(events).length === 0) delete hooks.events; + if (Object.keys(hooks).length === 0) delete data.hooks; + } + } + } + const mcp = zcodeAsPlain(data.mcp); + if (mcp) { + const servers = zcodeAsPlain(mcp.servers); + if ( + servers && + servers.bili !== undefined && + isOursZcodeMcpServer(servers.bili) + ) { + removed.push("mcp.servers.bili"); + delete servers.bili; + if (Object.keys(servers).length === 0) delete mcp.servers; + if (Object.keys(mcp).length === 0) delete data.mcp; + } + } + return { data, removed }; } function zcodeInstall(): string { - const root = selfPackageRoot(); - const hookEntry = path.join(root, "dist", "zcode", "bootstrap-hook.js"); - const mcpEntry = path.join(root, "dist", "zcode", "mcp-entry.js"); - requireDistFile(hookEntry); - requireDistFile(mcpEntry); - const file = zcodeUserConfigFile(); - const { data, notes } = applyZcodeManagedConfig(readJson(file), { hookEntry, mcpEntry }); - writeJson(file, data); - return `wrote the billion-context hook+MCP into ${file}${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new ZCode session to activate`; + const root = selfPackageRoot(); + const hookEntry = path.join(root, "dist", "zcode", "bootstrap-hook.js"); + const mcpEntry = path.join(root, "dist", "zcode", "mcp-entry.js"); + requireDistFile(hookEntry); + requireDistFile(mcpEntry); + const file = zcodeUserConfigFile(); + const { data, notes } = applyZcodeManagedConfig(readJson(file), { + hookEntry, + mcpEntry, + }); + writeJson(file, data); + return `wrote the billion-context hook+MCP into ${file}${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new ZCode session to activate`; } function zcodeRemove(): string { - const file = zcodeUserConfigFile(); - const notes: string[] = []; - try { - const doc = readJson(file); - const { data, removed } = stripZcodeManagedConfig(doc); - if (removed.length > 0) { - // Revert hooks.enabled only when the pre-install snapshot shows we - // are the reason it is on (never drop a user-owned switch). - let bak: Record | undefined; - try { - bak = JSON.parse(fs.readFileSync(`${file}.bili-bak`, "utf8")) as Record; - } catch {} - const hooks = zcodeAsPlain(data.hooks); - if (hooks && Object.keys(hooks).length === 1 && hooks.enabled === true) { - const bakEnabled = zcodeAsPlain(bak?.hooks)?.enabled === true; - if (!bakEnabled) delete hooks.enabled; - if (Object.keys(hooks).length === 0) delete data.hooks; - } - writeJson(file, data); - } - for (const r of removed) notes.push(`removed ${r}`); - } catch {} - const restored = restoreZcodeBackup({ log: (msg) => notes.push(msg) }); - if (!restored.restored) unrouteZcode({ log: () => {} }); - return notes.length > 0 ? `removed the billion-context zcode lane (${notes.join("; ")}) — start a new ZCode session to finish` : "not installed"; + const file = zcodeUserConfigFile(); + const notes: string[] = []; + try { + const doc = readJson(file); + const { data, removed } = stripZcodeManagedConfig(doc); + if (removed.length > 0) { + // Revert hooks.enabled only when the pre-install snapshot shows we + // are the reason it is on (never drop a user-owned switch). + let bak: Record | undefined; + try { + bak = JSON.parse(fs.readFileSync(`${file}.bili-bak`, "utf8")) as Record< + string, + unknown + >; + } catch {} + const hooks = zcodeAsPlain(data.hooks); + if (hooks && Object.keys(hooks).length === 1 && hooks.enabled === true) { + const bakEnabled = zcodeAsPlain(bak?.hooks)?.enabled === true; + if (!bakEnabled) delete hooks.enabled; + if (Object.keys(hooks).length === 0) delete data.hooks; + } + writeJson(file, data); + } + for (const r of removed) notes.push(`removed ${r}`); + } catch {} + const restored = restoreZcodeBackup({ log: (msg) => notes.push(msg) }); + if (!restored.restored) unrouteZcode({ log: () => {} }); + return notes.length > 0 + ? `removed the billion-context zcode lane (${notes.join("; ")}) — start a new ZCode session to finish` + : "not installed"; } function zcodeStatus(): string { - let hasHook = false; - let hasMcp = false; - try { - const doc = readJson(zcodeUserConfigFile()); - const sessionStart = zcodeAsPlain(zcodeAsPlain(doc.hooks)?.events)?.SessionStart; - hasHook = Array.isArray(sessionStart) && (sessionStart as unknown[]).some(isOursZcodeHookEntry); - hasMcp = isOursZcodeMcpServer(zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili); - } catch {} - let status = hasHook && hasMcp ? "installed" : hasHook || hasMcp ? "partially installed — rerun 'bili plugin install zcode' to fix" : "not installed"; - try { - const routed = inspectZcodeRouting(resolveZcodeDataDir(process.env)); - if (routed && routed.wrapped.length > 0) status += ` (routing ${routed.kind} store: ${routed.wrapped.map((w) => w.id).join(", ")})`; - } catch {} - return status; + let hasHook = false; + let hasMcp = false; + try { + const doc = readJson(zcodeUserConfigFile()); + const sessionStart = zcodeAsPlain( + zcodeAsPlain(doc.hooks)?.events, + )?.SessionStart; + hasHook = + Array.isArray(sessionStart) && + (sessionStart as unknown[]).some(isOursZcodeHookEntry); + hasMcp = isOursZcodeMcpServer( + zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili, + ); + } catch {} + let status = + hasHook && hasMcp + ? "installed" + : hasHook || hasMcp + ? "partially installed — rerun 'bili plugin install zcode' to fix" + : "not installed"; + try { + const routed = inspectZcodeRouting(resolveZcodeDataDir(process.env)); + if (routed && routed.wrapped.length > 0) + status += ` (routing ${routed.kind} store: ${routed.wrapped.map((w) => w.id).join(", ")})`; + } catch {} + return status; } // — doctor (#1235) ————————————————————————————————————————————————————— @@ -1857,30 +2751,40 @@ function zcodeStatus(): string { * malformed config; single-source probes (pi/opencode/zcode) propagate the * parse error so doctor reports a broken probe instead of a false "absent". */ interface LanePresence { - installed: boolean; - pointers: string[]; - targets: string[]; - form: "npm" | "local-path" | "managed-block" | "none"; - copyVersion?: string; - profiles?: Array<{ name: string; spec?: string; pinned: boolean; bundleInstalled: boolean; copyVersion?: string }>; + installed: boolean; + pointers: string[]; + targets: string[]; + form: "npm" | "local-path" | "managed-block" | "none"; + copyVersion?: string; + profiles?: Array<{ + name: string; + spec?: string; + pinned: boolean; + bundleInstalled: boolean; + copyVersion?: string; + }>; } function laneAbsent(): LanePresence { - return { installed: false, pointers: [], targets: [], form: "none" }; + return { installed: false, pointers: [], targets: [], form: "none" }; } function pkgVersionAt(rootDir: string): string | undefined { - try { - const v = (JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8")) as { version?: unknown }).version; - return typeof v === "string" ? v : undefined; - } catch { - return undefined; - } + try { + const v = ( + JSON.parse( + fs.readFileSync(path.join(rootDir, "package.json"), "utf8"), + ) as { version?: unknown } + ).version; + return typeof v === "string" ? v : undefined; + } catch { + return undefined; + } } /** Package root three levels above a /dist//.js entry. */ function rootFromDistFile(file: string): string { - return path.dirname(path.dirname(path.dirname(file))); + return path.dirname(path.dirname(path.dirname(file))); } // #2260(F): cache spec slots are `billion-context@`; for registry @@ -1889,30 +2793,30 @@ function rootFromDistFile(file: string): string { // segment; anything non-numeric ("latest", file: specs) falls back to plain // string order — same relative position as before. function compareSpecSlots(a: string, b: string): number { - const SPEC_PREFIX = "billion-context@"; - const av = a.startsWith(SPEC_PREFIX) ? a.slice(SPEC_PREFIX.length) : a; - const bv = b.startsWith(SPEC_PREFIX) ? b.slice(SPEC_PREFIX.length) : b; - const segments = (s: string): number[] | null => { - const parts = s.split("."); - if (parts.length === 0) return null; - const out: number[] = []; - for (const p of parts) { - if (!/^\d+$/.test(p)) return null; - out.push(Number(p)); - } - return out; - }; - const an = segments(av); - const bn = segments(bv); - if (an !== null && bn !== null) { - const len = Math.max(an.length, bn.length); - for (let i = 0; i < len; i++) { - const d = (an[i] ?? 0) - (bn[i] ?? 0); - if (d !== 0) return d; - } - return 0; - } - return av.localeCompare(bv); + const SPEC_PREFIX = "billion-context@"; + const av = a.startsWith(SPEC_PREFIX) ? a.slice(SPEC_PREFIX.length) : a; + const bv = b.startsWith(SPEC_PREFIX) ? b.slice(SPEC_PREFIX.length) : b; + const segments = (s: string): number[] | null => { + const parts = s.split("."); + if (parts.length === 0) return null; + const out: number[] = []; + for (const p of parts) { + if (!/^\d+$/.test(p)) return null; + out.push(Number(p)); + } + return out; + }; + const an = segments(av); + const bn = segments(bv); + if (an !== null && bn !== null) { + const len = Math.max(an.length, bn.length); + for (let i = 0; i < len; i++) { + const d = (an[i] ?? 0) - (bn[i] ?? 0); + if (d !== 0) return d; + } + return 0; + } + return av.localeCompare(bv); } /** #1234/#2199: on-disk root of the OpenCode v2 cache copy of billion-context — @@ -1923,285 +2827,438 @@ function compareSpecSlots(a: string, b: string): number { * reads/updates this INNER copy only — it never edits opencode's outer * package.json/package-lock.json nor deletes its cache, so drift between the * outer lockfile and the inner package version is expected and left alone. */ -export function opencodeCacheCopyRoot(env: NodeJS.ProcessEnv = process.env): string | undefined { - const xdgCache = env.XDG_CACHE_HOME && env.XDG_CACHE_HOME.trim().length > 0 ? env.XDG_CACHE_HOME : path.join(os.homedir(), ".cache"); - const npm = path.join(xdgCache, "opencode", "npm"); - let slots: string[]; - try { - slots = fs.readdirSync(npm); - } catch { - return undefined; - } - for (const slot of slots.filter((s) => s.startsWith("billion-context@")).sort(compareSpecSlots).reverse()) { - let stamps: string[]; - try { - stamps = fs.readdirSync(path.join(npm, slot)); - } catch { - continue; - } - for (const stamp of stamps.sort().reverse()) { - const root = path.join(npm, slot, stamp, "node_modules", DSH_PACKAGE); - try { - fs.accessSync(root); - return root; - } catch {} - } - } - return undefined; +export function opencodeCacheCopyRoot( + env: NodeJS.ProcessEnv = process.env, +): string | undefined { + const xdgCache = + env.XDG_CACHE_HOME && env.XDG_CACHE_HOME.trim().length > 0 + ? env.XDG_CACHE_HOME + : path.join(os.homedir(), ".cache"); + const npm = path.join(xdgCache, "opencode", "npm"); + let slots: string[]; + try { + slots = fs.readdirSync(npm); + } catch { + return undefined; + } + for (const slot of slots + .filter((s) => s.startsWith("billion-context@")) + .sort(compareSpecSlots) + .reverse()) { + let stamps: string[]; + try { + stamps = fs.readdirSync(path.join(npm, slot)); + } catch { + continue; + } + for (const stamp of stamps.sort().reverse()) { + const root = path.join(npm, slot, stamp, "node_modules", DSH_PACKAGE); + try { + fs.accessSync(root); + return root; + } catch {} + } + } + return undefined; } export function inspectLanePresence(agent: PluginAgent): LanePresence { - if (agent === "pi") { - const root = selfPackageRoot(); - const packages = readJson(piSettingsFile()).packages; - const list = Array.isArray(packages) ? (packages as unknown[]).map(String) : []; - const entries = list.filter((p) => isBiliPiEntry(p, root) || p === piEntryFor(root)); - if (entries.length === 0) return laneAbsent(); - // #2850: every npm spec form (plain / @pinned / @latest) resolves to - // the SAME pi-managed copy directory — the spec suffix never changes - // the folder name — so match the form, not just the exact unpinned - // string, and probe the real materialization path (piNpmCopyRoot). - if (entries.some((p) => /^npm:billion-context(@|$)/.test(p))) { - const store = piNpmCopyRoot(process.env); - return { - installed: true, - pointers: entries, - targets: fs.existsSync(store) ? [store] : [], - form: "npm", - copyVersion: pkgVersionAt(store), - }; - } - const abs = entries.find((p) => path.isAbsolute(p)); - return { - installed: true, - pointers: entries, - targets: abs !== undefined ? [abs] : [], - form: "local-path", - copyVersion: abs !== undefined ? pkgVersionAt(abs) : undefined, - }; - } - if (agent === "omp") { - let text: string; - try { - text = fs.readFileSync(ompConfigFile(), "utf8"); - } catch { - return laneAbsent(); - } - const lines = text.split("\n"); - const values = ompExtensionItemLines(text).map((i) => ompEntryValue(lines[i]!)).filter((v) => OMP_ENTRY_RE.test(v)); - if (values.length === 0) return laneAbsent(); - const targets = values.filter((v) => path.isAbsolute(v)); - const first = targets[0]; - return { - installed: true, - pointers: values, - targets, - form: "local-path", - copyVersion: first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, - }; - } - if (agent === "claude") { - const out = laneAbsent(); - try { - const data = readJson(claudeSettingsFile()); - const baseUrl = (data.env as Record | undefined)?.ANTHROPIC_BASE_URL; - if (typeof baseUrl === "string" && isBiliClaudeBaseUrl(baseUrl)) { - out.installed = true; - out.pointers.push(`env.ANTHROPIC_BASE_URL=${baseUrl}`); - } - } catch {} - try { - const mcpData = readJson(claudeMcpJson()) as { mcpServers?: Record }; - const bili = mcpData.mcpServers?.bili; - if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { - const s = bili as Record; - out.installed = true; - const args = Array.isArray(s.args) ? (s.args as unknown[]).map(String) : []; - out.pointers.push([s.command, ...args].filter((x) => typeof x === "string" && x.length > 0).join(" ")); - const script = args[0]; - if (script !== undefined && path.isAbsolute(script)) { - out.targets.push(script); - out.copyVersion = out.copyVersion ?? pkgVersionAt(rootFromDistFile(script)); - } - } - } catch {} - if (out.installed) out.form = "managed-block"; - return out; - } - if (agent === "codex") { - let text: string; - try { - text = fs.readFileSync(codexToml(), "utf8"); - } catch { - return laneAbsent(); - } - if (!/^\[mcp_servers\.bili\]\s*$/m.test(text)) return laneAbsent(); - const start = text.indexOf("[mcp_servers.bili]"); - const rest = text.slice(start); - const nextSection = /^\[[^\]\n]+\]/m.exec(rest.slice(1)); - const block = nextSection !== null ? rest.slice(0, 1 + nextSection.index) : rest; - const unquote = (raw: string): string => { - try { - const parsed: unknown = JSON.parse(raw); - return typeof parsed === "string" ? parsed : raw.replace(/^["']|["']$/g, ""); - } catch { - return raw.replace(/^["']|["']$/g, ""); - } - }; - const cmdMatch = /^command\s*=\s*(.+?)\s*$/m.exec(block); - const command = cmdMatch?.[1] ? unquote(cmdMatch[1]) : ""; - const argsMatch = /^args\s*=\s*\[(.*)\]\s*$/m.exec(block); - let args: string[] = []; - if (argsMatch?.[1]) { - try { - args = (JSON.parse(`[${argsMatch[1]}]`) as unknown[]).filter((x): x is string => typeof x === "string"); - } catch { - args = [...argsMatch[1].matchAll(/["']([^"']*)["']/g)].map((m) => m[1]!); - } - } - const targets = args.filter((a) => path.isAbsolute(a) && /\.js$/.test(a)); - const first = targets[0]; - return { - installed: true, - pointers: [`[mcp_servers.bili] command=${command || "?"} args=[${args.join(", ")}]`], - targets, - form: "managed-block", - copyVersion: first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, - }; - } - if (agent === "opencode") { - const file = opencodeTargetFile(); - const { data } = loadOpencodeConfig(file); - const dir = opencodePluginDir(file); - const listed = PLUGIN_KEYS.flatMap((k) => pluginEntries(data, k)).filter((p) => p === OPENCODE_NPM_ENTRY || p === dir); - const hasMcp = isPlainMcpObject(data.mcp) && "bili" in data.mcp; - if (listed.length === 0 && !hasMcp) return laneAbsent(); - const out: LanePresence = { installed: true, pointers: [...listed], targets: [], form: "none" }; - if (hasMcp) out.pointers.push("mcp.bili"); - if (listed.includes(OPENCODE_NPM_ENTRY)) { - out.form = "npm"; - // #1234/#2199: the bare npm entry is materialized into opencode's - // cache — surface the actual copy root + disk version so doctor can - // report staleness honestly instead of "version not resolvable". - const cacheRoot = opencodeCacheCopyRoot(); - if (cacheRoot !== undefined) { - out.targets.push(cacheRoot); - out.copyVersion = pkgVersionAt(cacheRoot); - } - } else if (listed.includes(dir)) { - out.form = "local-path"; - out.targets.push(path.join(dir, "index.js")); - out.copyVersion = pkgVersionAt(dir); - } - return out; - } - if (agent === "dsh") { - let dirs: string[]; - try { - dirs = dshProfileDirs(); - } catch { - return laneAbsent(); - } - const profiles = dirs.flatMap((dir) => { - const spec = dshProfileDepSpec(dir); - const bundled = dshBundleInstalled(dir); - if (spec === undefined && !bundled) return []; - return [{ - name: path.basename(dir), - spec, - pinned: spec !== undefined && !isRegistryDepSpec(spec), - bundleInstalled: bundled, - copyVersion: bundled ? pkgVersionAt(path.join(dir, "node_modules", DSH_PACKAGE)) : undefined, - }]; - }); - if (profiles.length === 0) return laneAbsent(); - return { - installed: true, - pointers: profiles.map((p) => `${p.name}: ${p.spec ?? "(no dep)"}`), - targets: [], - form: profiles.some((p) => p.pinned) ? "local-path" : "npm", - profiles, - }; - } - if (agent === "kimi") { - const manifestFile = path.join(kimiManagedDir(), "kimi.plugin.json"); - const manifestOk = fs.existsSync(manifestFile); - let registered = false; - try { - registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some((p) => p.id === KIMI_PLUGIN_ID); - } catch {} - if (!manifestOk && !registered) return laneAbsent(); - const out: LanePresence = { installed: manifestOk && registered, pointers: [], targets: [], form: "local-path" }; - if (!out.installed) out.pointers.push(manifestOk ? "manifest present but registry record missing" : "registry record present but manifest missing"); - try { - const man = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as Record; - if (typeof man.version === "string") out.copyVersion = man.version; - const mcpArgs = zcodeAsPlain(zcodeAsPlain(man.mcpServers)?.bili)?.args; - for (const a of Array.isArray(mcpArgs) ? (mcpArgs as unknown[]).map(String) : []) { - if (path.isAbsolute(a)) out.targets.push(a); - } - const hookCmd = Array.isArray(man.hooks) - ? (man.hooks as unknown[]).map((h) => zcodeAsPlain(h)?.command).find((c): c is string => typeof c === "string") - : undefined; - if (hookCmd !== undefined) { - const script = hookCmd.trim().split(/\s+/).pop(); - if (script !== undefined && path.isAbsolute(script)) out.targets.push(script); - } - } catch {} - return out; - } - if (agent === "hermes") { - const dir = hermesPluginDir(); - if (!fs.existsSync(path.join(dir, "__init__.py"))) return laneAbsent(); - const out: LanePresence = { installed: true, pointers: [dir], targets: [], form: "local-path" }; - try { - const sidecar = JSON.parse(fs.readFileSync(path.join(dir, "bili.json"), "utf8")) as HermesSidecar; - if (typeof sidecar.proxyScript === "string" && sidecar.proxyScript.length > 0) out.targets.push(sidecar.proxyScript); - } catch {} - try { - const yaml = fs.readFileSync(path.join(dir, "plugin.yaml"), "utf8"); - const m = /^version:\s*["']?([^"'\r\n]+?)["']?\s*$/m.exec(yaml); - if (m?.[1]) out.copyVersion = m[1]; - } catch {} - return out; - } - // zcode - const doc = readJson(zcodeUserConfigFile()); - const sessionStart = zcodeAsPlain(zcodeAsPlain(doc.hooks)?.events)?.SessionStart; - const hasHook = Array.isArray(sessionStart) && (sessionStart as unknown[]).some(isOursZcodeHookEntry); - const mcpBili = zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili; - const hasMcp = isOursZcodeMcpServer(mcpBili); - if (!hasHook && !hasMcp) return laneAbsent(); - const out: LanePresence = { installed: hasHook && hasMcp, pointers: [], targets: [], form: "managed-block" }; - if (!out.installed) out.pointers.push(hasHook ? "hook present, MCP face missing" : "MCP face present, hook missing"); - const collectArgs = (args: unknown): void => { - for (const a of Array.isArray(args) ? (args as unknown[]).map(String) : []) { - if (path.isAbsolute(a) && /\.(js|ts)$/.test(a)) out.targets.push(a); - } - }; - if (Array.isArray(sessionStart)) { - for (const e of sessionStart as unknown[]) { - if (!isOursZcodeHookEntry(e)) continue; - const hooks = zcodeAsPlain(e)?.hooks; - if (Array.isArray(hooks)) for (const h of hooks as unknown[]) collectArgs(zcodeAsPlain(h)?.args); - } - } - if (hasMcp) collectArgs(zcodeAsPlain(mcpBili)?.args); - const first = out.targets[0]; - if (first !== undefined) out.copyVersion = pkgVersionAt(rootFromDistFile(first)); - return out; + if (agent === "pi") { + const root = selfPackageRoot(); + const packages = readJson(piSettingsFile()).packages; + const list = Array.isArray(packages) + ? (packages as unknown[]).map(String) + : []; + const entries = list.filter( + (p) => isBiliPiEntry(p, root) || p === piEntryFor(root), + ); + if (entries.length === 0) return laneAbsent(); + // #2850: every npm spec form (plain / @pinned / @latest) resolves to + // the SAME pi-managed copy directory — the spec suffix never changes + // the folder name — so match the form, not just the exact unpinned + // string, and probe the real materialization path (piNpmCopyRoot). + if (entries.some((p) => /^npm:billion-context(@|$)/.test(p))) { + const store = piNpmCopyRoot(process.env); + return { + installed: true, + pointers: entries, + targets: fs.existsSync(store) ? [store] : [], + form: "npm", + copyVersion: pkgVersionAt(store), + }; + } + const abs = entries.find((p) => path.isAbsolute(p)); + return { + installed: true, + pointers: entries, + targets: abs !== undefined ? [abs] : [], + form: "local-path", + copyVersion: abs !== undefined ? pkgVersionAt(abs) : undefined, + }; + } + if (agent === "omp") { + let text: string; + try { + text = fs.readFileSync(ompConfigFile(), "utf8"); + } catch { + return laneAbsent(); + } + const lines = text.split("\n"); + const values = ompExtensionItemLines(text) + .map((i) => ompEntryValue(lines[i]!)) + .filter((v) => OMP_ENTRY_RE.test(v)); + if (values.length === 0) return laneAbsent(); + const targets = values.filter((v) => path.isAbsolute(v)); + const first = targets[0]; + return { + installed: true, + pointers: values, + targets, + form: "local-path", + copyVersion: + first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, + }; + } + if (agent === "claude") { + const out = laneAbsent(); + try { + const data = readJson(claudeSettingsFile()); + const baseUrl = (data.env as Record | undefined) + ?.ANTHROPIC_BASE_URL; + if (typeof baseUrl === "string" && isBiliClaudeBaseUrl(baseUrl)) { + out.installed = true; + out.pointers.push(`env.ANTHROPIC_BASE_URL=${baseUrl}`); + } + } catch {} + try { + const mcpData = readJson(claudeMcpJson()) as { + mcpServers?: Record; + }; + const bili = mcpData.mcpServers?.bili; + if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { + const s = bili as Record; + out.installed = true; + const args = Array.isArray(s.args) + ? (s.args as unknown[]).map(String) + : []; + out.pointers.push( + [s.command, ...args] + .filter((x) => typeof x === "string" && x.length > 0) + .join(" "), + ); + const script = args[0]; + if (script !== undefined && path.isAbsolute(script)) { + out.targets.push(script); + out.copyVersion = + out.copyVersion ?? pkgVersionAt(rootFromDistFile(script)); + } + } + } catch {} + if (out.installed) out.form = "managed-block"; + return out; + } + if (agent === "codex") { + let text: string; + try { + text = fs.readFileSync(codexToml(), "utf8"); + } catch { + return laneAbsent(); + } + if (!/^\[mcp_servers\.bili\]\s*$/m.test(text)) return laneAbsent(); + const start = text.indexOf("[mcp_servers.bili]"); + const rest = text.slice(start); + const nextSection = /^\[[^\]\n]+\]/m.exec(rest.slice(1)); + const block = + nextSection !== null ? rest.slice(0, 1 + nextSection.index) : rest; + const unquote = (raw: string): string => { + try { + const parsed: unknown = JSON.parse(raw); + return typeof parsed === "string" + ? parsed + : raw.replace(/^["']|["']$/g, ""); + } catch { + return raw.replace(/^["']|["']$/g, ""); + } + }; + const cmdMatch = /^command\s*=\s*(.+?)\s*$/m.exec(block); + const command = cmdMatch?.[1] ? unquote(cmdMatch[1]) : ""; + const argsMatch = /^args\s*=\s*\[(.*)\]\s*$/m.exec(block); + let args: string[] = []; + if (argsMatch?.[1]) { + try { + args = (JSON.parse(`[${argsMatch[1]}]`) as unknown[]).filter( + (x): x is string => typeof x === "string", + ); + } catch { + args = [...argsMatch[1].matchAll(/["']([^"']*)["']/g)].map( + (m) => m[1]!, + ); + } + } + const targets = args.filter((a) => path.isAbsolute(a) && /\.js$/.test(a)); + const first = targets[0]; + const out: LanePresence = { + installed: true, + pointers: [ + `[mcp_servers.bili] command=${command || "?"} args=[${args.join(", ")}]`, + ], + targets, + form: "managed-block", + copyVersion: + first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, + }; + // Ticket 08 faces, reported next to (never instead of) the MCP block: a + // session hook and the ACP skill are separate integration surfaces, so a + // lane missing only one of them must not read as fully installed. + const hookCommand = findBiliCodexHook(text); + if (hookCommand !== undefined) { + out.pointers.push(`hooks.SessionStart: ${hookCommand}`); + const hookDisabled = codexHooksEnabledNote(text); + if (hookDisabled !== "") + out.pointers.push(`hooks disabled — ${hookDisabled}`); + } else { + out.pointers.push("hooks.SessionStart: not installed"); + } + const skillState = codexSkillStatus(process.env); + out.pointers.push( + skillState === "installed" + ? `skill: ${codexSkillFile(process.env)}` + : skillState === "outdated" + ? "skill: outdated (rerun install)" + : skillState === "foreign" + ? "skill: not owned by bili (left untouched)" + : "skill: not installed", + ); + return out; + } + if (agent === "opencode") { + const file = opencodeTargetFile(); + const { data } = loadOpencodeConfig(file); + const dir = opencodePluginDir(file); + const listed = PLUGIN_KEYS.flatMap((k) => pluginEntries(data, k)).filter( + (p) => p === OPENCODE_NPM_ENTRY || p === dir, + ); + const hasMcp = isPlainMcpObject(data.mcp) && "bili" in data.mcp; + if (listed.length === 0 && !hasMcp) return laneAbsent(); + const out: LanePresence = { + installed: true, + pointers: [...listed], + targets: [], + form: "none", + }; + if (hasMcp) out.pointers.push("mcp.bili"); + if (listed.includes(OPENCODE_NPM_ENTRY)) { + out.form = "npm"; + // #1234/#2199: the bare npm entry is materialized into opencode's + // cache — surface the actual copy root + disk version so doctor can + // report staleness honestly instead of "version not resolvable". + const cacheRoot = opencodeCacheCopyRoot(); + if (cacheRoot !== undefined) { + out.targets.push(cacheRoot); + out.copyVersion = pkgVersionAt(cacheRoot); + } + } else if (listed.includes(dir)) { + out.form = "local-path"; + out.targets.push(path.join(dir, "index.js")); + out.copyVersion = pkgVersionAt(dir); + } + return out; + } + if (agent === "dsh") { + let dirs: string[]; + try { + dirs = dshProfileDirs(); + } catch { + return laneAbsent(); + } + const profiles = dirs.flatMap((dir) => { + const spec = dshProfileDepSpec(dir); + const bundled = dshBundleInstalled(dir); + if (spec === undefined && !bundled) return []; + return [ + { + name: path.basename(dir), + spec, + pinned: spec !== undefined && !isRegistryDepSpec(spec), + bundleInstalled: bundled, + copyVersion: bundled + ? pkgVersionAt(path.join(dir, "node_modules", DSH_PACKAGE)) + : undefined, + }, + ]; + }); + if (profiles.length === 0) return laneAbsent(); + return { + installed: true, + pointers: profiles.map((p) => `${p.name}: ${p.spec ?? "(no dep)"}`), + targets: [], + form: profiles.some((p) => p.pinned) ? "local-path" : "npm", + profiles, + }; + } + if (agent === "kimi") { + const manifestFile = path.join(kimiManagedDir(), "kimi.plugin.json"); + const manifestOk = fs.existsSync(manifestFile); + let registered = false; + try { + registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some( + (p) => p.id === KIMI_PLUGIN_ID, + ); + } catch {} + if (!manifestOk && !registered) return laneAbsent(); + const out: LanePresence = { + installed: manifestOk && registered, + pointers: [], + targets: [], + form: "local-path", + }; + if (!out.installed) + out.pointers.push( + manifestOk + ? "manifest present but registry record missing" + : "registry record present but manifest missing", + ); + try { + const man = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as Record< + string, + unknown + >; + if (typeof man.version === "string") out.copyVersion = man.version; + const mcpArgs = zcodeAsPlain(zcodeAsPlain(man.mcpServers)?.bili)?.args; + for (const a of Array.isArray(mcpArgs) + ? (mcpArgs as unknown[]).map(String) + : []) { + if (path.isAbsolute(a)) out.targets.push(a); + } + const hookCmd = Array.isArray(man.hooks) + ? (man.hooks as unknown[]) + .map((h) => zcodeAsPlain(h)?.command) + .find((c): c is string => typeof c === "string") + : undefined; + if (hookCmd !== undefined) { + const script = hookCmd.trim().split(/\s+/).pop(); + if (script !== undefined && path.isAbsolute(script)) + out.targets.push(script); + } + } catch {} + return out; + } + if (agent === "hermes") { + const dir = hermesPluginDir(); + if (!fs.existsSync(path.join(dir, "__init__.py"))) return laneAbsent(); + const out: LanePresence = { + installed: true, + pointers: [dir], + targets: [], + form: "local-path", + }; + try { + const sidecar = JSON.parse( + fs.readFileSync(path.join(dir, "bili.json"), "utf8"), + ) as HermesSidecar; + if ( + typeof sidecar.proxyScript === "string" && + sidecar.proxyScript.length > 0 + ) + out.targets.push(sidecar.proxyScript); + } catch {} + try { + const yaml = fs.readFileSync(path.join(dir, "plugin.yaml"), "utf8"); + const m = /^version:\s*["']?([^"'\r\n]+?)["']?\s*$/m.exec(yaml); + if (m?.[1]) out.copyVersion = m[1]; + } catch {} + return out; + } + // zcode + const doc = readJson(zcodeUserConfigFile()); + const sessionStart = zcodeAsPlain( + zcodeAsPlain(doc.hooks)?.events, + )?.SessionStart; + const hasHook = + Array.isArray(sessionStart) && + (sessionStart as unknown[]).some(isOursZcodeHookEntry); + const mcpBili = zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili; + const hasMcp = isOursZcodeMcpServer(mcpBili); + if (!hasHook && !hasMcp) return laneAbsent(); + const out: LanePresence = { + installed: hasHook && hasMcp, + pointers: [], + targets: [], + form: "managed-block", + }; + if (!out.installed) + out.pointers.push( + hasHook + ? "hook present, MCP face missing" + : "MCP face present, hook missing", + ); + const collectArgs = (args: unknown): void => { + for (const a of Array.isArray(args) + ? (args as unknown[]).map(String) + : []) { + if (path.isAbsolute(a) && /\.(js|ts)$/.test(a)) out.targets.push(a); + } + }; + if (Array.isArray(sessionStart)) { + for (const e of sessionStart as unknown[]) { + if (!isOursZcodeHookEntry(e)) continue; + const hooks = zcodeAsPlain(e)?.hooks; + if (Array.isArray(hooks)) + for (const h of hooks as unknown[]) collectArgs(zcodeAsPlain(h)?.args); + } + } + if (hasMcp) collectArgs(zcodeAsPlain(mcpBili)?.args); + const first = out.targets[0]; + if (first !== undefined) + out.copyVersion = pkgVersionAt(rootFromDistFile(first)); + return out; } export function isPluginAgent(value: string): value is PluginAgent { - return (PLUGIN_AGENTS as readonly string[]).includes(value); + return (PLUGIN_AGENTS as readonly string[]).includes(value); } -export function pluginInstall(agent: PluginAgent, opts: { withMcp?: boolean } = {}): string { - return agent === "pi" ? piInstall() : agent === "omp" ? ompInstall() : agent === "claude" ? claudeInstall() : agent === "codex" ? codexInstall() : agent === "dsh" ? dshInstall() : agent === "kimi" ? kimiInstall() : agent === "hermes" ? hermesInstall() : agent === "zcode" ? zcodeInstall() : opencodeInstall(opts.withMcp === true); +export function pluginInstall( + agent: PluginAgent, + opts: { withMcp?: boolean } = {}, +): string { + return agent === "pi" + ? piInstall() + : agent === "omp" + ? ompInstall() + : agent === "claude" + ? claudeInstall() + : agent === "codex" + ? codexInstall() + : agent === "dsh" + ? dshInstall() + : agent === "kimi" + ? kimiInstall() + : agent === "hermes" + ? hermesInstall() + : agent === "zcode" + ? zcodeInstall() + : opencodeInstall(opts.withMcp === true); } export function pluginRemove(agent: PluginAgent): string { - return agent === "pi" ? piRemove() : agent === "omp" ? ompRemove() : agent === "claude" ? claudeRemove() : agent === "codex" ? codexRemove() : agent === "dsh" ? dshRemove() : agent === "kimi" ? kimiRemove() : agent === "hermes" ? hermesRemove() : agent === "zcode" ? zcodeRemove() : opencodeRemove(); + return agent === "pi" + ? piRemove() + : agent === "omp" + ? ompRemove() + : agent === "claude" + ? claudeRemove() + : agent === "codex" + ? codexRemove() + : agent === "dsh" + ? dshRemove() + : agent === "kimi" + ? kimiRemove() + : agent === "hermes" + ? hermesRemove() + : agent === "zcode" + ? zcodeRemove() + : opencodeRemove(); } /** #2155 uninstall guardrail (advisory half): `bili plugin remove ` @@ -2210,35 +3267,48 @@ export function pluginRemove(agent: PluginAgent): string { * but the session binding is sticky). The proxy side self-heals those sessions * (degrade to proxy mode); this note closes the loop for the human. Best-effort: * any failure (no proxy, endpoint down, odd shape) stays silent. */ -export async function warnActivePluginSessions(agent: PluginAgent): Promise { - try { - const inst = readProxyInstanceFile(); - if (inst === undefined) return ""; - const res = await fetch(inst.origin.replace(/\/$/, "") + "/__bili/sessions", { signal: AbortSignal.timeout(2500), headers: { accept: "application/json" } }); - if (!res.ok) return ""; - const data = (await res.json()) as { sessions?: Array> }; - const sessions = Array.isArray(data.sessions) ? data.sessions : []; - const cutoff = Date.now() - 10 * 60 * 1000; - let live = 0; - for (const s of sessions) { - const hint = typeof s["clientHint"] === "string" ? s["clientHint"] : ""; - const seen = typeof s["lastSeen"] === "string" ? Date.parse(s["lastSeen"]) : Number.NaN; - if (hint === agent && Number.isFinite(seen) && seen >= cutoff) live += 1; - } - if (live === 0) return ""; - return `note: ${live} active ${agent} session(s) seen in the last 10 minutes — already-open client windows keep running; their plugin lane is gone and the proxy self-heals them to proxy mode (#2155). Reload/restart the client to fully detach.`; - } catch { - return ""; - } +export async function warnActivePluginSessions( + agent: PluginAgent, +): Promise { + try { + const inst = readProxyInstanceFile(); + if (inst === undefined) return ""; + const res = await fetch( + inst.origin.replace(/\/$/, "") + "/__bili/sessions", + { + signal: AbortSignal.timeout(2500), + headers: { accept: "application/json" }, + }, + ); + if (!res.ok) return ""; + const data = (await res.json()) as { + sessions?: Array>; + }; + const sessions = Array.isArray(data.sessions) ? data.sessions : []; + const cutoff = Date.now() - 10 * 60 * 1000; + let live = 0; + for (const s of sessions) { + const hint = typeof s["clientHint"] === "string" ? s["clientHint"] : ""; + const seen = + typeof s["lastSeen"] === "string" + ? Date.parse(s["lastSeen"]) + : Number.NaN; + if (hint === agent && Number.isFinite(seen) && seen >= cutoff) live += 1; + } + if (live === 0) return ""; + return `note: ${live} active ${agent} session(s) seen in the last 10 minutes — already-open client windows keep running; their plugin lane is gone and the proxy self-heals them to proxy mode (#2155). Reload/restart the client to fully detach.`; + } catch { + return ""; + } } export interface PluginStatusRow { - agent: string; - status: string; - channel: string; - /** On-disk version of the billion-context copy this lane loads (#2325); - * undefined when not resolvable from disk. */ - copyVersion?: string; + agent: string; + status: string; + channel: string; + /** On-disk version of the billion-context copy this lane loads (#2325); + * undefined when not resolvable from disk. */ + copyVersion?: string; } /** The billion-context version(s) a lane's on-disk copy actually loads @@ -2246,39 +3316,55 @@ export interface PluginStatusRow { * → the distinct per-profile versions joined with "," so cross-profile drift * stays visible. undefined when nothing is resolvable. */ function laneCopyVersion(presence: LanePresence): string | undefined { - if (!presence.installed) return undefined; - if (presence.profiles !== undefined) { - const set = [...new Set(presence.profiles.map((p) => p.copyVersion).filter((v): v is string => v !== undefined))]; - return set.length > 0 ? set.join(",") : undefined; - } - return presence.copyVersion; + if (!presence.installed) return undefined; + if (presence.profiles !== undefined) { + const set = [ + ...new Set( + presence.profiles + .map((p) => p.copyVersion) + .filter((v): v is string => v !== undefined), + ), + ]; + return set.length > 0 ? set.join(",") : undefined; + } + return presence.copyVersion; } export function pluginStatusAll(): PluginStatusRow[] { - const checks: Array<[PluginAgent, () => string]> = [ - ["pi", piStatus], - ["omp", ompStatus], - ["claude", claudeStatus], - ["codex", codexStatus], - ["opencode", opencodeStatus], - ["dsh", dshStatus], - ["kimi", kimiStatus], - ["hermes", hermesStatus], - ["zcode", zcodeStatus], - ]; - return checks.map(([agent, check]) => { - let copyVersion: string | undefined; - try { - copyVersion = laneCopyVersion(inspectLanePresence(agent)); - } catch { - copyVersion = undefined; - } - try { - return { agent, status: check(), channel: UPDATE_CHANNEL[agent], copyVersion }; - } catch (err) { - return { agent, status: `error: ${err instanceof Error ? err.message : String(err)}`, channel: UPDATE_CHANNEL[agent], copyVersion }; - } - }); + const checks: Array<[PluginAgent, () => string]> = [ + ["pi", piStatus], + ["omp", ompStatus], + ["claude", claudeStatus], + ["codex", codexStatus], + ["opencode", opencodeStatus], + ["dsh", dshStatus], + ["kimi", kimiStatus], + ["hermes", hermesStatus], + ["zcode", zcodeStatus], + ]; + return checks.map(([agent, check]) => { + let copyVersion: string | undefined; + try { + copyVersion = laneCopyVersion(inspectLanePresence(agent)); + } catch { + copyVersion = undefined; + } + try { + return { + agent, + status: check(), + channel: UPDATE_CHANNEL[agent], + copyVersion, + }; + } catch (err) { + return { + agent, + status: `error: ${err instanceof Error ? err.message : String(err)}`, + channel: UPDATE_CHANNEL[agent], + copyVersion, + }; + } + }); } // #991 single-writer: every lane's update path, user-facing. Host-managed @@ -2290,15 +3376,17 @@ export function pluginStatusAll(): PluginStatusRow[] { // bili install itself — hermes additionally re-copies its Python files via // `bili plugin update hermes`. export const UPDATE_CHANNEL: Record = { - pi: "pi update --extension npm:billion-context (pi owns the npm copy; its proxy self-drives the refresh every check cycle, #1196)", - omp: "the global bili install (entry points at it)", - claude: "the global bili install (hook/MCP point at it)", - codex: "the global bili install (the mcp launcher shells out to it)", - opencode: "the cache copy self-updates in place via its own proxy (#1234); OpenCode v2 'plugin update' is an extra manual channel — reload/restart OpenCode after a disk update to activate", - dsh: "the global bili self-update (profile bundles track it)", - kimi: "the global bili install (plugin points at its dist)", - hermes: "the global bili install (sidecar points at its dist); `bili plugin update hermes` re-copies the plugin", - zcode: "the global bili install (hook/MCP point at its dist)", + pi: "pi update --extension npm:billion-context (pi owns the npm copy; its proxy self-drives the refresh every check cycle, #1196)", + omp: "the global bili install (entry points at it)", + claude: "the global bili install (hook/MCP point at it)", + codex: "the global bili install (the mcp launcher shells out to it)", + opencode: + "the cache copy self-updates in place via its own proxy (#1234); OpenCode v2 'plugin update' is an extra manual channel — reload/restart OpenCode after a disk update to activate", + dsh: "the global bili self-update (profile bundles track it)", + kimi: "the global bili install (plugin points at its dist)", + hermes: + "the global bili install (sidecar points at its dist); `bili plugin update hermes` re-copies the plugin", + zcode: "the global bili install (hook/MCP point at its dist)", }; /** Render `bili plugin list` as an aligned table with a version column (#2325). @@ -2307,42 +3395,53 @@ export const UPDATE_CHANNEL: Record = { * the resolved version. It NEVER falls back to the running CLI version; the * on-disk copy may lag a still-running session until reload/restart. */ export function renderPluginList(rows: PluginStatusRow[]): string { - const cells = rows.map((r) => { - const hidden = r.status === "not installed" || r.status.startsWith("error"); - return { - agent: r.agent, - status: r.status, - version: hidden ? "—" : (r.copyVersion ?? "unknown"), - channel: hidden ? "" : r.channel, - }; - }); - const wAgent = Math.max("agent".length, ...cells.map((c) => c.agent.length)); - const wVersion = Math.max("version".length, ...cells.map((c) => c.version.length)); - // Status is unbounded free text (multi-profile summaries, probe errors that - // carry file paths) — cap the padded width so one long row cannot stretch - // every other row out; an over-long status simply overflows its own row - // rather than being truncated. - const STATUS_CAP = 52; - const wStatus = Math.min(STATUS_CAP, Math.max("status".length, ...cells.map((c) => c.status.length))); - const padTo = (s: string, w: number): string => s.padEnd(w); - const lines: string[] = []; - lines.push(`${padTo("agent", wAgent)} ${padTo("status", wStatus)} ${padTo("version", wVersion)} updates via`); - for (const c of cells) { - const statusCell = c.status.length > wStatus ? c.status : padTo(c.status, wStatus); - const body = `${padTo(c.agent, wAgent)} ${statusCell} ${padTo(c.version, wVersion)}`; - lines.push((c.channel === "" ? body : `${body} ${c.channel}`).replace(/\s+$/, "")); - } - return `${lines.join("\n")}\n`; + const cells = rows.map((r) => { + const hidden = r.status === "not installed" || r.status.startsWith("error"); + return { + agent: r.agent, + status: r.status, + version: hidden ? "—" : (r.copyVersion ?? "unknown"), + channel: hidden ? "" : r.channel, + }; + }); + const wAgent = Math.max("agent".length, ...cells.map((c) => c.agent.length)); + const wVersion = Math.max( + "version".length, + ...cells.map((c) => c.version.length), + ); + // Status is unbounded free text (multi-profile summaries, probe errors that + // carry file paths) — cap the padded width so one long row cannot stretch + // every other row out; an over-long status simply overflows its own row + // rather than being truncated. + const STATUS_CAP = 52; + const wStatus = Math.min( + STATUS_CAP, + Math.max("status".length, ...cells.map((c) => c.status.length)), + ); + const padTo = (s: string, w: number): string => s.padEnd(w); + const lines: string[] = []; + lines.push( + `${padTo("agent", wAgent)} ${padTo("status", wStatus)} ${padTo("version", wVersion)} updates via`, + ); + for (const c of cells) { + const statusCell = + c.status.length > wStatus ? c.status : padTo(c.status, wStatus); + const body = `${padTo(c.agent, wAgent)} ${statusCell} ${padTo(c.version, wVersion)}`; + lines.push( + (c.channel === "" ? body : `${body} ${c.channel}`).replace(/\s+$/, ""), + ); + } + return `${lines.join("\n")}\n`; } interface PluginUpdateOpts { - packageName: string; - resolveProxy?: (url: string) => string | undefined; - updateTag?: string; - /** Runs the global self-update check before per-lane reports. The CLI - * wires this to checkForUpdate(force); tests omit it to stay offline. */ - globalCheck?: () => Promise; - log?: (level: "info" | "warn", msg: string) => void; + packageName: string; + resolveProxy?: (url: string) => string | undefined; + updateTag?: string; + /** Runs the global self-update check before per-lane reports. The CLI + * wires this to checkForUpdate(force); tests omit it to stay offline. */ + globalCheck?: () => Promise; + log?: (level: "info" | "warn", msg: string) => void; } /** `bili plugin update [agent]` — bring every lane's bili presence up to @@ -2360,80 +3459,118 @@ interface PluginUpdateOpts { * through dsh's own plugin channel. * Returns user-facing lines. Network is only touched when a dsh profile * actually depends on bili (version lookup) or globalCheck is provided. */ -export async function pluginUpdate(agents: readonly PluginAgent[] | undefined, opts: PluginUpdateOpts): Promise { - const log = opts.log ?? (() => {}); - const lines: string[] = []; - if (opts.globalCheck) { - await opts.globalCheck(); - lines.push("global bili copy: update check ran (see log above; it skips copies owned by a host)"); - } - for (const agent of agents ?? PLUGIN_AGENTS) { - try { - lines.push(...await updateLane(agent as PluginAgent, opts, log)); - } catch (err) { - lines.push(`${agent}: update failed — ${err instanceof Error ? err.message : String(err)}`); - } - } - return lines; -} - -async function updateLane(agent: PluginAgent, opts: PluginUpdateOpts, log: (level: "info" | "warn", msg: string) => void): Promise { - if (agent === "pi") { - const packages = readJson(piSettingsFile()).packages; - const list = Array.isArray(packages) ? (packages as unknown[]).map(String) : []; - const root = selfPackageRoot(); - // #2850: versioned npm specs (@pinned/@latest) are the same pi-managed - // copy, not a checkout pointer — route them to the same message. - if (list.some((p) => /^npm:billion-context(@|$)/.test(p))) { - return ["pi: the plugin copy is pi-managed (npm:billion-context) — `pi update` upgrades it; bili never overwrites it (#991)"]; - } - if (list.some((p) => isPiEntry(p, root))) { - return ["pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; - } - return ["pi: not installed"]; - } - if (agent === "opencode") { - const file = opencodeTargetFile(); - const { data } = loadOpencodeConfig(file); - const dir = opencodePluginDir(file); - if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY))) { - const root = opencodeCacheCopyRoot(); - const ver = root !== undefined ? pkgVersionAt(root) : undefined; - const where = root !== undefined ? ` (${root})` : ""; - const v = ver !== undefined ? ` v${ver}` : ""; - return [`opencode: the cache copy is bili-owned and self-updates in place through its own proxy${where}${v} (#1234) — this command does NOT run opencode's upgrade; OpenCode v2 'plugin update' is an extra manual channel, and reload/restart OpenCode after a disk update to activate it`]; - } - if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir))) { - return ["opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; - } - return ["opencode: not installed"]; - } - if (agent === "dsh") { - let dirs: string[]; - try { - dirs = dshProfileDirs(); - } catch { - return ["dsh: never initialized on this machine — nothing to update"]; - } - const targets = dirs.filter((dir) => dshProfileDependsOnBili(dir)); - if (targets.length === 0) return ["dsh: no profile depends on billion-context — nothing to update"]; - const latest = await fetchRegistryVersion(opts, opts.packageName); - if (!latest) return ["dsh: could not resolve the latest version from npm — leaving profile bundles alone"]; - const before = targets.length; - const { refreshed, failed } = await refreshDshProfileBundles(latest, log); - if (failed === 0) { - // #2192: a clean manual run is evidence the lane works — disarm - // its cooldown immediately instead of letting the automatic channel - // wait out the window (up to 6 h). - await clearOwnerLaneBackoff("dsh-profile", latest); - } - return [`dsh: ${refreshed}/${before} profile bundle(s) refreshed to ${latest} through dsh's plugin channel${failed > 0 ? ` (${failed} failed)` : ""} (see log for per-profile results)`]; - } - if (agent === "hermes") { - if (hermesStatus() !== "installed") return ["hermes: not installed — nothing to update"]; - hermesInstallCore(); - return [`hermes: re-copied the plugin into ${hermesPluginDir()} (bili ${selfVersion()}) — restart hermes to pick it up`]; - } - const via = UPDATE_CHANNEL[agent]; - return [`${agent}: the plugin entry follows the global bili install — it updates together with it (${via})`]; +export async function pluginUpdate( + agents: readonly PluginAgent[] | undefined, + opts: PluginUpdateOpts, +): Promise { + const log = opts.log ?? (() => {}); + const lines: string[] = []; + if (opts.globalCheck) { + await opts.globalCheck(); + lines.push( + "global bili copy: update check ran (see log above; it skips copies owned by a host)", + ); + } + for (const agent of agents ?? PLUGIN_AGENTS) { + try { + lines.push(...(await updateLane(agent as PluginAgent, opts, log))); + } catch (err) { + lines.push( + `${agent}: update failed — ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + return lines; +} + +async function updateLane( + agent: PluginAgent, + opts: PluginUpdateOpts, + log: (level: "info" | "warn", msg: string) => void, +): Promise { + if (agent === "pi") { + const packages = readJson(piSettingsFile()).packages; + const list = Array.isArray(packages) + ? (packages as unknown[]).map(String) + : []; + const root = selfPackageRoot(); + // #2850: versioned npm specs (@pinned/@latest) are the same pi-managed + // copy, not a checkout pointer — route them to the same message. + if (list.some((p) => /^npm:billion-context(@|$)/.test(p))) { + return [ + "pi: the plugin copy is pi-managed (npm:billion-context) — `pi update` upgrades it; bili never overwrites it (#991)", + ]; + } + if (list.some((p) => isPiEntry(p, root))) { + return [ + "pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes", + ]; + } + return ["pi: not installed"]; + } + if (agent === "opencode") { + const file = opencodeTargetFile(); + const { data } = loadOpencodeConfig(file); + const dir = opencodePluginDir(file); + if ( + PLUGIN_KEYS.some((k) => + pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY), + ) + ) { + const root = opencodeCacheCopyRoot(); + const ver = root !== undefined ? pkgVersionAt(root) : undefined; + const where = root !== undefined ? ` (${root})` : ""; + const v = ver !== undefined ? ` v${ver}` : ""; + return [ + `opencode: the cache copy is bili-owned and self-updates in place through its own proxy${where}${v} (#1234) — this command does NOT run opencode's upgrade; OpenCode v2 'plugin update' is an extra manual channel, and reload/restart OpenCode after a disk update to activate it`, + ]; + } + if ( + PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir)) + ) { + return [ + "opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes", + ]; + } + return ["opencode: not installed"]; + } + if (agent === "dsh") { + let dirs: string[]; + try { + dirs = dshProfileDirs(); + } catch { + return ["dsh: never initialized on this machine — nothing to update"]; + } + const targets = dirs.filter((dir) => dshProfileDependsOnBili(dir)); + if (targets.length === 0) + return ["dsh: no profile depends on billion-context — nothing to update"]; + const latest = await fetchRegistryVersion(opts, opts.packageName); + if (!latest) + return [ + "dsh: could not resolve the latest version from npm — leaving profile bundles alone", + ]; + const before = targets.length; + const { refreshed, failed } = await refreshDshProfileBundles(latest, log); + if (failed === 0) { + // #2192: a clean manual run is evidence the lane works — disarm + // its cooldown immediately instead of letting the automatic channel + // wait out the window (up to 6 h). + await clearOwnerLaneBackoff("dsh-profile", latest); + } + return [ + `dsh: ${refreshed}/${before} profile bundle(s) refreshed to ${latest} through dsh's plugin channel${failed > 0 ? ` (${failed} failed)` : ""} (see log for per-profile results)`, + ]; + } + if (agent === "hermes") { + if (hermesStatus() !== "installed") + return ["hermes: not installed — nothing to update"]; + hermesInstallCore(); + return [ + `hermes: re-copied the plugin into ${hermesPluginDir()} (bili ${selfVersion()}) — restart hermes to pick it up`, + ]; + } + const via = UPDATE_CHANNEL[agent]; + return [ + `${agent}: the plugin entry follows the global bili install — it updates together with it (${via})`, + ]; } diff --git a/src/server/admin.ts b/src/server/admin.ts index 9f51be005c..6994a85246 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -1,11 +1,27 @@ -import http from "node:http"; +import type http from "node:http"; import fs from "node:fs"; import path from "node:path"; import type { CompressionCore, Config } from "acp-kernel"; -import { APIG_RESIGN_SCHEME, KNOWN_SIGNATURE_SCHEMES, readPendingRefusals, unresolvedRefusals } from "../apig-resign.js"; -import { handleAcpCache, readKeySwitchStats, readModelSwitchStats, readProjSwitchStats, readPromptSwitchStats } from "../cache-ledger.js"; +import { + APIG_RESIGN_SCHEME, + KNOWN_SIGNATURE_SCHEMES, + readPendingRefusals, + unresolvedRefusals, +} from "../apig-resign.js"; +import { + handleAcpCache, + readKeySwitchStats, + readModelSwitchStats, + readProjSwitchStats, + readPromptSwitchStats, +} from "../cache-ledger.js"; import type { ProxyOptions } from "../config.js"; -import { loadNamedProviders, loadOptions, loadRoutes, resolveResignSettings } from "../config.js"; +import { + loadNamedProviders, + loadOptions, + loadRoutes, + resolveResignSettings, +} from "../config.js"; import { applyCompressSettings } from "../compress-settings.js"; import { clearConflictEvents, summarizeConflicts } from "../conflict-watch.js"; import { cannotResolveTarget, getAdvisoryState } from "../advisory.js"; @@ -13,33 +29,81 @@ import { detectCostAdvisories } from "../plugin-advisory.js"; import { fetchWithTimeout } from "../fetch-util.js"; import { log as loggerLog, getLogPath } from "../logger.js"; import { getBlindTunnelStats } from "../mitm.js"; -import { handlePluginCompact, handlePluginFork, handlePluginManifest, handlePluginRegister, handlePluginRuntimeInfo, handlePluginSessionName, handlePluginSnapshot, handlePluginStatus, handlePluginTool } from "../plugin.js"; -import { parseAgentProviderReport, recordAgentProviders, agentProviderRecipes, sanitizeAgentProviderField } from "../agent-providers.js"; +import { + handlePluginCompact, + handlePluginFork, + handlePluginManifest, + handlePluginRegister, + handlePluginRuntimeInfo, + handlePluginSessionName, + handlePluginSnapshot, + handlePluginStatus, + handlePluginTool, +} from "../plugin.js"; +import { + parseAgentProviderReport, + recordAgentProviders, + agentProviderRecipes, + sanitizeAgentProviderField, +} from "../agent-providers.js"; import { defaultLogFile } from "../paths.js"; import { getUpdateVisibility, updateBannerPayload } from "../update-notes.js"; import { getUnrecognizedPathStats } from "./observability.js"; import { getStore } from "../persist.js"; -import { BodyTooLargeError, headerValue, readBody, selfAdminProbePath } from "../server.js"; -import { dismissHostPlugin, visibleHostPluginNotices } from "../host-plugin-notice.js"; -import { listSessions, peekSession, splitSessionWarnings, totalInFlight } from "../session.js"; +import { isCodexClient } from "../codex-compact.js"; +import { + BodyTooLargeError, + headerValue, + readBody, + selfAdminProbePath, +} from "../server.js"; +import { + dismissHostPlugin, + visibleHostPluginNotices, +} from "../host-plugin-notice.js"; +import { + listSessions, + peekSession, + splitSessionWarnings, + totalInFlight, +} from "../session.js"; import { BILI_TUNNEL_HEADER } from "../tunnel-guard.js"; import { isLoopbackAddress } from "../util.js"; -import { clearUpstreamAlertsForHost, getUpstreamAlerts } from "../upstream-alerts.js"; -import { formatUpstreamError, getUpstreamConnectionStatus, proxyDispatcher, recordUpstreamConnection, resetProxyCache, resolveProxyDecision } from "../upstream-proxy.js"; +import { + clearUpstreamAlertsForHost, + getUpstreamAlerts, +} from "../upstream-alerts.js"; +import { + formatUpstreamError, + getUpstreamConnectionStatus, + proxyDispatcher, + recordUpstreamConnection, + resetProxyCache, + resolveProxyDecision, +} from "../upstream-proxy.js"; import { detectStaleInstall } from "../update.js"; import { PACKAGE_NAME, VERSION, BUILD_COMMIT } from "../version.js"; -import { buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, handleConfigGet, handleConfigPut, hiddenEmptyCount, renderUI } from "../web/index.js"; +import { + buildOverview, + buildSessionDetail, + buildSessionList, + buildSessionPage, + handleConfigGet, + handleConfigPut, + hiddenEmptyCount, + renderUI, +} from "../web/index.js"; import { queryLogLines } from "../web/logs-query.js"; interface AdminCtx { - opts: ProxyOptions; - core: CompressionCore; - config: Config; - log: (level: string, msg: string) => void; - instanceId: string; - instanceStartedAt: number; - proxyWatchers: Set; - initialWatcherPid: number | null; + opts: ProxyOptions; + core: CompressionCore; + config: Config; + log: (level: string, msg: string) => void; + instanceId: string; + instanceStartedAt: number; + proxyWatchers: Set; + initialWatcherPid: number | null; } // #1537: reduce a Host-header value or a URL hostname to its bare lowercase @@ -47,43 +111,48 @@ interface AdminCtx { // Returns undefined for empty/unparseable input. The admin-origin gate uses it // to match on the hostname alone (see isTrustedAdminOrigin). function normalizeAdminHostname(value: string | undefined): string | undefined { - if (!value) return undefined; - const v = value.trim().toLowerCase(); - if (!v) return undefined; - if (v.startsWith("[")) { - const end = v.indexOf("]"); - if (end === -1) return undefined; - return v.slice(1, end); - } - // Bare IPv6 literal (no brackets): more than one colon means there is no - // host:port split to perform — return it untouched. - if ((v.match(/:/g) ?? []).length > 1) return v; - const idx = v.lastIndexOf(":"); - if (idx !== -1) return v.slice(0, idx); - return v; + if (!value) return undefined; + const v = value.trim().toLowerCase(); + if (!v) return undefined; + if (v.startsWith("[")) { + const end = v.indexOf("]"); + if (end === -1) return undefined; + return v.slice(1, end); + } + // Bare IPv6 literal (no brackets): more than one colon means there is no + // host:port split to perform — return it untouched. + if ((v.match(/:/g) ?? []).length > 1) return v; + const idx = v.lastIndexOf(":"); + if (idx !== -1) return v.slice(0, idx); + return v; } -function isTrustedAdminOrigin(origin: string | undefined, host: string | undefined, trustedHostnames: Set): boolean { - // Host must name one of OUR loopback identities regardless of whether an - // Origin header is present. A same-origin browser GET/fetch (the DNS - // rebinding read path: evil.com → 127.0.0.1) often carries NO Origin - // header, so gating on Origin alone would leave config reads exposed. - // #1537: match on the bare hostname and IGNORE the port — an SSH forward - // (ssh -L 18787:127.0.0.1:8787) legitimately presents a different local - // port while still arriving from loopback. The anti-rebinding property is - // preserved because an attacker's rebound domain (evil.com) can never equal - // a loopback NAME; only the port is relaxed. - const hn = normalizeAdminHostname(host); - if (!hn || !trustedHostnames.has(hn)) return false; - if (!origin) return true; // non-browser client (curl, CLI UI) on a trusted Host - try { - const parsed = new URL(origin); - if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false; - const ohn = normalizeAdminHostname(parsed.hostname); - return ohn !== undefined && trustedHostnames.has(ohn); - } catch { - return false; - } +function isTrustedAdminOrigin( + origin: string | undefined, + host: string | undefined, + trustedHostnames: Set, +): boolean { + // Host must name one of OUR loopback identities regardless of whether an + // Origin header is present. A same-origin browser GET/fetch (the DNS + // rebinding read path: evil.com → 127.0.0.1) often carries NO Origin + // header, so gating on Origin alone would leave config reads exposed. + // #1537: match on the bare hostname and IGNORE the port — an SSH forward + // (ssh -L 18787:127.0.0.1:8787) legitimately presents a different local + // port while still arriving from loopback. The anti-rebinding property is + // preserved because an attacker's rebound domain (evil.com) can never equal + // a loopback NAME; only the port is relaxed. + const hn = normalizeAdminHostname(host); + if (!hn || !trustedHostnames.has(hn)) return false; + if (!origin) return true; // non-browser client (curl, CLI UI) on a trusted Host + try { + const parsed = new URL(origin); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") + return false; + const ohn = normalizeAdminHostname(parsed.hostname); + return ohn !== undefined && trustedHostnames.has(ohn); + } catch { + return false; + } } /** The set of hostnames we accept on management endpoints. DNS rebinding @@ -96,648 +165,1077 @@ function isTrustedAdminOrigin(origin: string | undefined, host: string | undefin * accepted Host carried a loopback hostname, so dropping the port admits no * non-loopback identity. */ function adminTrustedHostnames(bindHost: string): Set { - const names = ["localhost", "127.0.0.1", "::1"]; - const bound = normalizeAdminHostname(bindHost); - if (bound && bound !== "0.0.0.0" && bound !== "::" && !names.includes(bound)) { - names.push(bound); - } - return new Set(names); + const names = ["localhost", "127.0.0.1", "::1"]; + const bound = normalizeAdminHostname(bindHost); + if ( + bound && + bound !== "0.0.0.0" && + bound !== "::" && + !names.includes(bound) + ) { + names.push(bound); + } + return new Set(names); } // #2170 split-session canary: one log line per conversation base per process. const splitWarnedBases = new Set(); -export async function handleAdminRoute(req: http.IncomingMessage, res: http.ServerResponse, ctx: AdminCtx): Promise { - const { opts, core, config, log, instanceId, instanceStartedAt, proxyWatchers, initialWatcherPid } = ctx; - // SECURITY: the /__bili/ management endpoints (config read/write, reload, - // session stats) are privileged — a remote caller who can reach them can - // rewrite upstream routing to exfiltrate API keys (MITM). Restrict them - // to loopback connections. The proxy default host is 127.0.0.1 (loopback - // only), but a user can set --host 0.0.0.0 to share the proxy on a LAN — - // in that case we still must NOT expose management to the LAN. Only the - // proxy /bili/ and CONNECT (model traffic) endpoints remain open to all. - // #1073: an absolute-form request addressed to THIS instance's own endpoint - // is a fetch of us, not a tunnel — strip the authority so the admin gate - // below sees a normal origin-form request and answers with real health - // state instead of 403ing via the tunnel path. - const selfProbePath = selfAdminProbePath(req.url ?? "", req.socket.localPort); - if (selfProbePath !== undefined) req.url = selfProbePath; - const isAdminPath = req.url === "/__bili/" || req.url?.startsWith("/__bili/") || req.url === "/__acp/" || req.url?.startsWith("/__acp/"); - // #409: management must never be reachable THROUGH the bili tunnel, not - // even from a loopback client: the tunnel's inner connection originates - // from the proxy itself, so the remoteAddress gate alone is satisfied and - // a `--host 0.0.0.0` peer could otherwise PUT /__bili/config over the - // tunnel. forward() stamps this marker on every /bili/ absolute-URL - // forward; clients have no legitimate reason to send it, and a spoofed - // value only locks the spoofer out of admin paths. - if (isAdminPath && headerValue(req, BILI_TUNNEL_HEADER) !== undefined) { - res.writeHead(403, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: "management endpoints are not reachable through the bili tunnel" })); - return; - } - if (isAdminPath && !isLoopbackAddress(req.socket.remoteAddress)) { - res.writeHead(403, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: "management endpoints are loopback-only; access denied for " + (req.socket.remoteAddress ?? "unknown") })); - return; - } - // localPort, not opts.port: when listening on port 0 (dynamic assignment, - // programmatic embedding, tests) the real port differs from opts.port and - // pinning to the configured value would 403 every admin request. - if (isAdminPath && !isTrustedAdminOrigin(req.headers.origin, req.headers.host, adminTrustedHostnames(opts.host))) { - res.writeHead(403, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: "management request origin does not match the local bili UI" })); - return; - } - if (req.method === "GET" && req.url === "/__bili/stats") return sendStats(res); - if (req.method === "GET" && req.url?.startsWith("/__bili/cache-report")) return sendCacheReport(res, req.url); - if (req.method === "GET" && req.url === "/__bili/status") return sendStatus(res, opts); - if (req.method === "GET" && req.url === "/__bili/resign") return sendResignStatus(res); - if (req.method === "GET" && req.url === "/__bili/overview") return sendOverview(res, opts); - if (req.method === "GET" && (req.url === "/__bili/sessions" || req.url?.startsWith("/__bili/sessions?"))) return sendWebSessions(res, req); - if (req.method === "GET" && req.url?.startsWith("/__bili/logs")) return sendWebLogs(res, req); - if (req.method === "GET" && req.url?.startsWith("/__bili/sessions/") && req.url.endsWith("/detail")) return sendWebSessionDetail(res, req.url); - if (req.method === "GET" && req.url === "/") { - // Browser visits root → redirect to the web UI. curl / health probes - // (Accept: */* or no Accept) still get the JSON health check so - // existing scripts and Docker-style health probes keep working. - const accept = req.headers.accept ?? ""; - if (accept.includes("text/html")) { - res.writeHead(302, { location: "/__bili/" }); - res.end(); - return; - } - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, upstream: opts.upstream })); - return; - } - if (req.method === "GET" && req.url === "/__bili/health") { - res.writeHead(200, { "content-type": "application/json" }); - // #1322: watchdog state is part of the health contract — attachers and - // operators can see whether this proxy dies with its sessions (armed) - // or outlives them all (daemon squatting a stable port). - res.end(JSON.stringify({ ok: true, upstream: opts.upstream, version: VERSION, commit: BUILD_COMMIT, instanceId, pid: process.pid, startedAt: instanceStartedAt, blindTunnels: getBlindTunnelStats(), watchdog: { armed: initialWatcherPid !== null, parentPid: initialWatcherPid ?? undefined, watchers: [...proxyWatchers] } })); - return; - } - // Web config UI (served as HTML, separate from the JSON health check above). - // #2321: the bare path also tolerates a query (?embed=1&lang=…) — the dsh - // settings panel frames exactly this route. Every /__bili/ URL already - // passed the loopback/trusted-origin/tunnel gates above, so nothing opens. - if (req.method === "GET" && req.url !== undefined && (req.url === "/__bili/" || req.url.startsWith("/__bili/?"))) { - const u = new URL(req.url, "http://localhost"); - const origin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${opts.port}`; - // #2559: embedding hosts pin the face's palette explicitly (?theme= - // light|dark) because app-level host themes are invisible to the - // framed document's prefers-color-scheme. - const rawTheme = u.searchParams.get("theme"); - const theme = rawTheme === "light" || rawTheme === "dark" ? rawTheme : undefined; - res.writeHead(200, { "content-type": "text/html; charset=utf-8" }); - res.end(renderUI(origin, { embed: u.searchParams.get("embed") === "1", theme })); - return; - } - if (req.method === "GET" && req.url === "/__bili/config") return handleConfigGet(res); - if (req.method === "PUT" && req.url === "/__bili/config") { - return handleConfigPut(req, res, () => { - const fresh = loadOptions(); - if (fresh.passthrough !== opts.passthrough) { - log( - fresh.passthrough ? "warn" : "info", - `[passthrough] ${fresh.passthrough ? "compression turned OFF via web config — forwarding verbatim" : "compression re-enabled via web config"}`, - ); - } - opts.passthrough = fresh.passthrough; - opts.passthroughSource = fresh.passthroughSource; - if (fresh.allowDshCompaction !== opts.allowDshCompaction) { - log( - fresh.allowDshCompaction ? "warn" : "info", - `[dsh-compaction] ${fresh.allowDshCompaction ? "dsh native compaction ALLOWED via web config — landed checkpoints durably shadow the raw history (#2028)" : "dsh native compaction interception restored via web config (#2028)"}`, - ); - } - opts.allowDshCompaction = fresh.allowDshCompaction; - opts.proxy = fresh.proxy; - opts.proxyMode = fresh.proxyMode; - opts.proxySource = fresh.proxySource; - opts.proxyFallback = fresh.proxyFallback; - opts.auxProxyFallback = fresh.auxProxyFallback; - opts.compress = fresh.compress; - opts.compat = fresh.compat; - resetProxyCache(); - for (const k of Object.keys(opts.routes)) delete opts.routes[k]; - Object.assign(opts.routes, loadRoutes()); - opts.namedProviders ??= {}; - for (const k of Object.keys(opts.namedProviders)) delete opts.namedProviders[k]; - Object.assign(opts.namedProviders, loadNamedProviders()); - }, opts.port); - } - if (req.method === "POST" && req.url === "/__bili/config/reload") return handleConfigReload(opts, res, log); - // #2102: wipe the diagnostic conflict ledgers (global, or one session via - // ?session=). Loopback + trusted-origin gated like every /__bili/ path. - if (req.method === "POST" && req.url?.startsWith("/__bili/conflicts/clear")) return handleConflictsClear(req.url, res, log); - // #2861: silence a known host-side plugin notice for this environment. - if (req.method === "POST" && req.url === "/__bili/host-plugins/dismiss") return handleHostPluginDismiss(req, res, log); - if (req.method === "GET" && req.url === "/__bili/upstream") { - const target = opts.upstream; - const decision = resolveProxyDecision(opts.routes, opts.proxy, target, opts.proxyFallback); - const connection = getUpstreamConnectionStatus(); - const connectionMatchesTarget = (() => { - if (!connection.url) return false; - try { return new URL(connection.url).origin === new URL(target).origin; } catch { return false; } - })(); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ - target, - proxy: decision.proxy ?? null, - source: decision.source, - mode: opts.proxyMode ?? "auto", - autoConfigUrl: decision.autoConfigUrl ?? null, - connected: connectionMatchesTarget ? connection.connected : undefined, - error: connectionMatchesTarget ? connection.error : undefined, - checkedAt: connectionMatchesTarget ? connection.checkedAt : undefined, - connectionUrl: connection.url, - connectionProxy: connection.proxy, - })); - return; - } - if (req.method === "POST" && req.url === "/__bili/upstream/test") { - const target = opts.upstream; - const targetUrl = new URL(target).origin; - // Keep the whole decision: #2809's skippedProxy diagnostic rides on it. - const decision = resolveProxyDecision(opts.routes, opts.proxy, target, opts.proxyFallback); - const proxyUrl = decision.proxy; - try { - const result = await fetchWithTimeout(targetUrl, { - method: "HEAD", - redirect: "follow", - ...(proxyUrl ? { dispatcher: proxyDispatcher(proxyUrl, 15_000) } : {}), - }, 15_000); - result.clearTimer(); - recordUpstreamConnection(targetUrl, proxyUrl); - // #1682: a successful probe clears active alerts for this host so - // the banner reflects the fix immediately, without waiting for traffic. - clearUpstreamAlertsForHost(targetUrl); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, status: result.response.status, target: targetUrl, proxy: proxyUrl ?? null })); - } catch (error) { - // #1682: probe failures deliberately do NOT feed the alert table — - // they are user-initiated diagnostics, not live-traffic evidence. - recordUpstreamConnection(targetUrl, proxyUrl, error, decision.skippedProxy); - res.writeHead(502, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: formatUpstreamError(error, targetUrl, proxyUrl, decision.skippedProxy) })); - } - return; - } +export async function handleAdminRoute( + req: http.IncomingMessage, + res: http.ServerResponse, + ctx: AdminCtx, +): Promise { + const { + opts, + core, + config, + log, + instanceId, + instanceStartedAt, + proxyWatchers, + initialWatcherPid, + } = ctx; + // SECURITY: the /__bili/ management endpoints (config read/write, reload, + // session stats) are privileged — a remote caller who can reach them can + // rewrite upstream routing to exfiltrate API keys (MITM). Restrict them + // to loopback connections. The proxy default host is 127.0.0.1 (loopback + // only), but a user can set --host 0.0.0.0 to share the proxy on a LAN — + // in that case we still must NOT expose management to the LAN. Only the + // proxy /bili/ and CONNECT (model traffic) endpoints remain open to all. + // #1073: an absolute-form request addressed to THIS instance's own endpoint + // is a fetch of us, not a tunnel — strip the authority so the admin gate + // below sees a normal origin-form request and answers with real health + // state instead of 403ing via the tunnel path. + const selfProbePath = selfAdminProbePath(req.url ?? "", req.socket.localPort); + if (selfProbePath !== undefined) req.url = selfProbePath; + const isAdminPath = + req.url === "/__bili/" || + req.url?.startsWith("/__bili/") || + req.url === "/__acp/" || + req.url?.startsWith("/__acp/"); + // #409: management must never be reachable THROUGH the bili tunnel, not + // even from a loopback client: the tunnel's inner connection originates + // from the proxy itself, so the remoteAddress gate alone is satisfied and + // a `--host 0.0.0.0` peer could otherwise PUT /__bili/config over the + // tunnel. forward() stamps this marker on every /bili/ absolute-URL + // forward; clients have no legitimate reason to send it, and a spoofed + // value only locks the spoofer out of admin paths. + if (isAdminPath && headerValue(req, BILI_TUNNEL_HEADER) !== undefined) { + res.writeHead(403, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + error: "management endpoints are not reachable through the bili tunnel", + }), + ); + return; + } + if (isAdminPath && !isLoopbackAddress(req.socket.remoteAddress)) { + res.writeHead(403, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + error: + "management endpoints are loopback-only; access denied for " + + (req.socket.remoteAddress ?? "unknown"), + }), + ); + return; + } + // localPort, not opts.port: when listening on port 0 (dynamic assignment, + // programmatic embedding, tests) the real port differs from opts.port and + // pinning to the configured value would 403 every admin request. + if ( + isAdminPath && + !isTrustedAdminOrigin( + req.headers.origin, + req.headers.host, + adminTrustedHostnames(opts.host), + ) + ) { + res.writeHead(403, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + error: "management request origin does not match the local bili UI", + }), + ); + return; + } + if (req.method === "GET" && req.url === "/__bili/stats") + return sendStats(res); + if (req.method === "GET" && req.url?.startsWith("/__bili/cache-report")) + return sendCacheReport(res, req.url); + if (req.method === "GET" && req.url === "/__bili/status") + return sendStatus(res, opts); + if (req.method === "GET" && req.url === "/__bili/resign") + return sendResignStatus(res); + if (req.method === "GET" && req.url === "/__bili/overview") + return sendOverview(res, opts); + if ( + req.method === "GET" && + (req.url === "/__bili/sessions" || req.url?.startsWith("/__bili/sessions?")) + ) + return sendWebSessions(res, req); + if (req.method === "GET" && req.url?.startsWith("/__bili/logs")) + return sendWebLogs(res, req); + if ( + req.method === "GET" && + req.url?.startsWith("/__bili/sessions/") && + req.url.endsWith("/detail") + ) + return sendWebSessionDetail(res, req.url); + if (req.method === "GET" && req.url === "/") { + // Browser visits root → redirect to the web UI. curl / health probes + // (Accept: */* or no Accept) still get the JSON health check so + // existing scripts and Docker-style health probes keep working. + const accept = req.headers.accept ?? ""; + if (accept.includes("text/html")) { + res.writeHead(302, { location: "/__bili/" }); + res.end(); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, upstream: opts.upstream })); + return; + } + if (req.method === "GET" && req.url === "/__bili/health") { + res.writeHead(200, { "content-type": "application/json" }); + // #1322: watchdog state is part of the health contract — attachers and + // operators can see whether this proxy dies with its sessions (armed) + // or outlives them all (daemon squatting a stable port). + res.end( + JSON.stringify({ + ok: true, + upstream: opts.upstream, + version: VERSION, + commit: BUILD_COMMIT, + instanceId, + pid: process.pid, + startedAt: instanceStartedAt, + blindTunnels: getBlindTunnelStats(), + watchdog: { + armed: initialWatcherPid !== null, + parentPid: initialWatcherPid ?? undefined, + watchers: [...proxyWatchers], + }, + }), + ); + return; + } + // Web config UI (served as HTML, separate from the JSON health check above). + // #2321: the bare path also tolerates a query (?embed=1&lang=…) — the dsh + // settings panel frames exactly this route. Every /__bili/ URL already + // passed the loopback/trusted-origin/tunnel gates above, so nothing opens. + if ( + req.method === "GET" && + req.url !== undefined && + (req.url === "/__bili/" || req.url.startsWith("/__bili/?")) + ) { + const u = new URL(req.url, "http://localhost"); + const origin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${opts.port}`; + // #2559: embedding hosts pin the face's palette explicitly (?theme= + // light|dark) because app-level host themes are invisible to the + // framed document's prefers-color-scheme. + const rawTheme = u.searchParams.get("theme"); + const theme = + rawTheme === "light" || rawTheme === "dark" ? rawTheme : undefined; + res.writeHead(200, { "content-type": "text/html; charset=utf-8" }); + res.end( + renderUI(origin, { embed: u.searchParams.get("embed") === "1", theme }), + ); + return; + } + if (req.method === "GET" && req.url === "/__bili/config") + return handleConfigGet(res); + if (req.method === "PUT" && req.url === "/__bili/config") { + return handleConfigPut( + req, + res, + () => { + const fresh = loadOptions(); + if (fresh.passthrough !== opts.passthrough) { + log( + fresh.passthrough ? "warn" : "info", + `[passthrough] ${fresh.passthrough ? "compression turned OFF via web config — forwarding verbatim" : "compression re-enabled via web config"}`, + ); + } + opts.passthrough = fresh.passthrough; + opts.passthroughSource = fresh.passthroughSource; + if (fresh.allowDshCompaction !== opts.allowDshCompaction) { + log( + fresh.allowDshCompaction ? "warn" : "info", + `[dsh-compaction] ${fresh.allowDshCompaction ? "dsh native compaction ALLOWED via web config — landed checkpoints durably shadow the raw history (#2028)" : "dsh native compaction interception restored via web config (#2028)"}`, + ); + } + opts.allowDshCompaction = fresh.allowDshCompaction; + opts.proxy = fresh.proxy; + opts.proxyMode = fresh.proxyMode; + opts.proxySource = fresh.proxySource; + opts.proxyFallback = fresh.proxyFallback; + opts.auxProxyFallback = fresh.auxProxyFallback; + opts.compress = fresh.compress; + opts.compat = fresh.compat; + resetProxyCache(); + for (const k of Object.keys(opts.routes)) delete opts.routes[k]; + Object.assign(opts.routes, loadRoutes()); + opts.namedProviders ??= {}; + for (const k of Object.keys(opts.namedProviders)) + delete opts.namedProviders[k]; + Object.assign(opts.namedProviders, loadNamedProviders()); + }, + opts.port, + ); + } + if (req.method === "POST" && req.url === "/__bili/config/reload") + return handleConfigReload(opts, res, log); + // #2102: wipe the diagnostic conflict ledgers (global, or one session via + // ?session=). Loopback + trusted-origin gated like every /__bili/ path. + if (req.method === "POST" && req.url?.startsWith("/__bili/conflicts/clear")) + return handleConflictsClear(req.url, res, log); + // #2861: silence a known host-side plugin notice for this environment. + if (req.method === "POST" && req.url === "/__bili/host-plugins/dismiss") + return handleHostPluginDismiss(req, res, log); + if (req.method === "GET" && req.url === "/__bili/upstream") { + const target = opts.upstream; + const decision = resolveProxyDecision( + opts.routes, + opts.proxy, + target, + opts.proxyFallback, + ); + const connection = getUpstreamConnectionStatus(); + const connectionMatchesTarget = (() => { + if (!connection.url) return false; + try { + return new URL(connection.url).origin === new URL(target).origin; + } catch { + return false; + } + })(); + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + target, + proxy: decision.proxy ?? null, + source: decision.source, + mode: opts.proxyMode ?? "auto", + autoConfigUrl: decision.autoConfigUrl ?? null, + connected: connectionMatchesTarget ? connection.connected : undefined, + error: connectionMatchesTarget ? connection.error : undefined, + checkedAt: connectionMatchesTarget ? connection.checkedAt : undefined, + connectionUrl: connection.url, + connectionProxy: connection.proxy, + }), + ); + return; + } + if (req.method === "POST" && req.url === "/__bili/upstream/test") { + const target = opts.upstream; + const targetUrl = new URL(target).origin; + // Keep the whole decision: #2809's skippedProxy diagnostic rides on it. + const decision = resolveProxyDecision( + opts.routes, + opts.proxy, + target, + opts.proxyFallback, + ); + const proxyUrl = decision.proxy; + try { + const result = await fetchWithTimeout( + targetUrl, + { + method: "HEAD", + redirect: "follow", + ...(proxyUrl + ? { dispatcher: proxyDispatcher(proxyUrl, 15_000) } + : {}), + }, + 15_000, + ); + result.clearTimer(); + recordUpstreamConnection(targetUrl, proxyUrl); + // #1682: a successful probe clears active alerts for this host so + // the banner reflects the fix immediately, without waiting for traffic. + clearUpstreamAlertsForHost(targetUrl); + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: true, + status: result.response.status, + target: targetUrl, + proxy: proxyUrl ?? null, + }), + ); + } catch (error) { + // #1682: probe failures deliberately do NOT feed the alert table — + // they are user-initiated diagnostics, not live-traffic evidence. + recordUpstreamConnection( + targetUrl, + proxyUrl, + error, + decision.skippedProxy, + ); + res.writeHead(502, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + error: formatUpstreamError( + error, + targetUrl, + proxyUrl, + decision.skippedProxy, + ), + }), + ); + } + return; + } - // Cooperative plugin protocol (see src/plugin.ts + PLUGIN.md): the - // manifest serves the exact tool schemas the wire injector uses, and the - // tool endpoint lets an agent-side plugin execute compress/decompress/ - // search_context/acp_status against the session the plugin drives. Both - // live under the /__bili/ loopback + trusted-origin gate above. - if (req.method === "GET" && req.url === "/__bili/plugin/manifest") { - // [#1271/#1278] kernelConfig carries no file/global compress settings; resolve the - // GLOBAL view exactly like the request path does (applyCompressSettings) so every - // opt-in tool — acp_retrieve (#1271), absorb (#1278) — is advertised exactly when the - // operator enabled it at the global level. Unset fields floor to kernel defaults - // (DEFAULT_CCR_CONFIG et al. inside applyCompressSettings); per-request/route overrides - // are still enforced at execution time, so the manifest stays conservative as #1192 - // requires. Do not "simplify" this back to `config`. - return handlePluginManifest(res, applyCompressSettings(config, opts.modelContextLimit, opts.compress, { ...agentProviderRecipes(), ...opts.namedProviders ?? {} })); - } - if (req.method === "GET" && req.url?.split("?")[0] === "/__bili/plugin/snapshot") { - return await handlePluginSnapshot(new URL(req.url, "http://localhost").searchParams.get("conversationId") ?? "", res); - } - if (req.method === "POST" && req.url === "/__bili/plugin/fork") { - try { - return await handlePluginFork((await readBody(req)).toString("utf8"), res); - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, code: "INVALID_REQUEST", error: String(err) })); - return; - } - } - if (req.method === "GET" && req.url?.startsWith("/__bili/plugin/status")) { - const query = req.url.slice(req.url.indexOf("?") + 1); - const params = new URLSearchParams(query); - const conversationId = params.get("conversationId")?.trim() ?? ""; - if (!conversationId) { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "conversationId query parameter is required" })); - return; - } - // Web UI origin as the user's browser dials it: the ACTUAL bound port - // (req.socket.localPort differs from opts.port when listening on port 0). - const webOrigin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${req.socket?.localPort ?? opts.port}`; - return handlePluginStatus(conversationId, res, { core, config, log, webOrigin }, params.get("fallback") === "latest"); - } - if (req.method === "POST" && req.url === "/__bili/watcher") { - // #7: an ATTACHING claude session registers its host pid so the shared - // proxy outlives the first spawner's exit. Only proxies started in - // parent-watch mode (BILI_PARENT_PID) take watchers — daemons stay - // daemons, and a rejected registration leaves behavior unchanged. - try { - const body = await readBody(req); - const parsed = JSON.parse(body.toString("utf8")) as { pid?: unknown }; - const pid = parsed.pid; - if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 1 || pid === process.pid) { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "expected { pid: }" })); - } else if (initialWatcherPid === null) { - res.writeHead(409, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "watchdog not armed (no parent pid) — this proxy does not take watchers" })); - } else { - proxyWatchers.add(pid); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, watchers: proxyWatchers.size })); - } - return; - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - return; - } - } - // #2671 Phase 2: replica/checkpoint management over the unified store. - // Loopback-gated like every /__bili/ route; 501 in legacy mode so the - // operator knows the knob, not the URL, is what is missing. - if (req.method === "GET" && (req.url === "/__bili/replicas" || req.url?.startsWith("/__bili/replicas?"))) return await sendReplicasList(res, req.url); - if (req.method === "POST" && req.url === "/__bili/replicas") { - try { - const parsed = JSON.parse((await readBody(req)).toString("utf8")) as { sessionId?: unknown; label?: unknown; pinned?: unknown }; - if (typeof parsed.sessionId !== "string" || !parsed.sessionId) { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "expected { sessionId: string, label?: string, pinned?: boolean }" })); - return; - } - const store = getStore(); - if (!store.replicasAvailable()) { - res.writeHead(501, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full (or storage.unified in the config file)" })); - return; - } - // Freshest snapshot first: a resident session is force-flushed so - // the checkpoint freezes what the caller just saw, not the last - // debounced write. - const resident = peekSession(parsed.sessionId); - if (resident) await store.writeNow(resident); - try { - const row = store.createReplica(parsed.sessionId, { - label: typeof parsed.label === "string" ? parsed.label : undefined, - pinned: parsed.pinned === true, - }); - res.writeHead(201, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, replica: serializeReplica(row) })); - } catch (err) { - const msg = String(err); - res.writeHead(msg.includes("not in the unified index") ? 404 : 500, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: msg })); - } - return; - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - return; - } - } - if (req.method === "GET" && req.url?.startsWith("/__bili/replicas/") && !req.url.endsWith("/restore")) return await sendReplicaDetail(res, req.url); - if (req.method === "POST" && req.url?.startsWith("/__bili/replicas/") && req.url.endsWith("/restore")) { - try { - const cpId = replicaIdFromUrl(req.url, "/restore"); - if (!cpId) { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "expected /__bili/replicas//restore" })); - return; - } - const store = getStore(); - if (!store.replicasAvailable()) { - res.writeHead(501, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full" })); - return; - } - let newSessionId: string | undefined; - const raw = await readBody(req); - if (raw.byteLength > 0) { - const parsed = JSON.parse(raw.toString("utf8")) as { sessionId?: unknown }; - if (parsed.sessionId !== undefined && (typeof parsed.sessionId !== "string" || !parsed.sessionId)) { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "sessionId must be a non-empty string" })); - return; - } - newSessionId = parsed.sessionId as string | undefined; - } - try { - const out = await store.restoreReplica(cpId, { sessionId: newSessionId }); - res.writeHead(201, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, ...out })); - } catch (err) { - const msg = String(err); - const code = msg.includes("checkpoint not found") ? 404 : msg.includes("already exists") ? 409 : 500; - res.writeHead(code, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: msg })); - } - return; - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - return; - } - } - if (req.method === "DELETE" && req.url?.startsWith("/__bili/replicas/")) { - const cpId = replicaIdFromUrl(req.url); - if (!cpId) { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "expected /__bili/replicas/" })); - return; - } - const store = getStore(); - if (!store.replicasAvailable()) { - res.writeHead(501, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full" })); - return; - } - const deleted = store.deleteReplica(cpId); - res.writeHead(deleted ? 200 : 404, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: deleted, deleted })); - return; - } - if (req.method === "POST" && req.url === "/__bili/plugin/tool") { - try { - const body = await readBody(req); - const webOrigin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${req.socket?.localPort ?? opts.port}`; - return await handlePluginTool(body.toString("utf8"), res, { core, config, log, webOrigin }); - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - return; - } - } - if (req.method === "POST" && req.url === "/__bili/plugin/register") { - try { - const body = await readBody(req); - handlePluginRegister(body.toString("utf8"), res); - return; - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - return; - } - } - if (req.method === "POST" && req.url === "/__bili/agent-providers") { - // #2336 agent-registry fallback: a plugin host reports its dialing - // recipes (key bytes resolved in the agent's memory). Names only in - // the response — the key never crosses a log or GET surface. - // #2585: intake is per-entry — a refused entry is logged and named in - // the response instead of discarding the whole report. - try { - const body = await readBody(req); - const report = parseAgentProviderReport(JSON.parse(body.toString("utf8"))); - recordAgentProviders(report.agent, report.registered); - const names = Object.keys(report.registered).sort(); - log("info", `[agent-providers] ${report.agent} registered: ${names.join(", ") || "(none)"} (#2336)`); - for (const s of report.skipped) log("warn", `[agent-providers] ${report.agent} skipped ${s.name}: ${s.reason} (this provider stays unresolved) (#2585)`); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, agent: report.agent, registered: names, skipped: report.skipped })); - return; - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - log("warn", `[agent-providers] report rejected: ${sanitizeAgentProviderField(msg, 200)} (#2585)`); - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: msg })); - return; - } - } - if (req.method === "POST" && req.url === "/__bili/plugin/runtime-info") { - try { - const body = await readBody(req); - handlePluginRuntimeInfo(body.toString("utf8"), res); - return; - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - return; - } - } - if (req.method === "POST" && req.url === "/__bili/plugin/compact") { - try { - const body = await readBody(req); - handlePluginCompact(body.toString("utf8"), res); - return; - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - return; - } - } - if (req.method === "POST" && req.url === "/__bili/plugin/session-name") { - // #2322: host-provided conversation name (pi /name) — becomes the - // session's display title in the web UI (clear = empty string). - try { - const body = await readBody(req); - handlePluginSessionName(body.toString("utf8"), res); - return; - } catch (err) { - res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - return; - } - } - // Unknown /__bili/ or /__acp/ path → 404 locally. These are bili's own - // management prefixes; forwarding would leak the internal path to the - // upstream (which 403s it) — #346. - if (isAdminPath) { - res.writeHead(404, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: { type: "not_found", message: "no such management endpoint" } })); - return; - } + // Cooperative plugin protocol (see src/plugin.ts + PLUGIN.md): the + // manifest serves the exact tool schemas the wire injector uses, and the + // tool endpoint lets an agent-side plugin execute compress/decompress/ + // search_context/acp_status against the session the plugin drives. Both + // live under the /__bili/ loopback + trusted-origin gate above. + if (req.method === "GET" && req.url === "/__bili/plugin/manifest") { + // [#1271/#1278] kernelConfig carries no file/global compress settings; resolve the + // GLOBAL view exactly like the request path does (applyCompressSettings) so every + // opt-in tool — acp_retrieve (#1271), absorb (#1278) — is advertised exactly when the + // operator enabled it at the global level. Unset fields floor to kernel defaults + // (DEFAULT_CCR_CONFIG et al. inside applyCompressSettings); per-request/route overrides + // are still enforced at execution time, so the manifest stays conservative as #1192 + // requires. Do not "simplify" this back to `config`. + return handlePluginManifest( + res, + applyCompressSettings(config, opts.modelContextLimit, opts.compress, { + ...agentProviderRecipes(), + ...(opts.namedProviders ?? {}), + }), + ); + } + if ( + req.method === "GET" && + req.url?.split("?")[0] === "/__bili/plugin/snapshot" + ) { + return await handlePluginSnapshot( + new URL(req.url, "http://localhost").searchParams.get("conversationId") ?? + "", + res, + ); + } + if (req.method === "POST" && req.url === "/__bili/plugin/fork") { + try { + return await handlePluginFork( + (await readBody(req)).toString("utf8"), + res, + ); + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end( + JSON.stringify({ + ok: false, + code: "INVALID_REQUEST", + error: String(err), + }), + ); + return; + } + } + if (req.method === "GET" && req.url?.startsWith("/__bili/plugin/status")) { + const query = req.url.slice(req.url.indexOf("?") + 1); + const params = new URLSearchParams(query); + const conversationId = params.get("conversationId")?.trim() ?? ""; + if (!conversationId) { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: "conversationId query parameter is required", + }), + ); + return; + } + // Web UI origin as the user's browser dials it: the ACTUAL bound port + // (req.socket.localPort differs from opts.port when listening on port 0). + const webOrigin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${req.socket?.localPort ?? opts.port}`; + return handlePluginStatus( + conversationId, + res, + { core, config, log, webOrigin }, + params.get("fallback") === "latest", + ); + } + if (req.method === "POST" && req.url === "/__bili/watcher") { + // #7: an ATTACHING claude session registers its host pid so the shared + // proxy outlives the first spawner's exit. Only proxies started in + // parent-watch mode (BILI_PARENT_PID) take watchers — daemons stay + // daemons, and a rejected registration leaves behavior unchanged. + try { + const body = await readBody(req); + const parsed = JSON.parse(body.toString("utf8")) as { pid?: unknown }; + const pid = parsed.pid; + if ( + typeof pid !== "number" || + !Number.isInteger(pid) || + pid <= 1 || + pid === process.pid + ) { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify({ ok: false, error: "expected { pid: }" }), + ); + } else if (initialWatcherPid === null) { + res.writeHead(409, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: + "watchdog not armed (no parent pid) — this proxy does not take watchers", + }), + ); + } else { + proxyWatchers.add(pid); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, watchers: proxyWatchers.size })); + } + return; + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + return; + } + } + // #2671 Phase 2: replica/checkpoint management over the unified store. + // Loopback-gated like every /__bili/ route; 501 in legacy mode so the + // operator knows the knob, not the URL, is what is missing. + if ( + req.method === "GET" && + (req.url === "/__bili/replicas" || req.url?.startsWith("/__bili/replicas?")) + ) + return await sendReplicasList(res, req.url); + if (req.method === "POST" && req.url === "/__bili/replicas") { + try { + const parsed = JSON.parse((await readBody(req)).toString("utf8")) as { + sessionId?: unknown; + label?: unknown; + pinned?: unknown; + }; + if (typeof parsed.sessionId !== "string" || !parsed.sessionId) { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: + "expected { sessionId: string, label?: string, pinned?: boolean }", + }), + ); + return; + } + const store = getStore(); + if (!store.replicasAvailable()) { + res.writeHead(501, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: + "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full (or storage.unified in the config file)", + }), + ); + return; + } + // Freshest snapshot first: a resident session is force-flushed so + // the checkpoint freezes what the caller just saw, not the last + // debounced write. + const resident = peekSession(parsed.sessionId); + if (resident) await store.writeNow(resident); + try { + const row = store.createReplica(parsed.sessionId, { + label: typeof parsed.label === "string" ? parsed.label : undefined, + pinned: parsed.pinned === true, + }); + res.writeHead(201, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, replica: serializeReplica(row) })); + } catch (err) { + const msg = String(err); + res.writeHead(msg.includes("not in the unified index") ? 404 : 500, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: msg })); + } + return; + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + return; + } + } + if ( + req.method === "GET" && + req.url?.startsWith("/__bili/replicas/") && + !req.url.endsWith("/restore") + ) + return await sendReplicaDetail(res, req.url); + if ( + req.method === "POST" && + req.url?.startsWith("/__bili/replicas/") && + req.url.endsWith("/restore") + ) { + try { + const cpId = replicaIdFromUrl(req.url, "/restore"); + if (!cpId) { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: "expected /__bili/replicas//restore", + }), + ); + return; + } + const store = getStore(); + if (!store.replicasAvailable()) { + res.writeHead(501, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: + "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full", + }), + ); + return; + } + let newSessionId: string | undefined; + const raw = await readBody(req); + if (raw.byteLength > 0) { + const parsed = JSON.parse(raw.toString("utf8")) as { + sessionId?: unknown; + }; + if ( + parsed.sessionId !== undefined && + (typeof parsed.sessionId !== "string" || !parsed.sessionId) + ) { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: "sessionId must be a non-empty string", + }), + ); + return; + } + newSessionId = parsed.sessionId as string | undefined; + } + try { + const out = await store.restoreReplica(cpId, { + sessionId: newSessionId, + }); + res.writeHead(201, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, ...out })); + } catch (err) { + const msg = String(err); + const code = msg.includes("checkpoint not found") + ? 404 + : msg.includes("already exists") + ? 409 + : 500; + res.writeHead(code, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: false, error: msg })); + } + return; + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + return; + } + } + if (req.method === "DELETE" && req.url?.startsWith("/__bili/replicas/")) { + const cpId = replicaIdFromUrl(req.url); + if (!cpId) { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: "expected /__bili/replicas/", + }), + ); + return; + } + const store = getStore(); + if (!store.replicasAvailable()) { + res.writeHead(501, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: + "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full", + }), + ); + return; + } + const deleted = store.deleteReplica(cpId); + res.writeHead(deleted ? 200 : 404, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: deleted, deleted })); + return; + } + if (req.method === "POST" && req.url === "/__bili/plugin/tool") { + try { + const body = await readBody(req); + const webOrigin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${req.socket?.localPort ?? opts.port}`; + return await handlePluginTool(body.toString("utf8"), res, { + core, + config, + log, + webOrigin, + }); + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + return; + } + } + if (req.method === "POST" && req.url === "/__bili/plugin/register") { + try { + const body = await readBody(req); + handlePluginRegister(body.toString("utf8"), res); + return; + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + return; + } + } + if (req.method === "POST" && req.url === "/__bili/agent-providers") { + // #2336 agent-registry fallback: a plugin host reports its dialing + // recipes (key bytes resolved in the agent's memory). Names only in + // the response — the key never crosses a log or GET surface. + // #2585: intake is per-entry — a refused entry is logged and named in + // the response instead of discarding the whole report. + try { + const body = await readBody(req); + const report = parseAgentProviderReport( + JSON.parse(body.toString("utf8")), + ); + recordAgentProviders(report.agent, report.registered); + const names = Object.keys(report.registered).sort(); + log( + "info", + `[agent-providers] ${report.agent} registered: ${names.join(", ") || "(none)"} (#2336)`, + ); + for (const s of report.skipped) + log( + "warn", + `[agent-providers] ${report.agent} skipped ${s.name}: ${s.reason} (this provider stays unresolved) (#2585)`, + ); + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: true, + agent: report.agent, + registered: names, + skipped: report.skipped, + }), + ); + return; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + log( + "warn", + `[agent-providers] report rejected: ${sanitizeAgentProviderField(msg, 200)} (#2585)`, + ); + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: msg })); + return; + } + } + if (req.method === "POST" && req.url === "/__bili/plugin/runtime-info") { + try { + const body = await readBody(req); + handlePluginRuntimeInfo(body.toString("utf8"), res); + return; + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + return; + } + } + if (req.method === "POST" && req.url === "/__bili/plugin/compact") { + try { + const body = await readBody(req); + handlePluginCompact(body.toString("utf8"), res); + return; + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + return; + } + } + if (req.method === "POST" && req.url === "/__bili/plugin/session-name") { + // #2322: host-provided conversation name (pi /name) — becomes the + // session's display title in the web UI (clear = empty string). + try { + const body = await readBody(req); + handlePluginSessionName(body.toString("utf8"), res); + return; + } catch (err) { + res.writeHead(err instanceof BodyTooLargeError ? 413 : 400, { + "content-type": "application/json", + }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + return; + } + } + // Unknown /__bili/ or /__acp/ path → 404 locally. These are bili's own + // management prefixes; forwarding would leak the internal path to the + // upstream (which 403s it) — #346. + if (isAdminPath) { + res.writeHead(404, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + error: { type: "not_found", message: "no such management endpoint" }, + }), + ); + return; + } } -function handleConfigReload(opts: ProxyOptions, res: http.ServerResponse, log: (level: string, msg: string) => void): void { - // Hot-reload routes from the config file into the running process — no - // restart needed. Routes and the global compress block are re-read; - // port/host/upstream stay as-is (the listen socket is already bound). - // Mutates opts.routes in place so all in-flight handle() closures that - // captured `opts` see the new routes. - const fresh = loadRoutes(); - // Clear and refill the SAME object reference so resolveUpstream/resolveContextLimit - // (which read opts.routes) pick up the new entries without needing reassignment. - for (const k of Object.keys(opts.routes)) delete opts.routes[k]; - Object.assign(opts.routes, fresh); - opts.namedProviders ??= {}; - for (const k of Object.keys(opts.namedProviders)) delete opts.namedProviders[k]; - Object.assign(opts.namedProviders, loadNamedProviders()); - const reloaded = loadOptions(); - opts.compress = reloaded.compress; - opts.compat = reloaded.compat; - opts.imageBilling = reloaded.imageBilling; - opts.imageTokenCap = reloaded.imageTokenCap; - // Release cached ProxyAgents so agents for proxy URLs that were - // removed/changed don't leak for the process lifetime. The next request - // re-creates the needed agent lazily via proxyDispatcher(). - resetProxyCache(); - const names = Object.keys(fresh); - log("info", `[acp-web] routes hot-reloaded (${names.length} providers): ${names.join(", ") || "(none)"}`); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, count: names.length, routes: names })); +function handleConfigReload( + opts: ProxyOptions, + res: http.ServerResponse, + log: (level: string, msg: string) => void, +): void { + // Hot-reload routes from the config file into the running process — no + // restart needed. Routes and the global compress block are re-read; + // port/host/upstream stay as-is (the listen socket is already bound). + // Mutates opts.routes in place so all in-flight handle() closures that + // captured `opts` see the new routes. + const fresh = loadRoutes(); + // Clear and refill the SAME object reference so resolveUpstream/resolveContextLimit + // (which read opts.routes) pick up the new entries without needing reassignment. + for (const k of Object.keys(opts.routes)) delete opts.routes[k]; + Object.assign(opts.routes, fresh); + opts.namedProviders ??= {}; + for (const k of Object.keys(opts.namedProviders)) + delete opts.namedProviders[k]; + Object.assign(opts.namedProviders, loadNamedProviders()); + const reloaded = loadOptions(); + opts.compress = reloaded.compress; + opts.compat = reloaded.compat; + opts.imageBilling = reloaded.imageBilling; + opts.imageTokenCap = reloaded.imageTokenCap; + // Release cached ProxyAgents so agents for proxy URLs that were + // removed/changed don't leak for the process lifetime. The next request + // re-creates the needed agent lazily via proxyDispatcher(). + resetProxyCache(); + const names = Object.keys(fresh); + log( + "info", + `[acp-web] routes hot-reloaded (${names.length} providers): ${names.join(", ") || "(none)"}`, + ); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, count: names.length, routes: names })); } function sendCacheReport(res: http.ServerResponse, url: string): void { - const sessionParam = new URL(url, "http://localhost").searchParams.get("session"); - let sessions = listSessions(); - if (sessionParam !== null) { - const hit = sessions.filter((s) => s.id === sessionParam); - if (hit.length === 0) { - res.writeHead(404, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: `unknown session: ${sessionParam}` })); - return; - } - sessions = hit; - } else { - sessions = sessions.slice().sort((a, b) => b.lastSeen - a.lastSeen); - } - res.writeHead(200, { "content-type": "application/json" }); - // Same markdown the acp_cache MCP tool emits (handleAcpCache = formatCacheReport), - // so web copy/download matches /acp-cache output exactly. - res.end(JSON.stringify({ reports: sessions.map((s) => ({ id: s.id, report: handleAcpCache(s, { detail: "full" }).text })) }, null, 2)); + const sessionParam = new URL(url, "http://localhost").searchParams.get( + "session", + ); + let sessions = listSessions(); + if (sessionParam !== null) { + const hit = sessions.filter((s) => s.id === sessionParam); + if (hit.length === 0) { + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: `unknown session: ${sessionParam}` })); + return; + } + sessions = hit; + } else { + sessions = sessions.slice().sort((a, b) => b.lastSeen - a.lastSeen); + } + res.writeHead(200, { "content-type": "application/json" }); + // Same markdown the acp_cache MCP tool emits (handleAcpCache = formatCacheReport), + // so web copy/download matches /acp-cache output exactly. + res.end( + JSON.stringify( + { + reports: sessions.map((s) => ({ + id: s.id, + report: handleAcpCache(s, { detail: "full" }).text, + })), + }, + null, + 2, + ), + ); } // #2102: wipe diagnostic conflict ledgers — global, or one session via ?session=. // Gated by the /__bili/* admin gate above (loopback + trusted origin only); // wiping loses no conversation data, only the evidence notes (#1206 design). -function handleConflictsClear(url: string, res: http.ServerResponse, log: (level: string, msg: string) => void): void { - const sessionId = new URL(url, "http://localhost").searchParams.get("session"); - const sessions = listSessions(); - if (sessionId !== null && sessionId !== "" && !sessions.some((s) => s.id === sessionId)) { - res.writeHead(404, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: `unknown session: ${sessionId}` }, null, 2)); - return; - } - const cleared = clearConflictEvents(sessions, sessionId || undefined); - log("info", `[conflict] ledger cleared via web UI: ${cleared.events} event(s) across ${cleared.sessions} session(s)${sessionId ? ` (session ${sessionId})` : ""}`); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, cleared }, null, 2)); +function handleConflictsClear( + url: string, + res: http.ServerResponse, + log: (level: string, msg: string) => void, +): void { + const sessionId = new URL(url, "http://localhost").searchParams.get( + "session", + ); + const sessions = listSessions(); + if ( + sessionId !== null && + sessionId !== "" && + !sessions.some((s) => s.id === sessionId) + ) { + res.writeHead(404, { "content-type": "application/json" }); + res.end( + JSON.stringify({ error: `unknown session: ${sessionId}` }, null, 2), + ); + return; + } + const cleared = clearConflictEvents(sessions, sessionId || undefined); + log( + "info", + `[conflict] ledger cleared via web UI: ${cleared.events} event(s) across ${cleared.sessions} session(s)${sessionId ? ` (session ${sessionId})` : ""}`, + ); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, cleared }, null, 2)); } // #2861: server-side dismissal of a host-plugin notice (body {"id": string}). -async function handleHostPluginDismiss(req: http.IncomingMessage, res: http.ServerResponse, log: (level: string, msg: string) => void): Promise { - let id = ""; - try { - const doc: unknown = JSON.parse((await readBody(req)).toString("utf8")); - if (doc && typeof doc === "object" && typeof (doc as { id?: unknown })["id"] === "string") id = (doc as { id: string })["id"]; - } catch { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: 'expected JSON body {"id": ""}' }, null, 2)); - return; - } - if (!dismissHostPlugin(id)) { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: `unknown host plugin notice: ${id}` }, null, 2)); - return; - } - log("info", `[host-plugin] notice ${id} dismissed via web UI`); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true }, null, 2)); +async function handleHostPluginDismiss( + req: http.IncomingMessage, + res: http.ServerResponse, + log: (level: string, msg: string) => void, +): Promise { + let id = ""; + try { + const doc: unknown = JSON.parse((await readBody(req)).toString("utf8")); + if ( + doc && + typeof doc === "object" && + typeof (doc as { id?: unknown })["id"] === "string" + ) + id = (doc as { id: string })["id"]; + } catch { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify( + { error: 'expected JSON body {"id": ""}' }, + null, + 2, + ), + ); + return; + } + if (!dismissHostPlugin(id)) { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify({ error: `unknown host plugin notice: ${id}` }, null, 2), + ); + return; + } + log("info", `[host-plugin] notice ${id} dismissed via web UI`); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true }, null, 2)); } // ---- #2671 Phase 2: replica (checkpoint) helpers -------------------------- /** checkpoints row (snake_case) → HTTP payload (camelCase). */ function serializeReplica(row: { - cp_id: string; - session_id: string; - seq_at: number; - block_set_hash: string; - kind: string; - created_at: number; - pinned: number; - label: string | null; -}): { cpId: string; sessionId: string; seqAt: number; blockSetHash: string; kind: string; createdAt: number; pinned: boolean; label: string | null } { - return { cpId: row.cp_id, sessionId: row.session_id, seqAt: row.seq_at, blockSetHash: row.block_set_hash, kind: row.kind, createdAt: row.created_at, pinned: row.pinned === 1, label: row.label }; + cp_id: string; + session_id: string; + seq_at: number; + block_set_hash: string; + kind: string; + created_at: number; + pinned: number; + label: string | null; +}): { + cpId: string; + sessionId: string; + seqAt: number; + blockSetHash: string; + kind: string; + createdAt: number; + pinned: boolean; + label: string | null; +} { + return { + cpId: row.cp_id, + sessionId: row.session_id, + seqAt: row.seq_at, + blockSetHash: row.block_set_hash, + kind: row.kind, + createdAt: row.created_at, + pinned: row.pinned === 1, + label: row.label, + }; } function replicaIdFromUrl(url: string, suffix = ""): string | null { - const id = url.slice("/__bili/replicas/".length, url.length - suffix.length); - return id && !id.includes("/") ? decodeURIComponent(id) : null; + const id = url.slice("/__bili/replicas/".length, url.length - suffix.length); + return id && !id.includes("/") ? decodeURIComponent(id) : null; } -async function sendReplicasList(res: http.ServerResponse, url: string): Promise { - const store = getStore(); - if (!store.replicasAvailable()) { - res.writeHead(501, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full" })); - return; - } - const q = new URL(url, "http://localhost").searchParams.get("sessionId"); - const rows = store.listReplicas(q ?? undefined); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, replicas: rows.map(serializeReplica) }, null, 2)); +async function sendReplicasList( + res: http.ServerResponse, + url: string, +): Promise { + const store = getStore(); + if (!store.replicasAvailable()) { + res.writeHead(501, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: + "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full", + }), + ); + return; + } + const q = new URL(url, "http://localhost").searchParams.get("sessionId"); + const rows = store.listReplicas(q ?? undefined); + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify({ ok: true, replicas: rows.map(serializeReplica) }, null, 2), + ); } -async function sendReplicaDetail(res: http.ServerResponse, url: string): Promise { - const store = getStore(); - if (!store.replicasAvailable()) { - res.writeHead(501, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full" })); - return; - } - const cpId = replicaIdFromUrl(url); - if (!cpId) { - res.writeHead(400, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "expected /__bili/replicas/" })); - return; - } - try { - const row = store.listReplicas().find((r) => r.cp_id === cpId); - if (!row) { - res.writeHead(404, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: `checkpoint not found: ${cpId}` })); - return; - } - const byteLen = store.replicaByteLen(cpId); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, replica: { ...serializeReplica(row), byteLen } }, null, 2)); - } catch (err) { - res.writeHead(500, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: String(err) })); - } +async function sendReplicaDetail( + res: http.ServerResponse, + url: string, +): Promise { + const store = getStore(); + if (!store.replicasAvailable()) { + res.writeHead(501, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + ok: false, + error: + "replicas require the unified store — start this instance with BILI_STORAGE_UNIFIED=shadow|full", + }), + ); + return; + } + const cpId = replicaIdFromUrl(url); + if (!cpId) { + res.writeHead(400, { "content-type": "application/json" }); + res.end( + JSON.stringify({ ok: false, error: "expected /__bili/replicas/" }), + ); + return; + } + try { + const row = store.listReplicas().find((r) => r.cp_id === cpId); + if (!row) { + res.writeHead(404, { "content-type": "application/json" }); + res.end( + JSON.stringify({ ok: false, error: `checkpoint not found: ${cpId}` }), + ); + return; + } + const byteLen = store.replicaByteLen(cpId); + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify( + { ok: true, replica: { ...serializeReplica(row), byteLen } }, + null, + 2, + ), + ); + } catch (err) { + res.writeHead(500, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: false, error: String(err) })); + } } function sendStats(res: http.ServerResponse): void { - const all = listSessions(); - const sessions = all.map((s) => { - const sw = readModelSwitchStats(s); - const ks = readKeySwitchStats(s); - const ps = readPromptSwitchStats(s); - const js = readProjSwitchStats(s); - return { - id: s.id, - protocol: s.meta.protocol, - upstream: s.meta.upstreamOrigin, - label: s.meta.label, - title: s.meta.hostTitle ?? s.meta.title, - requests: s.stats.requests, - contextTokens: s.stats.contextTokens, - contextTokensSource: s.stats.contextTokensSource, - inputTokens: s.stats.inputTokens, - cachedTokens: s.stats.cachedTokens, - outputTokens: s.stats.outputTokens, - cacheSamples: s.stats.cacheSamples, - cacheHitPct: s.stats.cacheSamples > 0 && s.stats.inputTokens > 0 ? Math.round(s.stats.cachedTokens / s.stats.inputTokens * 100) : null, - lastModel: typeof s.metadata.lastModel === "string" ? s.metadata.lastModel : undefined, - modelSwitches: sw?.count ?? 0, - switchMissedTokens: sw?.missedTokens ?? 0, - keySwitches: ks?.count ?? 0, - keySwitchMissedTokens: ks?.missedTokens ?? 0, - promptSwitches: ps?.count ?? 0, - promptSwitchMissedTokens: ps?.missedTokens ?? 0, - projSwitches: js?.count ?? 0, - projSwitchMissedTokens: js?.missedTokens ?? 0, - // #901: window credibility — trusted (configured/registry) window vs the - // largest input recent successful turns actually got through. A wide gap - // means the provider overstates its window. - contextWindow: typeof s.metadata.effectiveContextLimit === "number" ? s.metadata.effectiveContextLimit : undefined, - lastSeen: new Date(s.lastSeen).toISOString(), - restored: s.restored === true, - }; - }); - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ sessions, blindTunnels: getBlindTunnelStats(), unrecognizedPaths: getUnrecognizedPathStats(), conflicts: summarizeConflicts(all) }, null, 2)); + const all = listSessions(); + const sessions = all.map((s) => { + const sw = readModelSwitchStats(s); + const ks = readKeySwitchStats(s); + const ps = readPromptSwitchStats(s); + const js = readProjSwitchStats(s); + return { + id: s.id, + codexClient: + typeof s.metadata.clientHint === "string" && + isCodexClient({ "user-agent": s.metadata.clientHint }), + protocol: s.meta.protocol, + upstream: s.meta.upstreamOrigin, + label: s.meta.label, + title: s.meta.hostTitle ?? s.meta.title, + requests: s.stats.requests, + lastSeenMs: s.lastSeen, + contextTokens: s.stats.contextTokens, + contextTokensSource: s.stats.contextTokensSource, + inputTokens: s.stats.inputTokens, + cachedTokens: s.stats.cachedTokens, + outputTokens: s.stats.outputTokens, + cacheSamples: s.stats.cacheSamples, + cacheHitPct: + s.stats.cacheSamples > 0 && s.stats.inputTokens > 0 + ? Math.round((s.stats.cachedTokens / s.stats.inputTokens) * 100) + : null, + lastModel: + typeof s.metadata.lastModel === "string" + ? s.metadata.lastModel + : undefined, + modelSwitches: sw?.count ?? 0, + switchMissedTokens: sw?.missedTokens ?? 0, + keySwitches: ks?.count ?? 0, + keySwitchMissedTokens: ks?.missedTokens ?? 0, + promptSwitches: ps?.count ?? 0, + promptSwitchMissedTokens: ps?.missedTokens ?? 0, + projSwitches: js?.count ?? 0, + projSwitchMissedTokens: js?.missedTokens ?? 0, + // #901: window credibility — trusted (configured/registry) window vs the + // largest input recent successful turns actually got through. A wide gap + // means the provider overstates its window. + contextWindow: + typeof s.metadata.effectiveContextLimit === "number" + ? s.metadata.effectiveContextLimit + : undefined, + lastSeen: new Date(s.lastSeen).toISOString(), + // Native Codex requests carry no explicit client header, so absent + // evidence is reported as "unknown" rather than `false`: readers + // (bili doctor) must not treat a missing hint as proof that the + // session is not Codex's (#ticket 03). + clientHint: + typeof s.metadata.clientHint === "string" + ? s.metadata.clientHint + : null, + restored: s.restored === true, + }; + }); + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify( + { + sessions, + blindTunnels: getBlindTunnelStats(), + unrecognizedPaths: getUnrecognizedPathStats(), + conflicts: summarizeConflicts(all), + }, + null, + 2, + ), + ); } /** #2152: the `advisory` field exposed by BOTH /__bili/status and /__bili/overview — @@ -746,8 +1244,10 @@ function sendStats(res: http.ServerResponse): void { * null when no advisory is active; otherwise the active entry plus targetFailed * (pinned target unresolvable on the registry → banner falls back to @latest). */ function currentAdvisoryPayload() { - const adv = getAdvisoryState(); - return adv.active ? { ...adv.active, targetFailed: cannotResolveTarget(adv.lastError) } : null; + const adv = getAdvisoryState(); + return adv.active + ? { ...adv.active, targetFailed: cannotResolveTarget(adv.lastError) } + : null; } /** Stale-install state for the web UI badge (#811): whether the on-disk @@ -763,184 +1263,295 @@ function currentAdvisoryPayload() { // carries the MINIMUM fixed version so every locale can say "v{version} 或更新版本 / // v{version} or newer". null when the span is invisible (routine/recommended- // only or clean install — silent by default, #1977). -function updateReadyPayload(): { kind: "available" | "ready"; version: string; summary: string } | null { - return updateBannerPayload(getUpdateVisibility(VERSION)); +function updateReadyPayload(): { + kind: "available" | "ready"; + version: string; + summary: string; +} | null { + return updateBannerPayload(getUpdateVisibility(VERSION)); } -async function sendStatus(res: http.ServerResponse, opts: ProxyOptions): Promise { - let diskVersion: string | undefined; - let stale = false; - try { - ({ diskVersion, stale } = await detectStaleInstall(PACKAGE_NAME, VERSION)); - } catch { - // fs hiccup: report running state only, never fail the status endpoint - } - res.writeHead(200, { "content-type": "application/json" }); - const splitWarnings = splitSessionWarnings(listSessions()); - for (const w of splitWarnings) { - if (!splitWarnedBases.has(w.base)) { - splitWarnedBases.add(w.base); - loggerLog("warn", `split-session canary (#2170): conversation ${w.base} has live traffic under multiple session keys (design persona forks are excluded): ${w.sessions.map((s) => `${s.id} (requests=${s.requests})`).join("; ")}. For a non-persona host this is the #2165 failure shape (stolen anchor / never-compressing split) — investigate if unexpected.`); - } - } - res.end(JSON.stringify({ version: VERSION, commit: BUILD_COMMIT, diskVersion, stale, updateReady: updateReadyPayload(), autoRestartOnUpdate: opts.autoRestartOnUpdate, advisory: currentAdvisoryPayload(), pluginAdvisories: detectCostAdvisories(process.env), inFlight: totalInFlight(), splitSessions: splitWarnings, conflicts: summarizeConflicts(listSessions()) }, null, 2)); +async function sendStatus( + res: http.ServerResponse, + opts: ProxyOptions, +): Promise { + let diskVersion: string | undefined; + let stale = false; + try { + ({ diskVersion, stale } = await detectStaleInstall(PACKAGE_NAME, VERSION)); + } catch { + // fs hiccup: report running state only, never fail the status endpoint + } + res.writeHead(200, { "content-type": "application/json" }); + const splitWarnings = splitSessionWarnings(listSessions()); + for (const w of splitWarnings) { + if (!splitWarnedBases.has(w.base)) { + splitWarnedBases.add(w.base); + loggerLog( + "warn", + `split-session canary (#2170): conversation ${w.base} has live traffic under multiple session keys (design persona forks are excluded): ${w.sessions.map((s) => `${s.id} (requests=${s.requests})`).join("; ")}. For a non-persona host this is the #2165 failure shape (stolen anchor / never-compressing split) — investigate if unexpected.`, + ); + } + } + res.end( + JSON.stringify( + { + version: VERSION, + commit: BUILD_COMMIT, + diskVersion, + stale, + updateReady: updateReadyPayload(), + autoRestartOnUpdate: opts.autoRestartOnUpdate, + advisory: currentAdvisoryPayload(), + pluginAdvisories: detectCostAdvisories(process.env), + inFlight: totalInFlight(), + splitSessions: splitWarnings, + conflicts: summarizeConflicts(listSessions()), + }, + null, + 2, + ), + ); } // #2090 plan A — read-only view backing the web UI's "Signed upstreams" card: // every known/observed signature scheme with its current effective policy, // plus the remembered refusals and which of them are still unresolved. function sendResignStatus(res: http.ServerResponse): void { - const names = new Set([...Object.keys(KNOWN_SIGNATURE_SCHEMES), ...Object.keys(readPendingRefusals())]); - const schemes: Record = {}; - for (const name of [...names].sort()) { - const st = resolveResignSettings(process.env, undefined, name); - schemes[name] = { known: KNOWN_SIGNATURE_SCHEMES[name], builtIn: name === APIG_RESIGN_SCHEME, enabled: st.enabled, passthrough: st.passthrough, passthroughApplies: name === APIG_RESIGN_SCHEME }; - } - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ - builtinScheme: APIG_RESIGN_SCHEME, - builtinCredentialSource: "dsh credentials service (jet-hub state.json) — the only scheme bili re-signs itself", - envOverrides: { BILI_RESIGN: process.env.BILI_RESIGN ?? null, BILI_RESIGN_PASSTHROUGH: process.env.BILI_RESIGN_PASSTHROUGH ?? null }, - schemes, - pending: readPendingRefusals(), - unresolved: Object.keys(unresolvedRefusals()), - }, null, 2)); + const names = new Set([ + ...Object.keys(KNOWN_SIGNATURE_SCHEMES), + ...Object.keys(readPendingRefusals()), + ]); + const schemes: Record< + string, + { + known?: { label: string; source: string; builtIn?: boolean }; + builtIn: boolean; + enabled: boolean; + passthrough: boolean; + passthroughApplies: boolean; + } + > = {}; + for (const name of [...names].sort()) { + const st = resolveResignSettings(process.env, undefined, name); + schemes[name] = { + known: KNOWN_SIGNATURE_SCHEMES[name], + builtIn: name === APIG_RESIGN_SCHEME, + enabled: st.enabled, + passthrough: st.passthrough, + passthroughApplies: name === APIG_RESIGN_SCHEME, + }; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify( + { + builtinScheme: APIG_RESIGN_SCHEME, + builtinCredentialSource: + "dsh credentials service (jet-hub state.json) — the only scheme bili re-signs itself", + envOverrides: { + BILI_RESIGN: process.env.BILI_RESIGN ?? null, + BILI_RESIGN_PASSTHROUGH: process.env.BILI_RESIGN_PASSTHROUGH ?? null, + }, + schemes, + pending: readPendingRefusals(), + unresolved: Object.keys(unresolvedRefusals()), + }, + null, + 2, + ), + ); } -async function sendOverview(res: http.ServerResponse, opts: ProxyOptions): Promise { - let diskVersion: string | undefined; - let stale = false; - try { - ({ diskVersion, stale } = await detectStaleInstall(PACKAGE_NAME, VERSION)); - } catch { - // fs hiccup: report running state only, never fail the overview endpoint - } - let overview; - try { - overview = await buildOverview(); - } catch (error) { - loggerLog("error", `[acp-web] overview failed: ${String(error)}`); - res.writeHead(500, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: "failed to load session data" })); - return; - } - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ - overview, - version: VERSION, - commit: BUILD_COMMIT, - diskVersion, - stale, - updateReady: updateReadyPayload(), - autoRestartOnUpdate: opts.autoRestartOnUpdate, - advisory: currentAdvisoryPayload(), - pluginAdvisories: detectCostAdvisories(process.env), - hostPluginNotices: visibleHostPluginNotices(process.env), - inFlight: totalInFlight(), - blindTunnels: getBlindTunnelStats(), - conflicts: summarizeConflicts(listSessions()), - passthrough: { enabled: !!opts.passthrough, source: opts.passthroughSource }, - alerts: getUpstreamAlerts(), - }, null, 2)); +async function sendOverview( + res: http.ServerResponse, + opts: ProxyOptions, +): Promise { + let diskVersion: string | undefined; + let stale = false; + try { + ({ diskVersion, stale } = await detectStaleInstall(PACKAGE_NAME, VERSION)); + } catch { + // fs hiccup: report running state only, never fail the overview endpoint + } + let overview; + try { + overview = await buildOverview(); + } catch (error) { + loggerLog("error", `[acp-web] overview failed: ${String(error)}`); + res.writeHead(500, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "failed to load session data" })); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify( + { + overview, + version: VERSION, + commit: BUILD_COMMIT, + diskVersion, + stale, + updateReady: updateReadyPayload(), + autoRestartOnUpdate: opts.autoRestartOnUpdate, + advisory: currentAdvisoryPayload(), + pluginAdvisories: detectCostAdvisories(process.env), + hostPluginNotices: visibleHostPluginNotices(process.env), + inFlight: totalInFlight(), + blindTunnels: getBlindTunnelStats(), + conflicts: summarizeConflicts(listSessions()), + passthrough: { + enabled: !!opts.passthrough, + source: opts.passthroughSource, + }, + alerts: getUpstreamAlerts(), + }, + null, + 2, + ), + ); } /** #1937: optional ?q= / ?page= / ?pageSize= (≤200) switch the endpoint to * server-side filtered paging. Without params the response shape is unchanged * ({sessions, hiddenEmpty} + additive total) so older UIs keep working. */ -async function sendWebSessions(res: http.ServerResponse, req: http.IncomingMessage): Promise { - const u = new URL(req.url ?? "/__bili/sessions", "http://localhost"); - let body: Record; - try { - if (u.searchParams.has("page") || u.searchParams.has("pageSize") || u.searchParams.has("q")) { - const rawSize = Number(u.searchParams.get("pageSize")); - const pageSize = Number.isFinite(rawSize) && rawSize > 0 ? Math.min(Math.floor(rawSize), 200) : 50; - const rawPage = Number(u.searchParams.get("page")); - const page = Number.isFinite(rawPage) && rawPage >= 1 ? Math.floor(rawPage) : 1; - body = { ...(await buildSessionPage({ q: u.searchParams.get("q") ?? undefined, page, pageSize })), hiddenEmpty: hiddenEmptyCount() }; - } else { - const sessions = await buildSessionList(); - body = { sessions, hiddenEmpty: hiddenEmptyCount(), total: sessions.length }; - } - } catch (error) { - loggerLog("error", `[acp-web] sessions list failed: ${String(error)}`); - res.writeHead(500, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: "failed to load session data" })); - return; - } - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify(body, null, 2)); +async function sendWebSessions( + res: http.ServerResponse, + req: http.IncomingMessage, +): Promise { + const u = new URL(req.url ?? "/__bili/sessions", "http://localhost"); + let body: Record; + try { + if ( + u.searchParams.has("page") || + u.searchParams.has("pageSize") || + u.searchParams.has("q") + ) { + const rawSize = Number(u.searchParams.get("pageSize")); + const pageSize = + Number.isFinite(rawSize) && rawSize > 0 + ? Math.min(Math.floor(rawSize), 200) + : 50; + const rawPage = Number(u.searchParams.get("page")); + const page = + Number.isFinite(rawPage) && rawPage >= 1 ? Math.floor(rawPage) : 1; + body = { + ...(await buildSessionPage({ + q: u.searchParams.get("q") ?? undefined, + page, + pageSize, + })), + hiddenEmpty: hiddenEmptyCount(), + }; + } else { + const sessions = await buildSessionList(); + body = { + sessions, + hiddenEmpty: hiddenEmptyCount(), + total: sessions.length, + }; + } + } catch (error) { + loggerLog("error", `[acp-web] sessions list failed: ${String(error)}`); + res.writeHead(500, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "failed to load session data" })); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(body, null, 2)); } /** #1426 web UI run-log viewer: tail of the rotated logger files (bili.log.old * + bili.log), optionally filtered by a case-insensitive substring (?q=). * ?lines= caps the tail at 2000; ?raw=1 streams the same tail as a .txt download. */ -async function sendWebLogs(res: http.ServerResponse, req: http.IncomingMessage): Promise { - const u = new URL(req.url ?? "/__bili/logs", "http://localhost"); - const q = (u.searchParams.get("q") ?? "").trim(); - const fullDownload = u.searchParams.get("raw") === "1" && u.searchParams.get("all") === "1"; - let n = Number(u.searchParams.get("lines") ?? "500"); - if (!Number.isFinite(n) || n <= 0) n = 500; - // Full download is the forensic escape hatch: ignore `lines`, capped only - // by the memory guard below so users can export the whole .old + cur pair. - n = fullDownload ? 100_000 : Math.min(Math.floor(n), 2000); - // Context expansion (ctx=N rows around each hit) and time window (win=Ss - // around [firstHit, lastHit]) — selection logic lives in web/logs-query.ts - // (unit-tested pure function); win wins over ctx when both are given. - let ctx = Number(u.searchParams.get("ctx") ?? "0"); - if (!Number.isFinite(ctx) || ctx < 0) ctx = 0; - ctx = Math.min(Math.floor(ctx), 50); - let win = Number(u.searchParams.get("win") ?? "0"); - if (!Number.isFinite(win) || win < 0) win = 0; - win = Math.min(Math.floor(win), 3600); - const logFile = getLogPath() ?? defaultLogFile(); - // Cross-platform dir extraction: a naive "/" split yields "" on Windows - // paths and the candidates would silently resolve against cwd. - const dir = logFile ? path.dirname(logFile) + path.sep : ""; - const candidates = [dir + "bili.log.old", dir + "bili.log"]; - const existing = candidates.filter((f) => { - try { return fs.statSync(f).isFile(); } catch { return false; } - }); - let all: string[] = []; - for (const f of existing) { - let text: string; - try { text = fs.readFileSync(f, "utf8"); } catch { continue; } - all = all.concat(text.split("\n").filter((l) => l.length > 0)); - } - const r = queryLogLines(all, q, { ctx, winSec: win, n }); - if (u.searchParams.get("raw") === "1") { - res.writeHead(200, { - "content-type": "text/plain; charset=utf-8", - "content-disposition": `attachment; filename="${fullDownload ? "billion-context-full-log.txt" : "billion-context-log.txt"}"`, - }); - res.end(r.lines.join("\n")); - return; - } - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ - path: logFile, - total: r.total, - shown: r.shown, - omitted: r.omitted, - lines: r.lines, - ...(r.isMatch ? { isMatch: r.isMatch } : {}), - }, null, 2)); +async function sendWebLogs( + res: http.ServerResponse, + req: http.IncomingMessage, +): Promise { + const u = new URL(req.url ?? "/__bili/logs", "http://localhost"); + const q = (u.searchParams.get("q") ?? "").trim(); + const fullDownload = + u.searchParams.get("raw") === "1" && u.searchParams.get("all") === "1"; + let n = Number(u.searchParams.get("lines") ?? "500"); + if (!Number.isFinite(n) || n <= 0) n = 500; + // Full download is the forensic escape hatch: ignore `lines`, capped only + // by the memory guard below so users can export the whole .old + cur pair. + n = fullDownload ? 100_000 : Math.min(Math.floor(n), 2000); + // Context expansion (ctx=N rows around each hit) and time window (win=Ss + // around [firstHit, lastHit]) — selection logic lives in web/logs-query.ts + // (unit-tested pure function); win wins over ctx when both are given. + let ctx = Number(u.searchParams.get("ctx") ?? "0"); + if (!Number.isFinite(ctx) || ctx < 0) ctx = 0; + ctx = Math.min(Math.floor(ctx), 50); + let win = Number(u.searchParams.get("win") ?? "0"); + if (!Number.isFinite(win) || win < 0) win = 0; + win = Math.min(Math.floor(win), 3600); + const logFile = getLogPath() ?? defaultLogFile(); + // Cross-platform dir extraction: a naive "/" split yields "" on Windows + // paths and the candidates would silently resolve against cwd. + const dir = logFile ? path.dirname(logFile) + path.sep : ""; + const candidates = [dir + "bili.log.old", dir + "bili.log"]; + const existing = candidates.filter((f) => { + try { + return fs.statSync(f).isFile(); + } catch { + return false; + } + }); + let all: string[] = []; + for (const f of existing) { + let text: string; + try { + text = fs.readFileSync(f, "utf8"); + } catch { + continue; + } + all = all.concat(text.split("\n").filter((l) => l.length > 0)); + } + const r = queryLogLines(all, q, { ctx, winSec: win, n }); + if (u.searchParams.get("raw") === "1") { + res.writeHead(200, { + "content-type": "text/plain; charset=utf-8", + "content-disposition": `attachment; filename="${fullDownload ? "billion-context-full-log.txt" : "billion-context-log.txt"}"`, + }); + res.end(r.lines.join("\n")); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify( + { + path: logFile, + total: r.total, + shown: r.shown, + omitted: r.omitted, + lines: r.lines, + ...(r.isMatch ? { isMatch: r.isMatch } : {}), + }, + null, + 2, + ), + ); } -async function sendWebSessionDetail(res: http.ServerResponse, url: string): Promise { - const prefix = "/__bili/sessions/"; - const suffix = "/detail"; - let id = ""; - try { - id = decodeURIComponent(url.slice(prefix.length, -suffix.length)); - } catch { - // malformed percent-encoding → treat as unknown session (404 below) - } - const detail = await buildSessionDetail(id); - if (!detail) { - res.writeHead(404, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: `unknown session: ${id}` })); - return; - } - res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify(detail, null, 2)); +async function sendWebSessionDetail( + res: http.ServerResponse, + url: string, +): Promise { + const prefix = "/__bili/sessions/"; + const suffix = "/detail"; + let id = ""; + try { + id = decodeURIComponent(url.slice(prefix.length, -suffix.length)); + } catch { + // malformed percent-encoding → treat as unknown session (404 below) + } + const detail = await buildSessionDetail(id); + if (!detail) { + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: `unknown session: ${id}` })); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(detail, null, 2)); } diff --git a/tests/codex-responses-ws.test.ts b/tests/codex-responses-ws.test.ts index 18e7a4a110..4c0634889c 100644 --- a/tests/codex-responses-ws.test.ts +++ b/tests/codex-responses-ws.test.ts @@ -21,7 +21,11 @@ process.env.XDG_STATE_HOME = testHome; process.env.XDG_DATA_HOME = testHome; process.env.XDG_CACHE_HOME = testHome; -const user = (text: string): Item => ({ type: "message", role: "user", content: [{ type: "input_text", text }] }); +const user = (text: string): Item => ({ + type: "message", + role: "user", + content: [{ type: "input_text", text }], +}); // Mirrors the captured codex 0.147.0 Responses-over-WebSocket client: the // upgrade targets the ordinary prefix-mode path with codex's own transport @@ -29,273 +33,584 @@ const user = (text: string): Item => ({ type: "message", role: "user", content: // replay — a `generate: false` probe with empty input first, then one // full-history frame per turn. Codex never sends previous_response_id. async function fixture() { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-ws-")); - _setStoreForTest(new SessionStore({ enabled: false })); - setRegistryForTest({}); - const rows: Array<{ request: Item; headers: http.IncomingHttpHeaders }> = []; - let httpRequests = 0; - let serial = 0; - let toolArguments: string | undefined; - const upstream = http.createServer((req, res) => { if (req.method === "POST") httpRequests++; res.writeHead(404).end(); }); - const wss = new WebSocketServer({ server: upstream }); - wss.on("connection", (peer, req) => { peer.on("error", e => console.error("[FAKE-UPSTREAM-PEER-ERR]", e.message)); peer.on("message", raw => { - const request = JSON.parse(raw.toString()) as Item; - rows.push({ request, headers: req.headers }); - const id = `resp_codex_${++serial}`; - const send = (type: string, fields: Item): void => peer.send(JSON.stringify({ type, ...fields })); - if (Array.isArray(request.input) && request.input.length === 0) { - // Probe: codex expects a terminal event, nothing more. - send("response.created", { response: { id, status: "in_progress", output: [] } }); - send("response.completed", { response: { id, status: "completed", output: [], usage: { input_tokens: 0, output_tokens: 1, total_tokens: 1 } } }); - return; - } - const item: Item = toolArguments !== undefined - ? { type: "function_call", id: `fc_${id}`, call_id: `call_${id}`, name: "acp_status", arguments: toolArguments, status: "completed" } - : { type: "message", id: `msg_${id}`, role: "assistant", status: "completed", content: [{ type: "output_text", text: `ok-${serial}` }] }; - send("response.created", { response: { id, status: "in_progress", output: [] } }); - send("response.output_item.added", { output_index: 0, item: { ...item, status: "in_progress", ...(toolArguments === undefined ? { content: [] } : { arguments: "" }) } }); - if (toolArguments !== undefined) { - send("response.function_call_arguments.delta", { item_id: item.id, output_index: 0, delta: toolArguments }); - send("response.function_call_arguments.done", { item_id: item.id, output_index: 0, arguments: toolArguments }); - } else { - send("response.output_text.delta", { item_id: item.id, output_index: 0, content_index: 0, delta: `ok-${serial}` }); - send("response.output_text.done", { item_id: item.id, output_index: 0, content_index: 0, text: `ok-${serial}` }); - } - send("response.output_item.done", { output_index: 0, item }); - send("response.completed", { response: { id, object: "response", status: "completed", output: [item], usage: { input_tokens: 500, output_tokens: 10, total_tokens: 510 } } }); - }); }); - upstream.listen(0, "127.0.0.1"); - await once(upstream, "listening"); - const config = defaultConfig(200000); - config.preserveRecentTokens = 0; - const opts: ProxyOptions = { host: "127.0.0.1", port: 0, upstream: "http://127.0.0.1", routes: {}, modelContextLimit: 200000, kernelConfig: config, compress: { injectTool: true, injectNudge: false }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: true, logFile: path.join(tmp, "bili.log"), debug: false, passthrough: false, autoUpdate: false, mitm: { enabled: false, domains: [] } }; - const proxy = await startServer(opts); - await once(proxy, "listening"); - const proxyOrigin = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`; - const upstreamOrigin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`; - const sid = `codex-thread-${randomUUID()}`; - const openPeer = async (authorization = "Bearer fake-credential", extraHeaders: Record = {}) => { - const client = new WebSocket(`${proxyOrigin.replace(/^http/, "ws")}/bili/${upstreamOrigin}/v1/responses`, { headers: { authorization, "session-id": sid, "thread-id": sid, "openai-beta": "responses_websockets=2026-02-06", "user-agent": "codex_exec/0.147.0 (Ubuntu 24.4.0; x86_64) gnome-terminal (codex_exec; 0.147.0)", originator: "codex_exec", ...extraHeaders } }); - await once(client, "open"); - return client; - }; - const frame = (input: Item[], extra: Item = {}): string => JSON.stringify({ type: "response.create", model: "gpt-5.2", instructions: "You are Codex", store: false, stream: true, include: ["reasoning.encrypted_content"], prompt_cache_key: sid, reasoning: { effort: "medium", summary: "auto" }, text: { verbosity: "low" }, tools: [], input, client_metadata: { session_id: sid, thread_id: sid }, ...extra }); - async function exchange(payload: string, client: WebSocket): Promise { - client.send(payload); - return new Promise((resolve, reject) => { - const events: Item[] = []; - const cleanup = (): void => { clearTimeout(timer); client.off("message", onMessage); client.off("close", onClose); }; - const timer = setTimeout(() => { cleanup(); reject(new Error("WS turn timed out")); }, 10000); - const onClose = (): void => { cleanup(); reject(new Error("WS client closed")); }; - const onMessage = (raw: WebSocket.RawData): void => { - const event = JSON.parse(raw.toString()) as Item; - events.push(event); - if (["response.completed", "response.failed", "response.incomplete", "error"].includes(String(event.type))) { - cleanup(); - resolve(events); - } - }; - client.on("message", onMessage); - client.once("close", onClose); - }); - } - // Codex opens every connection with a prewarm probe and waits for its - // terminal event before sending the real turn; the test must respect the - // same ordering or the session correctly rejects it with response_in_progress. - const probe = (client: WebSocket = peer): Promise => exchange(frame([], { generate: false }), client); - const turn = (input: Item[], client: WebSocket = peer): Promise => exchange(frame(input), client); - const peer = await openPeer(); - peer.on("error", e => console.error("[TEST-CLIENT-ERR]", e.message)); - return { rows, sid, proxyOrigin, upstreamOrigin, proxy, peer, turn, probe, frame, openPeer, - logPath: path.join(tmp, "bili.log"), - setToolArguments: (args: string) => { toolArguments = args; }, get httpRequests() { return httpRequests; }, close: async () => { - peer.terminate(); - for (const client of wss.clients) client.terminate(); - await Promise.all([new Promise(resolve => proxy.close(() => resolve())), new Promise(resolve => upstream.close(() => resolve()))]); - wss.close(); - } }; + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-ws-")); + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const rows: Array<{ request: Item; headers: http.IncomingHttpHeaders }> = []; + let httpRequests = 0; + let serial = 0; + let toolArguments: string | undefined; + const upstream = http.createServer((req, res) => { + if (req.method === "POST") httpRequests++; + res.writeHead(404).end(); + }); + const wss = new WebSocketServer({ server: upstream }); + wss.on("connection", (peer, req) => { + peer.on("error", (e) => + console.error("[FAKE-UPSTREAM-PEER-ERR]", e.message), + ); + peer.on("message", (raw) => { + const request = JSON.parse(raw.toString()) as Item; + rows.push({ request, headers: req.headers }); + const id = `resp_codex_${++serial}`; + const send = (type: string, fields: Item): void => + peer.send(JSON.stringify({ type, ...fields })); + if (Array.isArray(request.input) && request.input.length === 0) { + // Probe: codex expects a terminal event, nothing more. + send("response.created", { + response: { id, status: "in_progress", output: [] }, + }); + send("response.completed", { + response: { + id, + status: "completed", + output: [], + usage: { input_tokens: 0, output_tokens: 1, total_tokens: 1 }, + }, + }); + return; + } + const item: Item = + toolArguments !== undefined + ? { + type: "function_call", + id: `fc_${id}`, + call_id: `call_${id}`, + name: "acp_status", + arguments: toolArguments, + status: "completed", + } + : { + type: "message", + id: `msg_${id}`, + role: "assistant", + status: "completed", + content: [{ type: "output_text", text: `ok-${serial}` }], + }; + send("response.created", { + response: { id, status: "in_progress", output: [] }, + }); + send("response.output_item.added", { + output_index: 0, + item: { + ...item, + status: "in_progress", + ...(toolArguments === undefined + ? { content: [] } + : { arguments: "" }), + }, + }); + if (toolArguments !== undefined) { + send("response.function_call_arguments.delta", { + item_id: item.id, + output_index: 0, + delta: toolArguments, + }); + send("response.function_call_arguments.done", { + item_id: item.id, + output_index: 0, + arguments: toolArguments, + }); + } else { + send("response.output_text.delta", { + item_id: item.id, + output_index: 0, + content_index: 0, + delta: `ok-${serial}`, + }); + send("response.output_text.done", { + item_id: item.id, + output_index: 0, + content_index: 0, + text: `ok-${serial}`, + }); + } + send("response.output_item.done", { output_index: 0, item }); + send("response.completed", { + response: { + id, + object: "response", + status: "completed", + output: [item], + usage: { input_tokens: 500, output_tokens: 10, total_tokens: 510 }, + }, + }); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const config = defaultConfig(200000); + config.preserveRecentTokens = 0; + const opts: ProxyOptions = { + host: "127.0.0.1", + port: 0, + upstream: "http://127.0.0.1", + routes: {}, + modelContextLimit: 200000, + kernelConfig: config, + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: true, + logFile: path.join(tmp, "bili.log"), + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + }; + const proxy = await startServer(opts); + await once(proxy, "listening"); + const proxyOrigin = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`; + const upstreamOrigin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`; + const sid = `codex-thread-${randomUUID()}`; + const openPeer = async ( + authorization = "Bearer fake-credential", + extraHeaders: Record = {}, + ) => { + const client = new WebSocket( + `${proxyOrigin.replace(/^http/, "ws")}/bili/${upstreamOrigin}/v1/responses`, + { + headers: { + authorization, + "session-id": sid, + "thread-id": sid, + "openai-beta": "responses_websockets=2026-02-06", + "user-agent": + "codex_exec/0.147.0 (Ubuntu 24.4.0; x86_64) gnome-terminal (codex_exec; 0.147.0)", + originator: "codex_exec", + ...extraHeaders, + }, + }, + ); + await once(client, "open"); + return client; + }; + const frame = (input: Item[], extra: Item = {}): string => + JSON.stringify({ + type: "response.create", + model: "gpt-5.2", + instructions: "You are Codex", + store: false, + stream: true, + include: ["reasoning.encrypted_content"], + prompt_cache_key: sid, + reasoning: { effort: "medium", summary: "auto" }, + text: { verbosity: "low" }, + tools: [], + input, + client_metadata: { session_id: sid, thread_id: sid }, + ...extra, + }); + async function exchange(payload: string, client: WebSocket): Promise { + client.send(payload); + return new Promise((resolve, reject) => { + const events: Item[] = []; + const cleanup = (): void => { + clearTimeout(timer); + client.off("message", onMessage); + client.off("close", onClose); + }; + const timer = setTimeout(() => { + cleanup(); + reject(new Error("WS turn timed out")); + }, 10000); + const onClose = (): void => { + cleanup(); + reject(new Error("WS client closed")); + }; + const onMessage = (raw: WebSocket.RawData): void => { + const event = JSON.parse(raw.toString()) as Item; + events.push(event); + if ( + [ + "response.completed", + "response.failed", + "response.incomplete", + "error", + ].includes(String(event.type)) + ) { + cleanup(); + resolve(events); + } + }; + client.on("message", onMessage); + client.once("close", onClose); + }); + } + // Codex opens every connection with a prewarm probe and waits for its + // terminal event before sending the real turn; the test must respect the + // same ordering or the session correctly rejects it with response_in_progress. + const probe = (client: WebSocket = peer): Promise => + exchange(frame([], { generate: false }), client); + const turn = (input: Item[], client: WebSocket = peer): Promise => + exchange(frame(input), client); + const peer = await openPeer(); + peer.on("error", (e) => console.error("[TEST-CLIENT-ERR]", e.message)); + return { + rows, + sid, + proxyOrigin, + upstreamOrigin, + proxy, + peer, + turn, + probe, + frame, + openPeer, + logPath: path.join(tmp, "bili.log"), + setToolArguments: (args: string) => { + toolArguments = args; + }, + get httpRequests() { + return httpRequests; + }, + close: async () => { + peer.terminate(); + for (const client of wss.clients) client.terminate(); + await Promise.all([ + new Promise((resolve) => proxy.close(() => resolve())), + new Promise((resolve) => upstream.close(() => resolve())), + ]); + wss.close(); + }, + }; } const completed = (events: Item[]): Item => { - const event = events.find(e => e.type === "response.completed"); - assert.ok(event, JSON.stringify(events)); - return event.response as Item; + const event = events.find((e) => e.type === "response.completed"); + assert.ok(event, JSON.stringify(events)); + return event.response as Item; }; -test("codex WS: prewarm probe plus full-replay turns ride the prefix lane through ACP", { timeout: 30000 }, async () => { - const f = await fixture(); - try { - await f.probe(); - const first = completed(await f.turn([user("codex-first-turn")])); - assert.equal(first.status, "completed"); - assert.ok(JSON.stringify(first.output).includes("ok-")); - assert.equal(f.httpRequests, 0); - assert.equal(f.rows.length, 2); - // Probe forwarded verbatim on the upstream transport (no ACP pipeline: - // no synthesized message, no injected tools, no phantom turn). - assert.deepEqual(f.rows[0].request.input, []); - assert.equal(f.rows[0].request.generate, false); - assert.ok(Array.isArray(f.rows[0].request.tools) && f.rows[0].request.tools.length === 0); - assert.equal(f.rows[0].headers.authorization, "Bearer fake-credential"); - assert.equal(f.rows[0].headers["session-id"], f.sid); - assert.match(String(f.rows[0].headers["user-agent"]), /^codex_exec\//); - // The real turn is a full replay the pipeline processed: bili's ACP - // tools ride alongside codex's own (empty) tool list. - assert.ok(Array.isArray(f.rows[1].request.tools) && (f.rows[1].request.tools as Item[]).some(t => t.name === "acp_status" || t.name === "compress"), JSON.stringify((f.rows[1].request.tools as Item[] | undefined)?.map?.((t: Item) => t.name))); - assert.ok(JSON.stringify(f.rows[1].request.input).includes("codex-first-turn")); - const session = peekSession(f.sid); - assert.ok(session); - assert.equal(session.stats.requests, 1); - assert.equal(session.stats.lastInputTokens, 500); - // Poll, don't one-shot-read (#2882): the logger's file stream is - // async/buffered (#1971) — same family as the :275 wait below — and a - // cold readFileSync here raced the flush on loaded CI runners, leaving - // only the 4 startup lines in the file. - const wantWs = /\[codex-responses-ws\] \[conn=1\]/; - const wantConnected = /Responses socket connected/; - const deadlineLog = Date.now() + 5000; - let log = ""; - for (;;) { - log = fs.readFileSync(f.logPath, "utf8"); - if (wantWs.test(log) && wantConnected.test(log)) break; - if (Date.now() >= deadlineLog) break; - await new Promise(r => setTimeout(r, 20)); - } - assert.match(log, wantWs); - assert.match(log, wantConnected); - assert.doesNotMatch(log, /side request \(/); - } finally { await f.close(); } +test("codex WS: prewarm probe plus full-replay turns ride the prefix lane through ACP", { + timeout: 30000, +}, async () => { + const f = await fixture(); + try { + await f.probe(); + const first = completed(await f.turn([user("codex-first-turn")])); + assert.equal(first.status, "completed"); + assert.ok(JSON.stringify(first.output).includes("ok-")); + assert.equal(f.httpRequests, 0); + assert.equal(f.rows.length, 2); + // Probe forwarded verbatim on the upstream transport (no ACP pipeline: + // no synthesized message, no injected tools, no phantom turn). + assert.deepEqual(f.rows[0].request.input, []); + assert.equal(f.rows[0].request.generate, false); + assert.ok( + Array.isArray(f.rows[0].request.tools) && + f.rows[0].request.tools.length === 0, + ); + assert.equal(f.rows[0].headers.authorization, "Bearer fake-credential"); + assert.equal(f.rows[0].headers["session-id"], f.sid); + assert.match(String(f.rows[0].headers["user-agent"]), /^codex_exec\//); + // The real turn is a full replay the pipeline processed: bili's ACP + // tools ride alongside codex's own (empty) tool list. + assert.ok( + Array.isArray(f.rows[1].request.tools) && + (f.rows[1].request.tools as Item[]).some( + (t) => t.name === "acp_status" || t.name === "compress", + ), + JSON.stringify( + (f.rows[1].request.tools as Item[] | undefined)?.map?.( + (t: Item) => t.name, + ), + ), + ); + assert.ok( + JSON.stringify(f.rows[1].request.input).includes("codex-first-turn"), + ); + const session = peekSession(f.sid); + assert.ok(session); + assert.equal(session.stats.requests, 1); + assert.equal(session.stats.lastInputTokens, 500); + const statsResponse = await fetch(`${f.proxyOrigin}/__bili/stats`); + const statsPayload = (await statsResponse.json()) as { + sessions: Array<{ id: string; codexClient: boolean }>; + }; + assert.equal( + statsPayload.sessions.find((row) => row.id === f.sid)?.codexClient, + true, + "doctor evidence must recognize a real Codex transport request", + ); + // Poll, don't one-shot-read (#2882): the logger's file stream is + // async/buffered (#1971) — same family as the :275 wait below — and a + // cold readFileSync here raced the flush on loaded CI runners, leaving + // only the 4 startup lines in the file. + const wantWs = /\[codex-responses-ws\] \[conn=1\]/; + const wantConnected = /Responses socket connected/; + const deadlineLog = Date.now() + 5000; + let log = ""; + for (;;) { + log = fs.readFileSync(f.logPath, "utf8"); + if (wantWs.test(log) && wantConnected.test(log)) break; + if (Date.now() >= deadlineLog) break; + await new Promise((r) => setTimeout(r, 20)); + } + assert.match(log, wantWs); + assert.match(log, wantConnected); + assert.doesNotMatch(log, /side request \(/); + } finally { + await f.close(); + } }); -test("codex WS: later turns replay full history; no previous_response_id is ever sent", { timeout: 30000 }, async () => { - const f = await fixture(); - try { - await f.probe(); - completed(await f.turn([user("turn-one-material")])); - completed(await f.turn([user("turn-one-material"), { type: "message", role: "assistant", content: [{ type: "output_text", text: "prior answer" }] }, user("turn-two")])); - - assert.equal(f.rows.length, 3); - for (const row of f.rows) assert.equal(row.request.previous_response_id, undefined); - const replayed = f.rows[2].request.input as Item[]; - // The lane injects a developer message (instructions + compression - // philosophy) ahead of the replay; codex replay itself is verbatim. - assert.equal(replayed.filter(item => item.type === "message" && item.role !== "developer").length, 3); - assert.ok(replayed.some(item => item.role === "developer")); - assert.ok(JSON.stringify(replayed).includes("turn-two")); - assert.equal(f.httpRequests, 0); - } finally { await f.close(); } +test("codex WS: later turns replay full history; no previous_response_id is ever sent", { + timeout: 30000, +}, async () => { + const f = await fixture(); + try { + await f.probe(); + completed(await f.turn([user("turn-one-material")])); + completed( + await f.turn([ + user("turn-one-material"), + { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "prior answer" }], + }, + user("turn-two"), + ]), + ); + + assert.equal(f.rows.length, 3); + for (const row of f.rows) + assert.equal(row.request.previous_response_id, undefined); + const replayed = f.rows[2].request.input as Item[]; + // The lane injects a developer message (instructions + compression + // philosophy) ahead of the replay; codex replay itself is verbatim. + assert.equal( + replayed.filter( + (item) => item.type === "message" && item.role !== "developer", + ).length, + 3, + ); + assert.ok(replayed.some((item) => item.role === "developer")); + assert.ok(JSON.stringify(replayed).includes("turn-two")); + assert.equal(f.httpRequests, 0); + } finally { + await f.close(); + } }); -test("codex WS: folding covered history shrinks the replayed turn", { timeout: 30000 }, async () => { - const f = await fixture(); - try { - await f.probe(); - // Codex replays the FULL history every turn (no previous_response_id); - // the fold test must drive the wire the same way or each single-message - // turn would replace the kernel's conversation view instead of growing it. - const replay: Item[] = []; - const play = async (text: string): Promise => { - const reply = completed(await f.turn([...replay, user(text)])); - replay.push(user(text)); - const message = Array.isArray(reply.output) ? (reply.output.find(item => item && typeof item === "object" && item.type === "message") as Item | undefined) : undefined; - if (message) replay.push(message); - }; - await play("session purpose: codex prefix-lane ACP integration"); - await play("OLD-BULKY-SENTINEL " + "unique filler content ".repeat(1200)); - const firstText = JSON.stringify((f.rows.at(-1)!.request.input as Item[]).find((item: Item) => JSON.stringify(item).includes("OLD-BULKY-SENTINEL"))); - const ref = firstText.match(/\x3cacp[^\x3e]*\x3e(m\d+)\x3c\/acp\x3e/)?.[1]; - assert.ok(ref, firstText.slice(-300)); - for (let i = 0; i < 4; i++) await play(`push ${i}`); - const args = { content: [{ startId: ref, endId: ref, summary: "SUMMARY-CODEX-WS-FOLD: initial bulky material contained deterministic filler; retain this verified summary instead of the original payload." }] }; - const result = await fetch(`${f.proxyOrigin}/__bili/plugin/tool`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ conversationId: f.sid, tool: "compress", args }) }); - const out = await result.json() as { ok: boolean; result: string }; - assert.equal(out.ok, true, JSON.stringify(out)); - assert.match(out.result, /Compressed/); - f.setToolArguments("{}"); - completed(await f.turn([ - ...replay, - { type: "function_call", id: "fc_compress", call_id: "call_compress", name: "compress", arguments: JSON.stringify(args) }, - { type: "function_call_output", call_id: "call_compress", output: out.result }, - user("continue after fold"), - ])); - const row = f.rows.at(-1)!; - assert.ok(!JSON.stringify(row.request.input).includes("OLD-BULKY-SENTINEL"), JSON.stringify((row.request.input as Item[]).filter(item => JSON.stringify(item).includes("OLD-BULKY-SENTINEL")).map(item => JSON.stringify(item.content).slice(0, 180)))); - assert.ok(JSON.stringify(row.request.input).includes("SUMMARY-CODEX-WS-FOLD")); - assert.ok(peekSession(f.sid)?.state.blocks.some(b => b.active)); - assert.equal(f.httpRequests, 0); - } finally { await f.close(); } +test("codex WS: folding covered history shrinks the replayed turn", { + timeout: 30000, +}, async () => { + const f = await fixture(); + try { + await f.probe(); + // Codex replays the FULL history every turn (no previous_response_id); + // the fold test must drive the wire the same way or each single-message + // turn would replace the kernel's conversation view instead of growing it. + const replay: Item[] = []; + const play = async (text: string): Promise => { + const reply = completed(await f.turn([...replay, user(text)])); + replay.push(user(text)); + const message = Array.isArray(reply.output) + ? (reply.output.find( + (item) => + item && typeof item === "object" && item.type === "message", + ) as Item | undefined) + : undefined; + if (message) replay.push(message); + }; + await play("session purpose: codex prefix-lane ACP integration"); + await play("OLD-BULKY-SENTINEL " + "unique filler content ".repeat(1200)); + const firstText = JSON.stringify( + (f.rows.at(-1)!.request.input as Item[]).find((item: Item) => + JSON.stringify(item).includes("OLD-BULKY-SENTINEL"), + ), + ); + const ref = firstText.match(/\x3cacp[^\x3e]*\x3e(m\d+)\x3c\/acp\x3e/)?.[1]; + assert.ok(ref, firstText.slice(-300)); + for (let i = 0; i < 4; i++) await play(`push ${i}`); + const args = { + content: [ + { + startId: ref, + endId: ref, + summary: + "SUMMARY-CODEX-WS-FOLD: initial bulky material contained deterministic filler; retain this verified summary instead of the original payload.", + }, + ], + }; + const result = await fetch(`${f.proxyOrigin}/__bili/plugin/tool`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: f.sid, tool: "compress", args }), + }); + const out = (await result.json()) as { ok: boolean; result: string }; + assert.equal(out.ok, true, JSON.stringify(out)); + assert.match(out.result, /Compressed/); + f.setToolArguments("{}"); + completed( + await f.turn([ + ...replay, + { + type: "function_call", + id: "fc_compress", + call_id: "call_compress", + name: "compress", + arguments: JSON.stringify(args), + }, + { + type: "function_call_output", + call_id: "call_compress", + output: out.result, + }, + user("continue after fold"), + ]), + ); + const row = f.rows.at(-1)!; + assert.ok( + !JSON.stringify(row.request.input).includes("OLD-BULKY-SENTINEL"), + JSON.stringify( + (row.request.input as Item[]) + .filter((item) => JSON.stringify(item).includes("OLD-BULKY-SENTINEL")) + .map((item) => JSON.stringify(item.content).slice(0, 180)), + ), + ); + assert.ok( + JSON.stringify(row.request.input).includes("SUMMARY-CODEX-WS-FOLD"), + ); + assert.ok(peekSession(f.sid)?.state.blocks.some((b) => b.active)); + assert.equal(f.httpRequests, 0); + } finally { + await f.close(); + } }); -test("codex WS: admission requires the conversation header and the responses path", { timeout: 30000 }, async () => { - const f = await fixture(); - const origin = f.proxyOrigin.replace(/^http/, "ws"); - const refused = async (url: string, headers: Record): Promise => { - const client = new WebSocket(url, { headers }); - const [, incoming] = (await once(client, "unexpected-response")) as unknown as [http.ClientRequest, http.IncomingMessage]; - const status = incoming.statusCode ?? 0; - incoming.destroy(); // pre-open refusal: destroy the socket, terminate() would throw - return status; - }; - try { - // Missing session-id: nothing claims the upgrade. - assert.equal(await refused(`${origin}/bili/${f.upstreamOrigin}/v1/responses`, { authorization: "Bearer fake" }), 426); - // Conversation header present but the path is not a responses endpoint. - assert.equal(await refused(`${origin}/bili/${f.upstreamOrigin}/v1/chat`, { "session-id": f.sid }), 426); - } finally { await f.close(); } +test("codex WS: admission requires the conversation header and the responses path", { + timeout: 30000, +}, async () => { + const f = await fixture(); + const origin = f.proxyOrigin.replace(/^http/, "ws"); + const refused = async ( + url: string, + headers: Record, + ): Promise => { + const client = new WebSocket(url, { headers }); + const [, incoming] = (await once( + client, + "unexpected-response", + )) as unknown as [http.ClientRequest, http.IncomingMessage]; + const status = incoming.statusCode ?? 0; + incoming.destroy(); // pre-open refusal: destroy the socket, terminate() would throw + return status; + }; + try { + // Missing session-id: nothing claims the upgrade. + assert.equal( + await refused(`${origin}/bili/${f.upstreamOrigin}/v1/responses`, { + authorization: "Bearer fake", + }), + 426, + ); + // Conversation header present but the path is not a responses endpoint. + assert.equal( + await refused(`${origin}/bili/${f.upstreamOrigin}/v1/chat`, { + "session-id": f.sid, + }), + 426, + ); + } finally { + await f.close(); + } }); -test("codex WS: non-streaming transport options are refused with a protocol error frame", { timeout: 30000 }, async () => { - const f = await fixture(); - try { - const events: Item[] = []; - const done = new Promise(resolve => { f.peer.on("message", (raw: WebSocket.RawData) => { const event = JSON.parse(raw.toString()) as Item; events.push(event); if (event.type === "error") resolve(event); }); }); - f.peer.send(f.frame([user("nope")], { stream: false })); - const error = await done; - assert.equal(error.type, "error"); - assert.equal((error.error as { code: string }).code, "invalid_request"); - } finally { await f.close(); } +test("codex WS: non-streaming transport options are refused with a protocol error frame", { + timeout: 30000, +}, async () => { + const f = await fixture(); + try { + const events: Item[] = []; + const done = new Promise((resolve) => { + f.peer.on("message", (raw: WebSocket.RawData) => { + const event = JSON.parse(raw.toString()) as Item; + events.push(event); + if (event.type === "error") resolve(event); + }); + }); + f.peer.send(f.frame([user("nope")], { stream: false })); + const error = await done; + assert.equal(error.type, "error"); + assert.equal((error.error as { code: string }).code, "invalid_request"); + } finally { + await f.close(); + } }); -test("codex WS: stream_options delivery hints are admitted (codex 0.160.0 shape, #2126)", { timeout: 30000 }, async () => { - const f = await fixture(); - try { - await f.probe(); - const events: Item[] = []; - const done = new Promise(resolve => { - f.peer.on("message", (raw: WebSocket.RawData) => { const event = JSON.parse(raw.toString()) as Item; events.push(event); if (event.type === "response.completed") resolve(events); }); - }); - // codex 0.147+ rides reasoning_summary_delivery on every response.create; - // the lane must admit it instead of refusing the whole frame. - f.peer.send(f.frame([user("stream-options-turn")], { stream_options: { reasoning_summary_delivery: "sequential_cutoff" } })); - const result = await done; - assert.equal(result.at(-1)?.type, "response.completed"); - assert.ok(result.every(e => e.type !== "error"), JSON.stringify(result)); - // Admitted through the ACP pipeline: probe row + one processed turn row, no error frame. - assert.equal(f.rows.length, 2); - assert.ok(JSON.stringify(f.rows[1].request.input).includes("stream-options-turn")); - } finally { await f.close(); } +test("codex WS: stream_options delivery hints are admitted (codex 0.160.0 shape, #2126)", { + timeout: 30000, +}, async () => { + const f = await fixture(); + try { + await f.probe(); + const events: Item[] = []; + const done = new Promise((resolve) => { + f.peer.on("message", (raw: WebSocket.RawData) => { + const event = JSON.parse(raw.toString()) as Item; + events.push(event); + if (event.type === "response.completed") resolve(events); + }); + }); + // codex 0.147+ rides reasoning_summary_delivery on every response.create; + // the lane must admit it instead of refusing the whole frame. + f.peer.send( + f.frame([user("stream-options-turn")], { + stream_options: { reasoning_summary_delivery: "sequential_cutoff" }, + }), + ); + const result = await done; + assert.equal(result.at(-1)?.type, "response.completed"); + assert.ok( + result.every((e) => e.type !== "error"), + JSON.stringify(result), + ); + // Admitted through the ACP pipeline: probe row + one processed turn row, no error frame. + assert.equal(f.rows.length, 2); + assert.ok( + JSON.stringify(f.rows[1].request.input).includes("stream-options-turn"), + ); + } finally { + await f.close(); + } }); -test("codex WS: rejection names the offending transport option in the frame and log (#2126)", { timeout: 30000 }, async () => { - const f = await fixture(); - try { - const done = new Promise(resolve => { f.peer.on("message", (raw: WebSocket.RawData) => { const event = JSON.parse(raw.toString()) as Item; if (event.type === "error") resolve(event); }); }); - f.peer.send(f.frame([user("bg")], { background: true })); - const error = await done; - assert.equal(error.type, "error"); - assert.equal((error.error as { code: string }).code, "invalid_request"); - assert.match(String((error.error as Item).message), /background/); - // Poll, don't one-shot-read: the logger's file stream is async/buffered - // (#1971) and readFileSync right after the error frame raced loaded CI runners. - const want = /client rejected reason=invalid_request detail=.*background/; - const deadline = Date.now() + 5000; - let log = ""; - for (;;) { - try { log = fs.readFileSync(f.logPath, "utf8"); } catch { /* open still in flight */ } - if (want.test(log)) break; - if (Date.now() >= deadline) break; - await new Promise(r => setTimeout(r, 20)); - } - assert.match(log, want); - } finally { await f.close(); } +test("codex WS: rejection names the offending transport option in the frame and log (#2126)", { + timeout: 30000, +}, async () => { + const f = await fixture(); + try { + const done = new Promise((resolve) => { + f.peer.on("message", (raw: WebSocket.RawData) => { + const event = JSON.parse(raw.toString()) as Item; + if (event.type === "error") resolve(event); + }); + }); + f.peer.send(f.frame([user("bg")], { background: true })); + const error = await done; + assert.equal(error.type, "error"); + assert.equal((error.error as { code: string }).code, "invalid_request"); + assert.match(String((error.error as Item).message), /background/); + // Poll, don't one-shot-read: the logger's file stream is async/buffered + // (#1971) and readFileSync right after the error frame raced loaded CI runners. + const want = /client rejected reason=invalid_request detail=.*background/; + const deadline = Date.now() + 5000; + let log = ""; + for (;;) { + try { + log = fs.readFileSync(f.logPath, "utf8"); + } catch { + /* open still in flight */ + } + if (want.test(log)) break; + if (Date.now() >= deadline) break; + await new Promise((r) => setTimeout(r, 20)); + } + assert.match(log, want); + } finally { + await f.close(); + } }); diff --git a/tests/doctor.test.ts b/tests/doctor.test.ts index 65c2cc860b..f41c6b3289 100644 --- a/tests/doctor.test.ts +++ b/tests/doctor.test.ts @@ -4,669 +4,1308 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { + existsSync, + mkdtempSync, + mkdirSync, + readFileSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { dshBundleShadowWarning, globalVerdict, laneVerdict, renderDoctorReport, runDoctor, type DoctorLane, type DoctorProcess, type DoctorReport } from "../src/doctor.ts"; +import { + dshBundleShadowWarning, + globalVerdict, + laneVerdict, + renderDoctorReport, + runDoctor, + type DoctorLane, + type DoctorProcess, + type DoctorReport, +} from "../src/doctor.ts"; import { PLUGIN_AGENTS, inspectLanePresence } from "../src/plugin-install.ts"; import { rmrf } from "./tmp-rm.ts"; -function withEnv(vars: Record, fn: () => void | Promise): Promise | void { - const effective: Record = { ...vars }; - // Windows os.homedir() resolves through USERPROFILE, not HOME — mirror the - // sandboxed HOME there or real-machine config (~/.dsh, ~/.zcode, …) leaks - // into tests that believe they are running in an empty home. - if (process.platform === "win32" && effective.HOME !== undefined && effective.USERPROFILE === undefined) { - effective.USERPROFILE = effective.HOME; - } - const saved: Record = {}; - for (const [k, v] of Object.entries(effective)) { - saved[k] = process.env[k]; - if (v === undefined) delete process.env[k]; - else process.env[k] = v; - } - const restore = (): void => { - for (const [k, v] of Object.entries(saved)) { - if (v === undefined) delete process.env[k]; - else process.env[k] = v; - } - }; - const r = fn(); - return r instanceof Promise ? r.finally(restore) : (restore(), undefined); +function withEnv( + vars: Record, + fn: () => void | Promise, +): Promise | void { + const effective: Record = { ...vars }; + // Windows os.homedir() resolves through USERPROFILE, not HOME — mirror the + // sandboxed HOME there or real-machine config (~/.dsh, ~/.zcode, …) leaks + // into tests that believe they are running in an empty home. + if ( + process.platform === "win32" && + effective.HOME !== undefined && + effective.USERPROFILE === undefined + ) { + effective.USERPROFILE = effective.HOME; + } + const saved: Record = {}; + for (const [k, v] of Object.entries(effective)) { + saved[k] = process.env[k]; + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + const restore = (): void => { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }; + const r = fn(); + return r instanceof Promise ? r.finally(restore) : (restore(), undefined); } -function mockFetch(handler: (url: string) => Response | Promise): (fn: () => Promise) => Promise { - const original = globalThis.fetch; - return (fn) => { - globalThis.fetch = ((url: unknown) => Promise.resolve(handler(String(url)))) as unknown as typeof fetch; - return fn().finally(() => { - globalThis.fetch = original; - }); - }; +function mockFetch( + handler: (url: string) => Response | Promise, +): (fn: () => Promise) => Promise { + const original = globalThis.fetch; + return (fn) => { + globalThis.fetch = ((url: unknown) => + Promise.resolve(handler(String(url)))) as unknown as typeof fetch; + return fn().finally(() => { + globalThis.fetch = original; + }); + }; } test("laneVerdict precedence: absent < broken < frozen < stale < ok", () => { - assert.equal(laneVerdict({ installed: false, targetMissing: true, frozen: true }), "absent"); - assert.equal(laneVerdict({ installed: true, targetMissing: true, frozen: true, copyVersion: "0.1.1", registryVersion: "999.0.0" }), "broken"); - assert.equal(laneVerdict({ installed: true, targetMissing: false, frozen: true, copyVersion: "0.1.1", registryVersion: "999.0.0" }), "frozen"); - assert.equal(laneVerdict({ installed: true, targetMissing: false, frozen: false, copyVersion: "0.1.1", registryVersion: "999.0.0" }), "stale"); - assert.equal(laneVerdict({ installed: true, targetMissing: false, frozen: false, copyVersion: "999.0.0", registryVersion: "0.1.1" }), "ok"); - // Freshness is only claimed when both versions are resolvable — an - // unreachable registry must never produce a false-stale verdict. - assert.equal(laneVerdict({ installed: true, targetMissing: false, frozen: false, copyVersion: "0.1.1" }), "ok"); + assert.equal( + laneVerdict({ installed: false, targetMissing: true, frozen: true }), + "absent", + ); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: true, + frozen: true, + copyVersion: "0.1.1", + registryVersion: "999.0.0", + }), + "broken", + ); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: true, + copyVersion: "0.1.1", + registryVersion: "999.0.0", + }), + "frozen", + ); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: "0.1.1", + registryVersion: "999.0.0", + }), + "stale", + ); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: "999.0.0", + registryVersion: "0.1.1", + }), + "ok", + ); + // Freshness is only claimed when both versions are resolvable — an + // unreachable registry must never produce a false-stale verdict. + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: "0.1.1", + }), + "ok", + ); }); test("globalVerdict: checkout is frozen regardless of registry; registry newer than disk is stale", () => { - assert.equal(globalVerdict({ form: "checkout", diskVersion: "0.1.143", registryVersion: "999.0.0" }), "frozen"); - assert.equal(globalVerdict({ form: "npm", diskVersion: "0.1.143", registryVersion: "0.1.144" }), "stale"); - assert.equal(globalVerdict({ form: "npm", diskVersion: "0.1.143", registryVersion: "0.1.143" }), "ok"); - assert.equal(globalVerdict({ form: "host-managed", diskVersion: "0.1.143" }), "ok"); + assert.equal( + globalVerdict({ + form: "checkout", + diskVersion: "0.1.143", + registryVersion: "999.0.0", + }), + "frozen", + ); + assert.equal( + globalVerdict({ + form: "npm", + diskVersion: "0.1.143", + registryVersion: "0.1.144", + }), + "stale", + ); + assert.equal( + globalVerdict({ + form: "npm", + diskVersion: "0.1.143", + registryVersion: "0.1.143", + }), + "ok", + ); + assert.equal( + globalVerdict({ form: "host-managed", diskVersion: "0.1.143" }), + "ok", + ); }); test("#2891: dshBundleShadowWarning fires only when a machine-global copy coexists with a divergent profile copy", () => { - assert.equal(dshBundleShadowWarning({ packageName: "billion-context", globalInstallDir: "/g/bc", globalDiskVersion: "0.1.135", profileName: "web", bundleInstalled: false, profileCopyVersion: undefined }), undefined); - assert.equal(dshBundleShadowWarning({ packageName: "billion-context", globalInstallDir: undefined, globalDiskVersion: undefined, profileName: "web", bundleInstalled: true, profileCopyVersion: "0.1.194" }), undefined); - assert.equal(dshBundleShadowWarning({ packageName: "billion-context", globalInstallDir: "/g/bc", globalDiskVersion: "0.1.194", profileName: "web", bundleInstalled: true, profileCopyVersion: "0.1.194" }), undefined); - const w = dshBundleShadowWarning({ packageName: "billion-context", globalInstallDir: "/g/bc", globalDiskVersion: "0.1.135", profileName: "web", bundleInstalled: true, profileCopyVersion: "0.1.194" }); - assert.ok(typeof w === "string" && w.includes("v0.1.135") && w.includes("v0.1.194") && w.includes("installation-anchor-first") && w.includes("dsh --profile web --dump-config"), `expected divergent-version shadow warning, got: ${w}`); - assert.ok(dshBundleShadowWarning({ packageName: "billion-context", globalInstallDir: "/g/bc", globalDiskVersion: undefined, profileName: "web", bundleInstalled: true, profileCopyVersion: "0.1.194" }) !== undefined); + assert.equal( + dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: "/g/bc", + globalDiskVersion: "0.1.135", + profileName: "web", + bundleInstalled: false, + profileCopyVersion: undefined, + }), + undefined, + ); + assert.equal( + dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: undefined, + globalDiskVersion: undefined, + profileName: "web", + bundleInstalled: true, + profileCopyVersion: "0.1.194", + }), + undefined, + ); + assert.equal( + dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: "/g/bc", + globalDiskVersion: "0.1.194", + profileName: "web", + bundleInstalled: true, + profileCopyVersion: "0.1.194", + }), + undefined, + ); + const w = dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: "/g/bc", + globalDiskVersion: "0.1.135", + profileName: "web", + bundleInstalled: true, + profileCopyVersion: "0.1.194", + }); + assert.ok( + typeof w === "string" && + w.includes("v0.1.135") && + w.includes("v0.1.194") && + w.includes("installation-anchor-first") && + w.includes("dsh --profile web --dump-config"), + `expected divergent-version shadow warning, got: ${w}`, + ); + assert.ok( + dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: "/g/bc", + globalDiskVersion: undefined, + profileName: "web", + bundleInstalled: true, + profileCopyVersion: "0.1.194", + }) !== undefined, + ); }); test("#2891: a dsh lane carrying the shadow warning renders under its row without touching the verdict", () => { - const text = renderDoctorReport(syntheticReport({ - lanes: [ - { agent: "dsh:web", kind: "host-managed", installed: true, detail: "dep spec: ^0.1.194", copyVersion: "0.1.194", verdict: "stale", registryVersion: "0.1.195", warnings: ["shadowed copy: a machine-global billion-context (/g/bc, v0.1.135) coexists with this profile's own copy (v0.1.194)"] }, - ], - })); - assert.match(text, /⚠️ shadowed copy/); - assert.match(text, /dsh:web\s+stale \(v0\.1\.194 → v0\.1\.195\)\s+host-managed/); + const text = renderDoctorReport( + syntheticReport({ + lanes: [ + { + agent: "dsh:web", + kind: "host-managed", + installed: true, + detail: "dep spec: ^0.1.194", + copyVersion: "0.1.194", + verdict: "stale", + registryVersion: "0.1.195", + warnings: [ + "shadowed copy: a machine-global billion-context (/g/bc, v0.1.135) coexists with this profile's own copy (v0.1.194)", + ], + }, + ], + }), + ); + assert.match(text, /⚠️ shadowed copy/); + assert.match( + text, + /dsh:web\s+stale \(v0\.1\.194 → v0\.1\.195\)\s+host-managed/, + ); }); test("#2891: runDoctor wires the shadow warning onto the divergent dsh profile lane and stays silent when versions match", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-shadow-run-")); - const runWithFetch = mockFetch(() => new Response(JSON.stringify({ name: "billion-context", version: "999.0.0" }), { status: 200, headers: { "Content-Type": "application/json" } })); - // For runDoctor the running test process IS the machine-global copy: findInstallDir - // walks up from src/update.ts to this repo root (#1628). Pin the profile fixture - // against that real disk version — divergent vs equal — instead of faking a global dir. - const repoPkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version?: unknown }; - const repoVersion = typeof repoPkg.version === "string" ? repoPkg.version : undefined; - assert.ok(repoVersion, "the repo package.json must carry its own version"); - try { - await runWithFetch(async () => { - const cases: Array<[string, string]> = [["divergent", "999.999.999"], ["equal", repoVersion]]; - for (const [profileName, copyVersion] of cases) { - const home = path.join(base, profileName); - const profileDir = path.join(home, "dsh", "profiles", profileName); - const copyDir = path.join(profileDir, "node_modules", "billion-context"); - mkdirSync(copyDir, { recursive: true }); - writeFileSync(path.join(profileDir, "package.json"), JSON.stringify({ dependencies: { "billion-context": "^0.1.140" }, dsh: { profile: { bundles: ["billion-context"] } } })); - writeFileSync(path.join(copyDir, "package.json"), JSON.stringify({ name: "billion-context", version: copyVersion })); - await withEnv({ ...doctorSandboxEnv(home), DSH_HOME: path.join(home, "dsh") }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - const lane = report.lanes.find((l) => l.agent === `dsh:${profileName}`); - assert.ok(lane !== undefined, `dsh:${profileName} lane present`); - if (copyVersion === repoVersion) { - assert.equal(lane?.warnings, undefined, `matching versions must not warn: ${JSON.stringify(lane?.warnings)}`); - } else { - assert.ok(lane?.warnings?.some((w) => w.startsWith("shadowed copy:") && w.includes(`v${repoVersion}`)), `divergent versions must warn, got: ${JSON.stringify(lane?.warnings)}`); - assert.match(renderDoctorReport(report), /⚠️ shadowed copy/); - } - }); - } - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-shadow-run-")); + const runWithFetch = mockFetch( + () => + new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ); + // For runDoctor the running test process IS the machine-global copy: findInstallDir + // walks up from src/update.ts to this repo root (#1628). Pin the profile fixture + // against that real disk version — divergent vs equal — instead of faking a global dir. + const repoPkg = JSON.parse( + readFileSync(new URL("../package.json", import.meta.url), "utf8"), + ) as { version?: unknown }; + const repoVersion = + typeof repoPkg.version === "string" ? repoPkg.version : undefined; + assert.ok(repoVersion, "the repo package.json must carry its own version"); + try { + await runWithFetch(async () => { + const cases: Array<[string, string]> = [ + ["divergent", "999.999.999"], + ["equal", repoVersion], + ]; + for (const [profileName, copyVersion] of cases) { + const home = path.join(base, profileName); + const profileDir = path.join(home, "dsh", "profiles", profileName); + const copyDir = path.join( + profileDir, + "node_modules", + "billion-context", + ); + mkdirSync(copyDir, { recursive: true }); + writeFileSync( + path.join(profileDir, "package.json"), + JSON.stringify({ + dependencies: { "billion-context": "^0.1.140" }, + dsh: { profile: { bundles: ["billion-context"] } }, + }), + ); + writeFileSync( + path.join(copyDir, "package.json"), + JSON.stringify({ name: "billion-context", version: copyVersion }), + ); + await withEnv( + { ...doctorSandboxEnv(home), DSH_HOME: path.join(home, "dsh") }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const lane = report.lanes.find( + (l) => l.agent === `dsh:${profileName}`, + ); + assert.ok(lane !== undefined, `dsh:${profileName} lane present`); + if (copyVersion === repoVersion) { + assert.equal( + lane?.warnings, + undefined, + `matching versions must not warn: ${JSON.stringify(lane?.warnings)}`, + ); + } else { + assert.ok( + lane?.warnings?.some( + (w) => + w.startsWith("shadowed copy:") && + w.includes(`v${repoVersion}`), + ), + `divergent versions must warn, got: ${JSON.stringify(lane?.warnings)}`, + ); + assert.match(renderDoctorReport(report), /⚠️ shadowed copy/); + } + }, + ); + } + }); + } finally { + rmrf(base); + } }); -function syntheticReport(overrides?: { lanes?: DoctorLane[]; processes?: DoctorProcess[] }): DoctorReport { - return { - generatedAt: Date.parse("2026-09-24T00:00:00Z"), - packageName: "billion-context", - global: { installDir: "/x/node_modules/billion-context", form: "npm", diskVersion: "0.1.143", runningVersion: "0.1.143", registryVersion: "0.1.143", updateTag: "latest", lastCheckTime: Date.parse("2026-09-24T00:00:00Z"), verdict: "ok" }, - lanes: overrides?.lanes ?? [], - processes: overrides?.processes ?? [], - }; +function syntheticReport(overrides?: { + lanes?: DoctorLane[]; + processes?: DoctorProcess[]; +}): DoctorReport { + return { + generatedAt: Date.parse("2026-09-24T00:00:00Z"), + packageName: "billion-context", + global: { + installDir: "/x/node_modules/billion-context", + form: "npm", + diskVersion: "0.1.143", + runningVersion: "0.1.143", + registryVersion: "0.1.143", + updateTag: "latest", + lastCheckTime: Date.parse("2026-09-24T00:00:00Z"), + verdict: "ok", + }, + lanes: overrides?.lanes ?? [], + processes: overrides?.processes ?? [], + codexIntegration: { + state: "unknown", + route: "absent", + proxyHealthy: false, + observedCodexRequest: false, + detail: "not configured", + }, + ccSwitch: { + discovered: false, + mode: "unknown", + compatibility: "unsupported", + evidence: [], + detail: "not detected", + }, + chatGptDesktop: { + state: "待完成/可实现", + credentials: "not-read-not-persisted", + officialLoginChannels: "preserved", + desktopMcp: "separate-from-model-routing", + }, + }; } test("renderDoctorReport: verdict lines carry the issue-specified formats", () => { - const text = renderDoctorReport(syntheticReport({ - lanes: [ - { agent: "omp", kind: "reference", installed: true, detail: "/old/dist/agent/omp-native.js", channel: "the global bili install (entry points at it)", verdict: "stale", copyVersion: "0.1.1", registryVersion: "0.1.2" }, - { agent: "dsh:dev", kind: "host-managed", installed: true, detail: "dep spec: link:/local/x (local pin — dev lane, manual)", verdict: "frozen", reason: "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)" }, - { agent: "pi", kind: "host-managed", installed: false, detail: "not installed", verdict: "absent" }, - ], - processes: [ - { instanceId: "abc", pid: 4242, port: 8787, origin: "http://127.0.0.1:8787", startedAt: Date.parse("2026-09-24T00:00:00Z"), alive: true, runningFrom: "/x/node_modules/billion-context/dist/index.js" }, - { instanceId: "def", pid: 5555, port: 8788, origin: "http://127.0.0.1:8788", startedAt: Date.parse("2026-09-24T00:00:00Z"), alive: false }, - ], - })); - assert.match(text, /stale \(v0\.1\.1 → v0\.1\.2\)/); - assert.match(text, /frozen/); - assert.match(text, /zombie \(process gone, marker left behind\)/); - assert.match(text, /summary: 0 ok, 1 stale, 1 frozen, 0 broken, 1 absent; processes: 1 live, 1 zombie/); - assert.match(text, /updates via: the global bili install \(entry points at it\)/); + const text = renderDoctorReport( + syntheticReport({ + lanes: [ + { + agent: "omp", + kind: "reference", + installed: true, + detail: "/old/dist/agent/omp-native.js", + channel: "the global bili install (entry points at it)", + verdict: "stale", + copyVersion: "0.1.1", + registryVersion: "0.1.2", + }, + { + agent: "dsh:dev", + kind: "host-managed", + installed: true, + detail: "dep spec: link:/local/x (local pin — dev lane, manual)", + verdict: "frozen", + reason: + "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)", + }, + { + agent: "pi", + kind: "host-managed", + installed: false, + detail: "not installed", + verdict: "absent", + }, + ], + processes: [ + { + instanceId: "abc", + pid: 4242, + port: 8787, + origin: "http://127.0.0.1:8787", + startedAt: Date.parse("2026-09-24T00:00:00Z"), + alive: true, + runningFrom: "/x/node_modules/billion-context/dist/index.js", + }, + { + instanceId: "def", + pid: 5555, + port: 8788, + origin: "http://127.0.0.1:8788", + startedAt: Date.parse("2026-09-24T00:00:00Z"), + alive: false, + }, + ], + }), + ); + assert.match(text, /stale \(v0\.1\.1 → v0\.1\.2\)/); + assert.match(text, /frozen/); + assert.match(text, /zombie \(process gone, marker left behind\)/); + assert.match( + text, + /summary: 0 ok, 1 stale, 1 frozen, 0 broken, 1 absent; processes: 1 live, 1 zombie/, + ); + assert.match( + text, + /updates via: the global bili install \(entry points at it\)/, + ); }); test("inspectLanePresence omp: dead entry is a broken lane, live entry resolves its copy version", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-omp-")); - try { - const ompHome = path.join(base, "omp"); - const deadEntry = path.join(base, "dead", "dist", "agent", "omp-native.js"); - const liveRoot = path.join(base, "fakepkg"); - const liveEntry = path.join(liveRoot, "dist", "agent", "omp-native.js"); - mkdirSync(path.join(ompHome), { recursive: true }); - mkdirSync(path.dirname(liveEntry), { recursive: true }); - writeFileSync(liveEntry, "export {};\n"); - writeFileSync(path.join(liveRoot, "package.json"), JSON.stringify({ name: "billion-context", version: "0.1.143" })); - const cfg = (entries: string[]): string => ["extensions:", ...entries.map((e) => ` - ${e}`)].join("\n") + "\n"; - writeFileSync(path.join(ompHome, "config.yml"), cfg([deadEntry])); - withEnv({ PI_CODING_AGENT_DIR: ompHome }, () => { - const dead = inspectLanePresence("omp"); - assert.equal(dead.installed, true); - assert.deepEqual(dead.targets, [deadEntry]); - assert.equal(laneVerdict({ installed: dead.installed, targetMissing: !existsSync(deadEntry), frozen: false, copyVersion: dead.copyVersion, registryVersion: "999.0.0" }), "broken"); - }); - writeFileSync(path.join(ompHome, "config.yml"), cfg([liveEntry])); - withEnv({ PI_CODING_AGENT_DIR: ompHome }, () => { - const live = inspectLanePresence("omp"); - assert.equal(live.installed, true); - assert.equal(live.copyVersion, "0.1.143"); - assert.ok(live.targets.every((t) => existsSync(t))); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-omp-")); + try { + const ompHome = path.join(base, "omp"); + const deadEntry = path.join(base, "dead", "dist", "agent", "omp-native.js"); + const liveRoot = path.join(base, "fakepkg"); + const liveEntry = path.join(liveRoot, "dist", "agent", "omp-native.js"); + mkdirSync(path.join(ompHome), { recursive: true }); + mkdirSync(path.dirname(liveEntry), { recursive: true }); + writeFileSync(liveEntry, "export {};\n"); + writeFileSync( + path.join(liveRoot, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.143" }), + ); + const cfg = (entries: string[]): string => + ["extensions:", ...entries.map((e) => ` - ${e}`)].join("\n") + "\n"; + writeFileSync(path.join(ompHome, "config.yml"), cfg([deadEntry])); + withEnv({ PI_CODING_AGENT_DIR: ompHome }, () => { + const dead = inspectLanePresence("omp"); + assert.equal(dead.installed, true); + assert.deepEqual(dead.targets, [deadEntry]); + assert.equal( + laneVerdict({ + installed: dead.installed, + targetMissing: !existsSync(deadEntry), + frozen: false, + copyVersion: dead.copyVersion, + registryVersion: "999.0.0", + }), + "broken", + ); + }); + writeFileSync(path.join(ompHome, "config.yml"), cfg([liveEntry])); + withEnv({ PI_CODING_AGENT_DIR: ompHome }, () => { + const live = inspectLanePresence("omp"); + assert.equal(live.installed, true); + assert.equal(live.copyVersion, "0.1.143"); + assert.ok(live.targets.every((t) => existsSync(t))); + }); + } finally { + rmrf(base); + } }); test("inspectLanePresence dsh: local pin flags a frozen dev lane, registry pin resolves bundle version", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-dsh-")); - try { - const dshHome = path.join(base, "dsh"); - const devDir = path.join(dshHome, "profiles", "dev"); - const mainDir = path.join(dshHome, "profiles", "main"); - const mainCopy = path.join(mainDir, "node_modules", "billion-context"); - mkdirSync(devDir, { recursive: true }); - mkdirSync(mainCopy, { recursive: true }); - writeFileSync(path.join(devDir, "package.json"), JSON.stringify({ dependencies: { "billion-context": "link:/local/x" }, dsh: { profile: { bundles: ["billion-context"] } } })); - writeFileSync(path.join(mainDir, "package.json"), JSON.stringify({ dependencies: { "billion-context": "^0.1.140" }, dsh: { profile: { bundles: ["billion-context"] } } })); - writeFileSync(path.join(mainCopy, "package.json"), JSON.stringify({ name: "billion-context", version: "0.1.140" })); - withEnv({ DSH_HOME: dshHome }, () => { - const p = inspectLanePresence("dsh"); - assert.equal(p.installed, true); - assert.equal(p.form, "local-path"); - const dev = p.profiles?.find((x) => x.name === "dev"); - assert.equal(dev?.pinned, true); - assert.equal(dev?.spec, "link:/local/x"); - assert.equal(laneVerdict({ installed: true, targetMissing: false, frozen: dev?.pinned === true, copyVersion: dev?.copyVersion, registryVersion: "999.0.0" }), "frozen"); - const main = p.profiles?.find((x) => x.name === "main"); - assert.equal(main?.pinned, false); - assert.equal(main?.copyVersion, "0.1.140"); - assert.equal(laneVerdict({ installed: true, targetMissing: false, frozen: false, copyVersion: main?.copyVersion, registryVersion: "999.0.0" }), "stale"); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-dsh-")); + try { + const dshHome = path.join(base, "dsh"); + const devDir = path.join(dshHome, "profiles", "dev"); + const mainDir = path.join(dshHome, "profiles", "main"); + const mainCopy = path.join(mainDir, "node_modules", "billion-context"); + mkdirSync(devDir, { recursive: true }); + mkdirSync(mainCopy, { recursive: true }); + writeFileSync( + path.join(devDir, "package.json"), + JSON.stringify({ + dependencies: { "billion-context": "link:/local/x" }, + dsh: { profile: { bundles: ["billion-context"] } }, + }), + ); + writeFileSync( + path.join(mainDir, "package.json"), + JSON.stringify({ + dependencies: { "billion-context": "^0.1.140" }, + dsh: { profile: { bundles: ["billion-context"] } }, + }), + ); + writeFileSync( + path.join(mainCopy, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.140" }), + ); + withEnv({ DSH_HOME: dshHome }, () => { + const p = inspectLanePresence("dsh"); + assert.equal(p.installed, true); + assert.equal(p.form, "local-path"); + const dev = p.profiles?.find((x) => x.name === "dev"); + assert.equal(dev?.pinned, true); + assert.equal(dev?.spec, "link:/local/x"); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: dev?.pinned === true, + copyVersion: dev?.copyVersion, + registryVersion: "999.0.0", + }), + "frozen", + ); + const main = p.profiles?.find((x) => x.name === "main"); + assert.equal(main?.pinned, false); + assert.equal(main?.copyVersion, "0.1.140"); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: main?.copyVersion, + registryVersion: "999.0.0", + }), + "stale", + ); + }); + } finally { + rmrf(base); + } }); test("#2850: inspectLanePresence pi: npm lane resolves the real copy root for every spec form", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-npm-")); - try { - const piHome = path.join(base, "pi"); - const realCopy = path.join(piHome, "npm", "node_modules", "billion-context"); - mkdirSync(realCopy, { recursive: true }); - writeFileSync(path.join(realCopy, "package.json"), JSON.stringify({ name: "billion-context", version: "0.1.143" })); - // Decoy at the OLD buggy probe path (/agent/npm/...) — must never be read. - const decoy = path.join(piHome, "agent", "npm", "node_modules", "billion-context"); - mkdirSync(decoy, { recursive: true }); - writeFileSync(path.join(decoy, "package.json"), JSON.stringify({ name: "billion-context", version: "9.9.9" })); - mkdirSync(piHome, { recursive: true }); - const settings = (packages: string[]): void => writeFileSync(path.join(piHome, "settings.json"), JSON.stringify({ packages })); - for (const spec of ["npm:billion-context", "npm:billion-context@0.1.150", "npm:billion-context@latest"]) { - settings([spec]); - withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { - const p = inspectLanePresence("pi"); - assert.equal(p.installed, true); - assert.equal(p.form, "npm"); - assert.deepEqual(p.targets, [realCopy], `${spec}: target must be the real pi materialization dir`); - assert.equal(p.copyVersion, "0.1.143", `${spec}: the decoy at the old wrong path must not leak`); - }); - } - // Copy not materialized yet → empty targets (the doctor hint applies), still installed/npm. - settings(["npm:billion-context"]); - rmrf(realCopy); - withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { - const p = inspectLanePresence("pi"); - assert.equal(p.installed, true); - assert.equal(p.form, "npm"); - assert.deepEqual(p.targets, []); - assert.equal(p.copyVersion, undefined); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-npm-")); + try { + const piHome = path.join(base, "pi"); + const realCopy = path.join( + piHome, + "npm", + "node_modules", + "billion-context", + ); + mkdirSync(realCopy, { recursive: true }); + writeFileSync( + path.join(realCopy, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.143" }), + ); + // Decoy at the OLD buggy probe path (/agent/npm/...) — must never be read. + const decoy = path.join( + piHome, + "agent", + "npm", + "node_modules", + "billion-context", + ); + mkdirSync(decoy, { recursive: true }); + writeFileSync( + path.join(decoy, "package.json"), + JSON.stringify({ name: "billion-context", version: "9.9.9" }), + ); + mkdirSync(piHome, { recursive: true }); + const settings = (packages: string[]): void => + writeFileSync( + path.join(piHome, "settings.json"), + JSON.stringify({ packages }), + ); + for (const spec of [ + "npm:billion-context", + "npm:billion-context@0.1.150", + "npm:billion-context@latest", + ]) { + settings([spec]); + withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { + const p = inspectLanePresence("pi"); + assert.equal(p.installed, true); + assert.equal(p.form, "npm"); + assert.deepEqual( + p.targets, + [realCopy], + `${spec}: target must be the real pi materialization dir`, + ); + assert.equal( + p.copyVersion, + "0.1.143", + `${spec}: the decoy at the old wrong path must not leak`, + ); + }); + } + // Copy not materialized yet → empty targets (the doctor hint applies), still installed/npm. + settings(["npm:billion-context"]); + rmrf(realCopy); + withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { + const p = inspectLanePresence("pi"); + assert.equal(p.installed, true); + assert.equal(p.form, "npm"); + assert.deepEqual(p.targets, []); + assert.equal(p.copyVersion, undefined); + }); + } finally { + rmrf(base); + } }); test("#2850: inspectLanePresence pi: absolute-path entry keeps local-path semantics; corrupt settings stays a probe failure", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-abs-")); - try { - const piHome = path.join(base, "pi"); - // A real dev checkout is named billion-context — the recognition regex - // keys off that basename (or a node_modules/billion-context segment). - const absRoot = path.join(base, "billion-context"); - mkdirSync(absRoot, { recursive: true }); - mkdirSync(piHome, { recursive: true }); - writeFileSync(path.join(absRoot, "package.json"), JSON.stringify({ name: "billion-context", version: "0.1.142" })); - writeFileSync(path.join(piHome, "settings.json"), JSON.stringify({ packages: [absRoot] })); - withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { - const p = inspectLanePresence("pi"); - assert.equal(p.installed, true); - assert.equal(p.form, "local-path"); - assert.deepEqual(p.targets, [absRoot]); - assert.equal(p.copyVersion, "0.1.142"); - }); - // Corrupt settings: single-source probe propagates the parse error (no false absent). - writeFileSync(path.join(piHome, "settings.json"), "{ not json"); - withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { - assert.throws(() => inspectLanePresence("pi"), /not valid JSON/); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-abs-")); + try { + const piHome = path.join(base, "pi"); + // A real dev checkout is named billion-context — the recognition regex + // keys off that basename (or a node_modules/billion-context segment). + const absRoot = path.join(base, "billion-context"); + mkdirSync(absRoot, { recursive: true }); + mkdirSync(piHome, { recursive: true }); + writeFileSync( + path.join(absRoot, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.142" }), + ); + writeFileSync( + path.join(piHome, "settings.json"), + JSON.stringify({ packages: [absRoot] }), + ); + withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { + const p = inspectLanePresence("pi"); + assert.equal(p.installed, true); + assert.equal(p.form, "local-path"); + assert.deepEqual(p.targets, [absRoot]); + assert.equal(p.copyVersion, "0.1.142"); + }); + // Corrupt settings: single-source probe propagates the parse error (no false absent). + writeFileSync(path.join(piHome, "settings.json"), "{ not json"); + withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { + assert.throws(() => inspectLanePresence("pi"), /not valid JSON/); + }); + } finally { + rmrf(base); + } }); test("#2850: runDoctor pi npm lane verdicts off the real copy and drops the false materialize hint", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-run-")); - const piHome = path.join(base, "pi"); - const realCopy = path.join(piHome, "npm", "node_modules", "billion-context"); - mkdirSync(realCopy, { recursive: true }); - writeFileSync(path.join(realCopy, "package.json"), JSON.stringify({ name: "billion-context", version: "0.1.143" })); - writeFileSync(path.join(piHome, "settings.json"), JSON.stringify({ packages: ["npm:billion-context"] })); - const registryDoc = (version: string): Response => new Response(JSON.stringify({ name: "billion-context", version }), { status: 200, headers: { "Content-Type": "application/json" } }); - try { - await mockFetch(() => registryDoc("999.0.0"))(async () => { - await withEnv({ ...doctorSandboxEnv(base), PI_CODING_AGENT_DIR: piHome }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - const pi = report.lanes.find((l) => l.agent === "pi"); - assert.equal(pi?.installed, true); - assert.equal(pi?.copyVersion, "0.1.143"); - assert.equal(pi?.verdict, "stale"); - assert.match(renderDoctorReport(report), /stale \(v0\.1\.143 → v999\.0\.0\)/); - assert.ok(!(pi?.detail ?? "").includes("materializes"), `copy exists — no false hint: ${pi?.detail}`); - }); - }); - // Copy genuinely absent → the pre-materialization hint applies again. - rmrf(realCopy); - await mockFetch(() => registryDoc("999.0.0"))(async () => { - await withEnv({ ...doctorSandboxEnv(base), PI_CODING_AGENT_DIR: piHome }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - const pi = report.lanes.find((l) => l.agent === "pi"); - assert.equal(pi?.installed, true); - assert.match(pi?.detail ?? "", /pi materializes the npm copy on next startup/); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-run-")); + const piHome = path.join(base, "pi"); + const realCopy = path.join(piHome, "npm", "node_modules", "billion-context"); + mkdirSync(realCopy, { recursive: true }); + writeFileSync( + path.join(realCopy, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.143" }), + ); + writeFileSync( + path.join(piHome, "settings.json"), + JSON.stringify({ packages: ["npm:billion-context"] }), + ); + const registryDoc = (version: string): Response => + new Response(JSON.stringify({ name: "billion-context", version }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + try { + await mockFetch(() => registryDoc("999.0.0"))(async () => { + await withEnv( + { ...doctorSandboxEnv(base), PI_CODING_AGENT_DIR: piHome }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const pi = report.lanes.find((l) => l.agent === "pi"); + assert.equal(pi?.installed, true); + assert.equal(pi?.copyVersion, "0.1.143"); + assert.equal(pi?.verdict, "stale"); + assert.match( + renderDoctorReport(report), + /stale \(v0\.1\.143 → v999\.0\.0\)/, + ); + assert.ok( + !(pi?.detail ?? "").includes("materializes"), + `copy exists — no false hint: ${pi?.detail}`, + ); + }, + ); + }); + // Copy genuinely absent → the pre-materialization hint applies again. + rmrf(realCopy); + await mockFetch(() => registryDoc("999.0.0"))(async () => { + await withEnv( + { ...doctorSandboxEnv(base), PI_CODING_AGENT_DIR: piHome }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const pi = report.lanes.find((l) => l.agent === "pi"); + assert.equal(pi?.installed, true); + assert.match( + pi?.detail ?? "", + /pi materializes the npm copy on next startup/, + ); + }, + ); + }); + } finally { + rmrf(base); + } }); test("inspectLanePresence hermes: baked plugin.yaml version is the freshness signal", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-hermes-")); - try { - const hermesHome = path.join(base, "hermes"); - const pluginDir = path.join(hermesHome, "plugins", "billion-context"); - const proxyScript = path.join(base, "global", "dist", "index.js"); - mkdirSync(pluginDir, { recursive: true }); - writeFileSync(path.join(pluginDir, "__init__.py"), ""); - writeFileSync(path.join(pluginDir, "plugin.yaml"), "id: billion-context\nversion: 0.1.100\nname: Billion Context\n"); - writeFileSync(path.join(pluginDir, "bili.json"), JSON.stringify({ proxyScript, nodePath: "node" })); - withEnv({ HERMES_HOME: hermesHome }, () => { - const p = inspectLanePresence("hermes"); - assert.equal(p.installed, true); - assert.equal(p.form, "local-path"); - assert.equal(p.copyVersion, "0.1.100"); - assert.deepEqual(p.targets, [proxyScript]); - assert.equal(laneVerdict({ installed: true, targetMissing: false, frozen: false, copyVersion: p.copyVersion, registryVersion: "999.0.0" }), "stale"); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-hermes-")); + try { + const hermesHome = path.join(base, "hermes"); + const pluginDir = path.join(hermesHome, "plugins", "billion-context"); + const proxyScript = path.join(base, "global", "dist", "index.js"); + mkdirSync(pluginDir, { recursive: true }); + writeFileSync(path.join(pluginDir, "__init__.py"), ""); + writeFileSync( + path.join(pluginDir, "plugin.yaml"), + "id: billion-context\nversion: 0.1.100\nname: Billion Context\n", + ); + writeFileSync( + path.join(pluginDir, "bili.json"), + JSON.stringify({ proxyScript, nodePath: "node" }), + ); + withEnv({ HERMES_HOME: hermesHome }, () => { + const p = inspectLanePresence("hermes"); + assert.equal(p.installed, true); + assert.equal(p.form, "local-path"); + assert.equal(p.copyVersion, "0.1.100"); + assert.deepEqual(p.targets, [proxyScript]); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: p.copyVersion, + registryVersion: "999.0.0", + }), + "stale", + ); + }); + } finally { + rmrf(base); + } }); test("inspectLanePresence: corrupt single-source config is a probe failure, not a false absent", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-corrupt-")); - try { - const ocDir = path.join(base, "opencode"); - mkdirSync(ocDir, { recursive: true }); - writeFileSync(path.join(ocDir, "opencode.json"), "{ not json"); - withEnv({ OPENCODE_CONFIG: path.join(ocDir, "opencode.json") }, () => { - assert.throws(() => inspectLanePresence("opencode"), /not valid JSON/); - }); - // zcode resolves its config via os.homedir(), which follows $HOME on - // POSIX but not on Windows — sandboxable only where $HOME rules. - if (process.platform !== "win32") { - const zcDir = path.join(base, "home", ".zcode", "cli"); - mkdirSync(zcDir, { recursive: true }); - writeFileSync(path.join(zcDir, "config.json"), "{ not json"); - withEnv({ HOME: path.join(base, "home") }, () => { - assert.throws(() => inspectLanePresence("zcode"), /not valid JSON/); - }); - } - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-corrupt-")); + try { + const ocDir = path.join(base, "opencode"); + mkdirSync(ocDir, { recursive: true }); + writeFileSync(path.join(ocDir, "opencode.json"), "{ not json"); + withEnv({ OPENCODE_CONFIG: path.join(ocDir, "opencode.json") }, () => { + assert.throws(() => inspectLanePresence("opencode"), /not valid JSON/); + }); + // zcode resolves its config via os.homedir(), which follows $HOME on + // POSIX but not on Windows — sandboxable only where $HOME rules. + if (process.platform !== "win32") { + const zcDir = path.join(base, "home", ".zcode", "cli"); + mkdirSync(zcDir, { recursive: true }); + writeFileSync(path.join(zcDir, "config.json"), "{ not json"); + withEnv({ HOME: path.join(base, "home") }, () => { + assert.throws(() => inspectLanePresence("zcode"), /not valid JSON/); + }); + } + } finally { + rmrf(base); + } }); test("runDoctor: corrupt lane config surfaces as a broken probe row, not absent", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-corrupt-run-")); - const ocCfg = path.join(base, "opencode.json"); - writeFileSync(ocCfg, "{ not json"); - const runWithFetch = mockFetch(() => new Response(JSON.stringify({ name: "billion-context", version: "999.0.0" }), { status: 200, headers: { "Content-Type": "application/json" } })); - try { - await runWithFetch(async () => { - await withEnv({ - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: ocCfg, - }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - const oc = report.lanes.find((l) => l.agent === "opencode"); - assert.equal(oc?.verdict, "broken"); - assert.match(oc?.detail ?? "", /probe failed: .*not valid JSON/); - for (const l of report.lanes.filter((x) => x.agent !== "opencode")) { - assert.equal(l.verdict, "absent", `${l.agent} should be absent in an empty sandbox`); - } - assert.match(renderDoctorReport(report), /probe failed/); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-corrupt-run-")); + const ocCfg = path.join(base, "opencode.json"); + writeFileSync(ocCfg, "{ not json"); + const runWithFetch = mockFetch( + () => + new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ); + try { + await runWithFetch(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: ocCfg, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const oc = report.lanes.find((l) => l.agent === "opencode"); + assert.equal(oc?.verdict, "broken"); + assert.match(oc?.detail ?? "", /probe failed: .*not valid JSON/); + for (const l of report.lanes.filter((x) => x.agent !== "opencode")) { + assert.equal( + l.verdict, + "absent", + `${l.agent} should be absent in an empty sandbox`, + ); + } + assert.match(renderDoctorReport(report), /probe failed/); + }, + ); + }); + } finally { + rmrf(base); + } }); test("#2199: opencode npm lane surfaces the cache copy path + disk version and goes stale only when the registry leads", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-oc-cache-")); - const ocCfg = path.join(base, "opencode.json"); - writeFileSync(ocCfg, JSON.stringify({ plugin: ["billion-context"] })); - const cacheRoot = path.join(base, "xdg-cache", "opencode", "npm", "billion-context@latest", "1760000000000", "node_modules", "billion-context"); - mkdirSync(cacheRoot, { recursive: true }); - writeFileSync(path.join(cacheRoot, "package.json"), JSON.stringify({ name: "billion-context", version: "0.1.143" })); - const registryDoc = (version: string): Response => new Response(JSON.stringify({ name: "billion-context", version }), { status: 200, headers: { "Content-Type": "application/json" } }); - try { - await mockFetch(() => registryDoc("999.0.0"))(async () => { - await withEnv({ - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, PI_HOME: undefined, DSH_HOME: undefined, - HERMES_HOME: undefined, KIMI_CODE_HOME: undefined, CODEX_HOME: undefined, CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: ocCfg, - }, async () => { - const presence = inspectLanePresence("opencode"); - assert.equal(presence.form, "npm"); - assert.equal(presence.targets[0], cacheRoot); - assert.equal(presence.copyVersion, "0.1.143"); - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - const oc = report.lanes.find((l) => l.agent === "opencode"); - assert.equal(oc?.copyVersion, "0.1.143"); - assert.equal(oc?.verdict, "stale"); - assert.match(oc?.detail ?? "", /cache copy \(/); - assert.ok((oc?.detail ?? "").includes(presence.targets[0]!), `detail must carry the actual load path: ${oc?.detail}`); - assert.match(oc?.detail ?? "", /reload\/restart OpenCode/); - assert.match(renderDoctorReport(report), /stale \(v0\.1\.143 → v999\.0\.0\)/); - }); - }); - // Same layout, registry at the same version as disk — must stay ok (no false-stale). - await mockFetch(() => registryDoc("0.1.143"))(async () => { - await withEnv({ - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, PI_HOME: undefined, DSH_HOME: undefined, - HERMES_HOME: undefined, KIMI_CODE_HOME: undefined, CODEX_HOME: undefined, CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: ocCfg, - }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - const oc = report.lanes.find((l) => l.agent === "opencode"); - assert.equal(oc?.verdict, "ok"); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-oc-cache-")); + const ocCfg = path.join(base, "opencode.json"); + writeFileSync(ocCfg, JSON.stringify({ plugin: ["billion-context"] })); + const cacheRoot = path.join( + base, + "xdg-cache", + "opencode", + "npm", + "billion-context@latest", + "1760000000000", + "node_modules", + "billion-context", + ); + mkdirSync(cacheRoot, { recursive: true }); + writeFileSync( + path.join(cacheRoot, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.143" }), + ); + const registryDoc = (version: string): Response => + new Response(JSON.stringify({ name: "billion-context", version }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + try { + await mockFetch(() => registryDoc("999.0.0"))(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: ocCfg, + }, + async () => { + const presence = inspectLanePresence("opencode"); + assert.equal(presence.form, "npm"); + assert.equal(presence.targets[0], cacheRoot); + assert.equal(presence.copyVersion, "0.1.143"); + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const oc = report.lanes.find((l) => l.agent === "opencode"); + assert.equal(oc?.copyVersion, "0.1.143"); + assert.equal(oc?.verdict, "stale"); + assert.match(oc?.detail ?? "", /cache copy \(/); + assert.ok( + (oc?.detail ?? "").includes(presence.targets[0]!), + `detail must carry the actual load path: ${oc?.detail}`, + ); + assert.match(oc?.detail ?? "", /reload\/restart OpenCode/); + assert.match( + renderDoctorReport(report), + /stale \(v0\.1\.143 → v999\.0\.0\)/, + ); + }, + ); + }); + // Same layout, registry at the same version as disk — must stay ok (no false-stale). + await mockFetch(() => registryDoc("0.1.143"))(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: ocCfg, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const oc = report.lanes.find((l) => l.agent === "opencode"); + assert.equal(oc?.verdict, "ok"); + }, + ); + }); + } finally { + rmrf(base); + } }); test("renderDoctorReport: lane warnings render under the lane row without touching the verdict", () => { - const text = renderDoctorReport(syntheticReport({ - lanes: [ - { agent: "claude", kind: "reference", installed: true, detail: "installed", verdict: "ok", warnings: ["Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL"] }, - { agent: "pi", kind: "host-managed", installed: false, detail: "not installed", verdict: "absent" }, - ], - })); - assert.match(text, /⚠️ Claude Desktop detected/); - assert.match(text, /claude\s+ok\s+reference/); + const text = renderDoctorReport( + syntheticReport({ + lanes: [ + { + agent: "claude", + kind: "reference", + installed: true, + detail: "installed", + verdict: "ok", + warnings: [ + "Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL", + ], + }, + { + agent: "pi", + kind: "host-managed", + installed: false, + detail: "not installed", + verdict: "absent", + }, + ], + }), + ); + assert.match(text, /⚠️ Claude Desktop detected/); + assert.match(text, /claude\s+ok\s+reference/); }); test("#2290: claude lane surfaces the last hook-detected routing bypass from the state marker", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-claude-warn-")); - const cfgDir = path.join(base, "claude-cfg"); - mkdirSync(cfgDir, { recursive: true }); - writeFileSync(path.join(cfgDir, "settings.json"), JSON.stringify({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:48787/bili/https://api.anthropic.com", DISABLE_AUTO_COMPACT: "1" } })); - const stateLane = path.join(base, "xdg-state", "billion-context"); - mkdirSync(stateLane, { recursive: true }); - writeFileSync(path.join(stateLane, "claude-routing-warning.json"), JSON.stringify({ at: Date.parse("2026-10-07T00:00:00Z"), reasons: ["CLAUDE_CODE_ENTRYPOINT=claude-desktop — this host sets its own ANTHROPIC_BASE_URL"] })); - try { - await mockFetch(() => new Response(JSON.stringify({ name: "billion-context", version: "999.0.0" }), { status: 200, headers: { "Content-Type": "application/json" } }))(async () => { - await withEnv({ - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, PI_HOME: undefined, DSH_HOME: undefined, - HERMES_HOME: undefined, KIMI_CODE_HOME: undefined, CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: cfgDir, - OPENCODE_CONFIG: undefined, - }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - const cl = report.lanes.find((l) => l.agent === "claude"); - assert.equal(cl?.installed, true); - assert.ok(cl?.warnings?.some((w) => w.includes("routing bypass") && w.includes("CLAUDE_CODE_ENTRYPOINT=claude-desktop")), `warnings: ${JSON.stringify(cl?.warnings)}`); - assert.match(renderDoctorReport(report), /⚠️ .*routing bypass/); - }); - }); - // Corrupt marker: surfaced as nothing, never as a probe failure. - writeFileSync(path.join(stateLane, "claude-routing-warning.json"), "{ not json"); - await mockFetch(() => new Response(JSON.stringify({ name: "billion-context", version: "999.0.0" }), { status: 200, headers: { "Content-Type": "application/json" } }))(async () => { - await withEnv({ - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, PI_HOME: undefined, DSH_HOME: undefined, - HERMES_HOME: undefined, KIMI_CODE_HOME: undefined, CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: cfgDir, - OPENCODE_CONFIG: undefined, - }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - const cl = report.lanes.find((l) => l.agent === "claude"); - assert.equal(cl?.verdict, "ok"); - assert.ok(!cl?.warnings?.some((w) => w.includes("routing bypass")), `corrupt marker must not surface: ${JSON.stringify(cl?.warnings)}`); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-claude-warn-")); + const cfgDir = path.join(base, "claude-cfg"); + mkdirSync(cfgDir, { recursive: true }); + writeFileSync( + path.join(cfgDir, "settings.json"), + JSON.stringify({ + env: { + ANTHROPIC_BASE_URL: + "http://127.0.0.1:48787/bili/https://api.anthropic.com", + DISABLE_AUTO_COMPACT: "1", + }, + }), + ); + const stateLane = path.join(base, "xdg-state", "billion-context"); + mkdirSync(stateLane, { recursive: true }); + writeFileSync( + path.join(stateLane, "claude-routing-warning.json"), + JSON.stringify({ + at: Date.parse("2026-10-07T00:00:00Z"), + reasons: [ + "CLAUDE_CODE_ENTRYPOINT=claude-desktop — this host sets its own ANTHROPIC_BASE_URL", + ], + }), + ); + try { + await mockFetch( + () => + new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + )(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: cfgDir, + OPENCODE_CONFIG: undefined, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const cl = report.lanes.find((l) => l.agent === "claude"); + assert.equal(cl?.installed, true); + assert.ok( + cl?.warnings?.some( + (w) => + w.includes("routing bypass") && + w.includes("CLAUDE_CODE_ENTRYPOINT=claude-desktop"), + ), + `warnings: ${JSON.stringify(cl?.warnings)}`, + ); + assert.match(renderDoctorReport(report), /⚠️ .*routing bypass/); + }, + ); + }); + // Corrupt marker: surfaced as nothing, never as a probe failure. + writeFileSync( + path.join(stateLane, "claude-routing-warning.json"), + "{ not json", + ); + await mockFetch( + () => + new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + )(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: cfgDir, + OPENCODE_CONFIG: undefined, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const cl = report.lanes.find((l) => l.agent === "claude"); + assert.equal(cl?.verdict, "ok"); + assert.ok( + !cl?.warnings?.some((w) => w.includes("routing bypass")), + `corrupt marker must not surface: ${JSON.stringify(cl?.warnings)}`, + ); + }, + ); + }); + } finally { + rmrf(base); + } }); test("runDoctor: full report against a mocked registry, sandboxed homes", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-run-")); - const urls: string[] = []; - const runWithFetch = mockFetch((url) => { - urls.push(url); - return new Response(JSON.stringify({ name: "billion-context", version: "999.0.0" }), { status: 200, headers: { "Content-Type": "application/json" } }); - }); - try { - await runWithFetch(async () => { - await withEnv({ - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: undefined, - }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - assert.ok(urls.some((u) => u.includes("registry.npmjs.org/billion-context/latest")), `registry URL hit: ${urls.join(", ")}`); - assert.equal(report.global.registryVersion, "999.0.0"); - assert.equal(report.global.updateTag, "latest"); - assert.deepEqual(report.lanes.map((l) => l.agent).sort(), [...PLUGIN_AGENTS].sort()); - for (const lane of report.lanes) { - assert.equal(lane.installed, false, `${lane.agent} should be absent in an empty sandbox`); - assert.equal(lane.verdict, "absent"); - assert.equal(lane.registryVersion, "999.0.0"); - } - assert.deepEqual(report.processes, []); - if (report.global.form === "checkout") { - assert.equal(report.global.verdict, "frozen"); - } else { - assert.ok(["ok", "stale"].includes(report.global.verdict)); - } - const parsed = JSON.parse(JSON.stringify(report, null, 2)) as DoctorReport; - assert.equal(parsed.global.registryVersion, "999.0.0"); - assert.ok(renderDoctorReport(parsed).includes("bili doctor")); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-run-")); + const urls: string[] = []; + const runWithFetch = mockFetch((url) => { + urls.push(url); + return new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }); + try { + await runWithFetch(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: undefined, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + assert.ok( + urls.some((u) => + u.includes("registry.npmjs.org/billion-context/latest"), + ), + `registry URL hit: ${urls.join(", ")}`, + ); + assert.equal(report.global.registryVersion, "999.0.0"); + assert.equal(report.global.updateTag, "latest"); + assert.deepEqual( + report.lanes.map((l) => l.agent).sort(), + [...PLUGIN_AGENTS].sort(), + ); + for (const lane of report.lanes) { + assert.equal( + lane.installed, + false, + `${lane.agent} should be absent in an empty sandbox`, + ); + assert.equal(lane.verdict, "absent"); + assert.equal(lane.registryVersion, "999.0.0"); + } + assert.deepEqual(report.processes, []); + if (report.global.form === "checkout") { + assert.equal(report.global.verdict, "frozen"); + } else { + assert.ok(["ok", "stale"].includes(report.global.verdict)); + } + const parsed = JSON.parse( + JSON.stringify(report, null, 2), + ) as DoctorReport; + assert.equal(parsed.global.registryVersion, "999.0.0"); + assert.ok(renderDoctorReport(parsed).includes("bili doctor")); + }, + ); + }); + } finally { + rmrf(base); + } }); test("runDoctor: unreachable registry never produces a false-stale verdict", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-run-")); - const runWithFetch = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); - try { - await runWithFetch(async () => { - await withEnv({ - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: undefined, - }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); - assert.equal(report.global.registryVersion, undefined); - assert.match(report.global.reason ?? "", /registry unreachable/); - for (const lane of report.lanes) { - assert.notEqual(lane.verdict, "stale"); - } - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-run-")); + const runWithFetch = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); + try { + await runWithFetch(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: undefined, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + assert.equal(report.global.registryVersion, undefined); + assert.match(report.global.reason ?? "", /registry unreachable/); + for (const lane of report.lanes) { + assert.notEqual(lane.verdict, "stale"); + } + }, + ); + }); + } finally { + rmrf(base); + } }); -function advisoryDocFor(entries: Array<{ id: string; affected: string; target: string; reason: string }>): Record { - return { billionContextAdvisories: { schema: 1, updated: "2026-09-28", advisories: entries } }; +function advisoryDocFor( + entries: Array<{ + id: string; + affected: string; + target: string; + reason: string; + }>, +): Record { + return { + billionContextAdvisories: { + schema: 1, + updated: "2026-09-28", + advisories: entries, + }, + }; } const ADVISORY_URL = "https://registry.test/bc-advisories.json"; function doctorSandboxEnv(base: string): Record { - return { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, PI_HOME: undefined, DSH_HOME: undefined, HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, CODEX_HOME: undefined, CLAUDE_CONFIG_DIR: undefined, OPENCODE_CONFIG: undefined, - }; + return { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: undefined, + }; } test("#1577: bili doctor reports an active advisory against the on-disk version", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-adv-")); - const advDoc = advisoryDocFor([{ id: "bc-2026-001", affected: ">=0.0.0", target: "99.0.0", reason: "corrupts tool-call arguments" }]); - const runWithFetch = mockFetch((url) => - url.includes("bc-advisories.json") - ? new Response(JSON.stringify(advDoc)) - : new Response(JSON.stringify({ name: "billion-context", version: "999.0.0" }), { status: 200, headers: { "content-type": "application/json" } }), - ); - try { - await runWithFetch(async () => { - await withEnv(doctorSandboxEnv(base), async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143", advisoryUrl: ADVISORY_URL }); - assert.equal(report.global.advisory?.error, undefined); - assert.equal(report.global.advisory?.active?.id, "bc-2026-001"); - assert.equal(report.global.advisory?.active?.currentVersion, report.global.diskVersion ?? "0.1.143"); - const text = renderDoctorReport(report); - assert.match(text, /advisory ⚠️ \[bc-2026-001\] .*corrupts tool-call arguments/); - assert.ok(text.includes("npm install -g billion-context@99.0.0")); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-adv-")); + const advDoc = advisoryDocFor([ + { + id: "bc-2026-001", + affected: ">=0.0.0", + target: "99.0.0", + reason: "corrupts tool-call arguments", + }, + ]); + const runWithFetch = mockFetch((url) => + url.includes("bc-advisories.json") + ? new Response(JSON.stringify(advDoc)) + : new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ); + try { + await runWithFetch(async () => { + await withEnv(doctorSandboxEnv(base), async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + advisoryUrl: ADVISORY_URL, + }); + assert.equal(report.global.advisory?.error, undefined); + assert.equal(report.global.advisory?.active?.id, "bc-2026-001"); + assert.equal( + report.global.advisory?.active?.currentVersion, + report.global.diskVersion ?? "0.1.143", + ); + const text = renderDoctorReport(report); + assert.match( + text, + /advisory {6}⚠️ \[bc-2026-001\] .*corrupts tool-call arguments/, + ); + assert.ok(text.includes("npm install -g billion-context@99.0.0")); + }); + }); + } finally { + rmrf(base); + } }); test("#1577: bili doctor reports a clean advisory state as 'none' and a failed source as unknown", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-adv-none-")); - const cleanDoc = advisoryDocFor([]); - const runClean = mockFetch((url) => - url.includes("bc-advisories.json") - ? new Response(JSON.stringify(cleanDoc)) - : new Response(JSON.stringify({ name: "billion-context", version: "999.0.0" }), { status: 200, headers: { "content-type": "application/json" } }), - ); - try { - await runClean(async () => { - await withEnv(doctorSandboxEnv(base), async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143", advisoryUrl: ADVISORY_URL }); - assert.equal(report.global.advisory?.active, undefined); - assert.equal(report.global.advisory?.error, undefined); - assert.match(renderDoctorReport(report), /advisory none/); - }); - }); - const runFail = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); - await runFail(async () => { - await withEnv(doctorSandboxEnv(base), async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143", advisoryUrl: ADVISORY_URL }); - assert.equal(report.global.advisory?.active, undefined); - assert.match(report.global.advisory?.error ?? "", /ENOTFOUND|fetch/i); - assert.match(renderDoctorReport(report), /advisory check failed .*— status unknown/); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-adv-none-")); + const cleanDoc = advisoryDocFor([]); + const runClean = mockFetch((url) => + url.includes("bc-advisories.json") + ? new Response(JSON.stringify(cleanDoc)) + : new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ); + try { + await runClean(async () => { + await withEnv(doctorSandboxEnv(base), async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + advisoryUrl: ADVISORY_URL, + }); + assert.equal(report.global.advisory?.active, undefined); + assert.equal(report.global.advisory?.error, undefined); + assert.match(renderDoctorReport(report), /advisory {6}none/); + }); + }); + const runFail = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); + await runFail(async () => { + await withEnv(doctorSandboxEnv(base), async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + advisoryUrl: ADVISORY_URL, + }); + assert.equal(report.global.advisory?.active, undefined); + assert.match(report.global.advisory?.error ?? "", /ENOTFOUND|fetch/i); + assert.match( + renderDoctorReport(report), + /advisory {6}check failed .*— status unknown/, + ); + }); + }); + } finally { + rmrf(base); + } }); diff --git a/tsup.config.ts b/tsup.config.ts index e25f2505f5..d83831732b 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -3,90 +3,122 @@ import { fileURLToPath } from "node:url"; import { defineConfig } from "tsup"; export default [ -defineConfig({ - entry: ["src/index.ts", "src/mcp.ts", "src/claude-native-bootstrap.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/omp.ts", "src/agent/omp-native.ts", "src/agent/opencode.ts", "src/agent/opencode-native.ts", "src/agent/dsh-acp.ts", "src/agent/dsh-native.ts", "src/kimi/native-mcp.ts", "src/kimi/bootstrap-hook.ts", "src/zcode/mcp-entry.ts", "src/zcode/bootstrap-hook.ts"], - format: ["esm"], - target: "node20", - platform: "node", - // Non-minified esbuild output KEEPS JSDoc comments attached to class - // members (verified empirically against esbuild bundled with tsup 8.x): - // undici ships class-body JSDoc like `@param {import('./client.js')}` and - // those annotations survive into dist verbatim. Node's ESM loader ignores - // them, but opencode's plugin loader resolves them as REAL files and dies - // with ENOENT → the whole plugin fails to load (silent dead lane; see the - // issue filed from #1234). minifyWhitespace makes esbuild drop all - // non-legal comments while keeping code structure intact (no identifier - // mangling, no syntax rewriting); legal/license footers stay via the - // default legalComments. scripts/check-dist-import-annotations.mjs fails - // the build if any relative import()/require() text ever reappears. - esbuildOptions(options) { - options.minifyWhitespace = true; - // #2186: billion-context-pi-subagents is inlined via noExternal, and - // its ONLY runtime host import is a namespace import of - // @earendil-works/pi-coding-agent (config-dir reads CONFIG_DIR_NAME, - // falling back to ".pi" when absent — the package's documented - // degradation for aliased hosts). Alias it to an empty stub so the - // bundle keeps bili's zero-runtime-dependency contract; no bili entry - // ever imports the real package. - options.alias = { "@earendil-works/pi-coding-agent": resolve(dirname(fileURLToPath(import.meta.url)), "src/agent/pi-host-stub.ts") }; - }, - outDir: "dist", - clean: true, - sourcemap: true, - splitting: false, - shims: false, - // acp-kernel is a BUILD-TIME dependency: tsup inlines it into dist so the - // published artifact is self-contained (zero runtime deps). Without - // noExternal, esbuild keeps `import ... from "acp-kernel"` in dist, and - // npm then installs acp-kernel as a runtime dep — breaking the - // "dist/index.js is self-contained" contract (AGENTS.md §2.1). Same for - // billion-context-pi-subagents (#2384): vendored under pi-subagents/, - // consumed via file:, and its own build already inlines its typebox peer, - // so its dist is self-contained too. - noExternal: ["acp-kernel", "billion-context-pi-subagents", "fzstd", "node-forge", "semver", "tar", "undici", "jsonc-parser", "ws"], - // sharp is an OPTIONAL runtime dependency (native module): it must stay - // EXTERNAL so dist keeps a real lazy `import("sharp")` that Node resolves - // at runtime from node_modules — missing ⇒ clean pass-through, and the - // bundle stays independent of which sharp version npm resolved (the caret - // range in optionalDependencies would otherwise bake that version into - // dist and break reproducible builds). tsup does not auto-externalize - // optionalDependencies, hence the explicit entry. - external: ["sharp"], - banner: { - // node-forge is a CommonJS dependency that calls require("crypto") etc. - // inlined into our ESM output, esbuild's __require shim throws in an - // ESM context where `require` is undefined. Provide a real require - // (via createRequire) so the shim can load node built-ins. Only node - // built-ins ever reach this path — node-forge is otherwise bundled. - js: "import { createRequire as __biliCreateRequire } from 'node:module';\nconst require = __biliCreateRequire(import.meta.url);", - }, -}), -// #1590: dsh web-profile settings entry (dsh.client browser half). Built as a -// classic script: CJS body wrapped in window.__ModuleLoader__.load({id, -// factory}) — the banner/footer locals shadow module/exports so esbuild's CJS -// output lands inside the factory closure, whose `require` parameter resolves -// externals through dsh's module system (react stays external; nothing else -// may be required). No clean here: this runs after the main config above. -defineConfig({ - entry: { "agent/dsh-native-client": "src/agent/dsh-native-client.ts" }, - format: ["cjs"], - target: "es2020", - platform: "browser", - external: ["react"], - outDir: "dist", - clean: false, - splitting: false, - shims: false, - // Keep the .js name (not tsup's default .cjs): this is a browser classic - // script, not a node CJS artifact, and package.json points at it as-is. - outExtension: () => ({ js: ".js" }), - banner: { - // Trailing balance: `load({ id, factory: (require) => {` opens call + - // object + arrow-body, so the footer closes all three. - js: "window.__ModuleLoader__.load({ id: \"billion-context\", factory: (require) => {\nvar module = { exports: {} };\nvar exports = module.exports;\n", - }, - footer: { - js: "\nreturn module.exports;\n}});", - }, -}), + defineConfig({ + entry: [ + "src/index.ts", + "src/mcp.ts", + "src/claude-native-bootstrap.ts", + "src/agent/pi.ts", + "src/agent/pi-native.ts", + "src/agent/omp.ts", + "src/agent/omp-native.ts", + "src/agent/opencode.ts", + "src/agent/opencode-native.ts", + "src/agent/dsh-acp.ts", + "src/agent/dsh-native.ts", + "src/kimi/native-mcp.ts", + "src/kimi/bootstrap-hook.ts", + "src/zcode/mcp-entry.ts", + "src/zcode/bootstrap-hook.ts", + "src/codex/bootstrap-hook.ts", + ], + format: ["esm"], + target: "node20", + platform: "node", + // Non-minified esbuild output KEEPS JSDoc comments attached to class + // members (verified empirically against esbuild bundled with tsup 8.x): + // undici ships class-body JSDoc like `@param {import('./client.js')}` and + // those annotations survive into dist verbatim. Node's ESM loader ignores + // them, but opencode's plugin loader resolves them as REAL files and dies + // with ENOENT → the whole plugin fails to load (silent dead lane; see the + // issue filed from #1234). minifyWhitespace makes esbuild drop all + // non-legal comments while keeping code structure intact (no identifier + // mangling, no syntax rewriting); legal/license footers stay via the + // default legalComments. scripts/check-dist-import-annotations.mjs fails + // the build if any relative import()/require() text ever reappears. + esbuildOptions(options) { + options.minifyWhitespace = true; + // #2186: billion-context-pi-subagents is inlined via noExternal, and + // its ONLY runtime host import is a namespace import of + // @earendil-works/pi-coding-agent (config-dir reads CONFIG_DIR_NAME, + // falling back to ".pi" when absent — the package's documented + // degradation for aliased hosts). Alias it to an empty stub so the + // bundle keeps bili's zero-runtime-dependency contract; no bili entry + // ever imports the real package. + options.alias = { + "@earendil-works/pi-coding-agent": resolve( + dirname(fileURLToPath(import.meta.url)), + "src/agent/pi-host-stub.ts", + ), + }; + }, + outDir: "dist", + clean: true, + sourcemap: true, + splitting: false, + shims: false, + // acp-kernel is a BUILD-TIME dependency: tsup inlines it into dist so the + // published artifact is self-contained (zero runtime deps). Without + // noExternal, esbuild keeps `import ... from "acp-kernel"` in dist, and + // npm then installs acp-kernel as a runtime dep — breaking the + // "dist/index.js is self-contained" contract (AGENTS.md §2.1). Same for + // billion-context-pi-subagents (#2384): vendored under pi-subagents/, + // consumed via file:, and its own build already inlines its typebox peer, + // so its dist is self-contained too. + noExternal: [ + "acp-kernel", + "billion-context-pi-subagents", + "fzstd", + "node-forge", + "semver", + "tar", + "undici", + "jsonc-parser", + "ws", + ], + // sharp is an OPTIONAL runtime dependency (native module): it must stay + // EXTERNAL so dist keeps a real lazy `import("sharp")` that Node resolves + // at runtime from node_modules — missing ⇒ clean pass-through, and the + // bundle stays independent of which sharp version npm resolved (the caret + // range in optionalDependencies would otherwise bake that version into + // dist and break reproducible builds). tsup does not auto-externalize + // optionalDependencies, hence the explicit entry. + external: ["sharp"], + banner: { + // node-forge is a CommonJS dependency that calls require("crypto") etc. + // inlined into our ESM output, esbuild's __require shim throws in an + // ESM context where `require` is undefined. Provide a real require + // (via createRequire) so the shim can load node built-ins. Only node + // built-ins ever reach this path — node-forge is otherwise bundled. + js: "import { createRequire as __biliCreateRequire } from 'node:module';\nconst require = __biliCreateRequire(import.meta.url);", + }, + }), + // #1590: dsh web-profile settings entry (dsh.client browser half). Built as a + // classic script: CJS body wrapped in window.__ModuleLoader__.load({id, + // factory}) — the banner/footer locals shadow module/exports so esbuild's CJS + // output lands inside the factory closure, whose `require` parameter resolves + // externals through dsh's module system (react stays external; nothing else + // may be required). No clean here: this runs after the main config above. + defineConfig({ + entry: { "agent/dsh-native-client": "src/agent/dsh-native-client.ts" }, + format: ["cjs"], + target: "es2020", + platform: "browser", + external: ["react"], + outDir: "dist", + clean: false, + splitting: false, + shims: false, + // Keep the .js name (not tsup's default .cjs): this is a browser classic + // script, not a node CJS artifact, and package.json points at it as-is. + outExtension: () => ({ js: ".js" }), + banner: { + // Trailing balance: `load({ id, factory: (require) => {` opens call + + // object + arrow-body, so the footer closes all three. + js: 'window.__ModuleLoader__.load({ id: "billion-context", factory: (require) => {\nvar module = { exports: {} };\nvar exports = module.exports;\n', + }, + footer: { + js: "\nreturn module.exports;\n}});", + }, + }), ]; From 51f3dfa6742b5836c758e9c8db26619665663345 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 21:38:14 +0800 Subject: [PATCH 03/20] fix: restore 22 files the branch had silently pinned to pre-fork state The branch diverged from master at 7f96abe and carried repo-wide whitespace-reformatted copies of files master advanced afterwards (#3063 egressTransportFields + WC-017 wire-contract entry, #2877 attachPolicy/attachUrl config surface, restart/instance/port-zone work, CHANGELOG/CONFIGURATION/TECHNICAL-NOTES updates). The merge kept the stale copies, so merging as-is would have reverted that work. Restore every such file verbatim from origin/master. None of these files carries any semantic edit from the branch (verified: zero ignore-whitespace footprint vs fork point). Part of #3176 (conflict takeover). --- CHANGELOG.md | 1 + CONFIGURATION.md | 19 ++- CONFIGURATION.zh-CN.md | 19 ++- TECHNICAL-NOTES.md | 6 +- TECHNICAL-NOTES.zh-CN.md | 4 +- src/config.ts | 79 ++++++++--- src/instance.ts | 22 +++ src/launcher.ts | 66 +++++++-- src/listen-policy.ts | 73 ++++++++++ src/responses-ws.ts | 23 +++- src/restart.ts | 121 +++++++++++++++-- src/server.ts | 52 ++++++-- tests/auto-restart.test.ts | 177 ++++++++++++++++++++++++- tests/claude-native.test.ts | 65 ++++++++- tests/codex-responses-ws.test.ts | 12 ++ tests/launcher.test.ts | 119 ++++++++++++++++- tests/listen-policy.test.ts | 90 +++++++++++++ tests/port-zone-live.test.ts | 109 ++++++++++++++- tests/wire-contract-fakes.ts | 26 +++- tests/wire-contract.test.ts | 15 ++- website/config-reference/env-only.yaml | 8 ++ website/config-reference/server.yaml | 14 ++ 22 files changed, 1036 insertions(+), 84 deletions(-) create mode 100644 src/listen-policy.ts create mode 100644 tests/listen-policy.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index bcbd058ec7..0bb8d27e9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag independent #1729 wire-level dsh-compaction refusal, the #2709 framing-absent rewrite attribution, and the #2695 majority-absent zombie reap (its `orphan-reap` ledger record); none of those paths are touched here. Goldens: metadata-only drift, exactly the new latch. +- **Self-restart: replacement no longer hops to the next port when the target port is occupied (#3044)** — with `autoRestartOnUpdate`, a replacement spawned while the old instance still held its port (or a racing process took it during the drain window) inherited the launcher's EADDRINUSE ladder and silently drifted to P+1, P+2, …: idle orphans serving no client while the prior instance never exited (reported shape: 14 orphans over 9 h, ~8 GB private memory combined). Now the replacement is marked at spawn (`BILI_UPGRADE_REPLACEMENT=1`, internal spawn channel) and must bind EXACTLY the freed port — after the bounded same-lane predecessor wait of #1723 — or fail fast with exit code 1 and a clear log line ("upgrade pending; the host decides retry"). The parent verifies the handover against the replacement's own registry record (pid + port it ACTUALLY bound) instead of a raw TCP answer: bound the wrong port → terminated, kill verified, service resumes; another live bili instance already owns the port → the upgrade counts as landed there and the parent exits cleanly instead of resuming an old-code copy that would ladder-drift into its own zombie; a kill that does not take effect escalates loudly with a manual-cleanup hint. A foreign non-bili squatter keeps today's resume behavior. A lane'd spawn that races a LIVE same-build instance on the same port (the host-respawn trigger path of the 2026-10-13 recurrence) now exits loudly instead of hopping: the duplicate loses, the serving instance keeps serving, and the next launch attaches to it. Tests: tests/listen-policy.test.ts (policy matrix), auto-restart.test.ts (marker env, misplaced termination, supersede-exit, unkillable escalation), port-zone-live.test.ts (live fail-fast end-to-end, CI lane). - **Storage: drop the `better-sqlite3` optional dependency (#2823)** — the native SQLite engine lived in `optionalDependencies`, but pnpm ≥10's strict build-script gate (`strictDepBuilds`) blocks any unlisted install script and treats it as a hard error, so dsh plugin-market installs/updates on fresh profiles failed with `[ERR_PNPM_IGNORED_BUILDS] better-sqlite3`. Unified storage is OFF by default (legacy file persistence), so dropping the optional native engine is low-impact: the driver already prefers built-in `node:sqlite` when the native module is absent, and when no engine is available at all `UnifiedShadow.maybeOpen` degrades to legacy-only (one warn, never bricks). New tests pin the no-engine contract (`tests/storage-engine-proofs.test.ts`: `maybeOpen` → null; `SessionStore` runs legacy-only, writes survive, no `index.db`). The opportunistic `require("better-sqlite3")` probe is kept, so hosts that still have the native module keep using it. The dsh-side fix (downgrading build-blocking of *optional* deps to non-fatal) is tracked separately. - **Inbound markers: one declarative engine for all four wires (#2789, #2798, #2811 plan B)** — the per-protocol inbound stripping calls (panel → status markers → chain carriers, each wired diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 26cdb71b63..cf2f3435df 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -118,6 +118,8 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `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) | — | 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. | +| `native.attachPolicy` | "own-lane" \| "global-fallback" | own-lane | BILI_NATIVE_ATTACH_POLICY | Lane affinity for native-hook attach, and the gate on whether any cross-lane riding happens (#2877). own-lane (default): a LANEd hook rides ONLY a same-lane daemon and, with none available, spawns its own instead of falling back onto a lane-less / manually-started bili start daemon or another lane's daemon (that convergence pinned every agent to one daemon's version and double-wrote sessions); an armed lane-less daemon (a managed shared proxy, #1225) stays shareable under either policy. global-fallback restores the pre-#2877 behavior: same-lane first, then a compatible lane-less/user-zone daemon, and (with attachLanePriority) the listed foreign lanes. | +| `native.attachUrl` | string | unset (discover per lane) | BILI_MCP_PROXY | Explicit target origin for native-hook attach (any URL). When set, a hook attaches ONLY to that exact origin instead of auto-discovering, and spawns its own if it is not live; it must still be code-compatible and pass the lifecycle gate. The BILI_MCP_PROXY env var (also set by CLI --origin) takes precedence over this file value; empty/whitespace means unset. | | `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. | @@ -331,6 +333,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `BILI_MCP_PROXY` | string | unset | — | Spawn channel: MCP proxy target for plugin-hosted tools. | | `BILI_PARENT_PID` | number | unset | — | Spawn channel: parent process id for lifecycle supervision. | | `BILI_STRICT_PORT` | number | unset | — | Spawn channel: exact-port requirement (squatters refused loudly instead of hopping). | +| `BILI_UPGRADE_REPLACEMENT` | boolean-ish | unset | — | Spawn channel: marks a self-restart replacement — it must own exactly the freed port or exit without hopping (#3044). | | `BILI_OPENCODE_ACP_SPEC` | string | unset | — | Spawn channel: ACP spec marker for opencode-native lanes. | | `BILI_LAUNCHER_MODEL_WINDOWS` | string | unset | — | Launcher channel: model-window overrides passed into spawned clients. | | `BILI_LAUNCHER_LANE` | string | unset | — | Launcher channel: lane identity of the spawning bili process. | @@ -708,11 +711,15 @@ Top-level keys that control how the proxy listens and behaves globally. ### `native` -- **Type:** `{ attachExternal?: boolean; attachLanePriority?: string[] }` -- **Default:** `{}` (attach gate closed for lane'd instances; no foreign lanes listed) +- **Type:** `{ attachExternal?: boolean; attachLanePriority?: string[]; attachPolicy?: "own-lane" | "global-fallback"; attachUrl?: string }` +- **Default:** `{}` (own-lane policy; 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"] }`. +- **Description:** Native-hook attach selection (#1335, #1660, #2905, #2877). A native hook may ride an already-running proxy instead of spawning its own when it is code-compatible and passes the lifecycle gate (`watchdog.armed == true`, or `attachExternal: true`). Four independent knobs shape *which* proxy it rides: + - **`attachPolicy`** (default `"own-lane"`, env `BILI_NATIVE_ATTACH_POLICY`) — lane affinity, and the gate on whether cross-lane riding happens at all. `"own-lane"`: a LANEd hook rides ONLY a same-lane daemon; with none available it **spawns its own** instead of falling back onto a lane-less / manually-started `bili start` daemon or another lane's daemon (that convergence pinned every agent to one daemon's version and double-wrote sessions, #2877). An **armed** lane-less daemon (a managed shared proxy, #1225) stays shareable under either policy. `"global-fallback"` restores the pre-#2877 behavior: same-lane first, then a compatible lane-less/user-zone daemon (and, with `attachLanePriority`, the listed foreign lanes). + - **`attachLanePriority`** (#2905, file-only, no env var) — ordered list of FOREIGN lane names this hook may ride when no own-lane instance exists. Where cross-lane riding is allowed (i.e. under `global-fallback`), attach priority is: 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"] }`. + - **`attachUrl`** (env `BILI_MCP_PROXY`, which also accepts `--origin`; the env wins) — an explicit target origin (any local or remote URL). When set, discovery attaches ONLY to that exact origin (bypassing the policy filter); if it is unreachable or incompatible the hook spawns its own instead of hard-failing. This is how a host pins itself to one specific resident daemon. + - **`attachExternal`** (env `BILI_NATIVE_ATTACH_EXTERNAL`) — the lifecycle-gate escape hatch: `true` attaches to *lane'd* unarmed listeners too (any code/lane-compatible listener regardless of watchdog state, incl. pre-#1330 builds) and bypasses the `own-lane` affinity filter entirely (fully permissive). It does NOT change which lane's daemon is preferred — that is `attachPolicy`. Precedence: `1` opens the gate even over a closed file; `0` closes it even over a permissive file. + - **Behavior change (#2877):** the DEFAULT flipped from “a LANEd hook falls back to riding a compatible lane-less/manual daemon” to “it spawns its own.” If you relied on one manual `bili start` daemon serving all native agents, set `native.attachPolicy: "global-fallback"` (or keep `BILI_NATIVE_ATTACH_EXTERNAL=1`). Full mechanics: [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660). ### `pi` @@ -1645,10 +1652,12 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_LOG_MASK_HOSTS` | `maskHosts` | true | | `BILI_MAX_SESSIONS` | `sessions.max` | 256 | | `BILI_MAX_SHRINK_PER_COMPRESS` | `network.maxShrinkPerCompress` | unset | +| `BILI_MCP_PROXY` | `native.attachUrl` | unset (discover per lane) | | `BILI_MITM` | `mitm.enabled` | true | | `BILI_MITM_DOMAINS` | `mitm.domains` | [] | | `BILI_MITM_HANDSHAKE_TIMEOUT_MS` | `mitm.handshakeTimeoutMs` | 10000 | | `BILI_NATIVE_ATTACH_EXTERNAL` | `native.attachExternal` | false | +| `BILI_NATIVE_ATTACH_POLICY` | `native.attachPolicy` | own-lane | | `BILI_NON_HTTP_PROVIDERS` | `compactionOptIn` | false | | `BILI_NO_CACHE_CONTROL` | `compat.noCacheControl` | false | | `BILI_PERSIST` | `persist.enabled` | true | @@ -1792,7 +1801,7 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_LAUNCHER_LANE` | Internal: the launcher hands its client's lane name (pi / codex / claude / …) to the spawned proxy, which records it in the instance file (#1225). Reuse is identity-based: two instances with *different declared* lanes never attach to each other; an instance without a declared lane is a manually-started user-zone daemon — attachable by default (#1660). Only the launcher sets it — no user configuration. | | `BILI_LAUNCHER_PLUGIN` | Set `0` to disable the launcher's bili MCP server injection for claude/codex (pure wire mode); `1` forces plugin mode. Default: injected — except codex with a local/private upstream (sglang/vllm/ollama cannot parse codex's namespace tool type, so bili auto-falls back to wire tools there). See [Launcher Reference](#launcher-reference). | | `BILI_LAUNCHER_DIRECT` | Set `1` for direct-URL routing in the launcher (drop MITM/CA trust). See [Launcher Reference](#launcher-reference). | - | `BILI_NATIVE_ATTACH_EXTERNAL` | Attach-gate escape hatch (#1335). Lane'd native hooks attach to a running proxy only when it reports an armed session-lifecycle watchdog (`watchdog.armed == true` in `/__bili/health`) — an unarmed *lane'd* proxy (a crashed session's orphan, or an instance whose lifecycle state cannot be verified) is refused loudly instead of being silently ridden. #1660: a **manually started `bili start` daemon** (no lane, no launch token) is user-zone by definition — native hooks attach to it by default, so a deliberate resident daemon “just works” without this env; you then own its lifetime and version. Set `1`/`true` to also attach to *lane'd* unarmed listeners anyway: any code/lane-compatible listener becomes attachable regardless of watchdog state (including pre-#1330 builds that report no `watchdog` field at all). `"native": { "attachExternal": true }` in the config file does the same; the env var wins (`0`/`false` closes the gate even over a permissive file — including for user-zone daemons, forcing fresh lane spawns). Default is closed (for lane'd instances). Full mechanics (reuse rules, listener table, escape hatch): [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660). | + | `BILI_NATIVE_ATTACH_EXTERNAL` | Attach-gate escape hatch (#1335). Lane'd native hooks attach to a running proxy only when it reports an armed session-lifecycle watchdog (`watchdog.armed == true` in `/__bili/health`) — an unarmed *lane'd* proxy (a crashed session's orphan, or an instance whose lifecycle state cannot be verified) is refused loudly instead of being silently ridden. #1660: a **manually started `bili start` daemon** (no lane, no launch token) is user-zone by definition — an **armed** user-zone daemon (a managed shared proxy, #1225) is still ridden by any compatible client lane, but an **unarmed** manual daemon is, by default (`attachPolicy: "own-lane"`, #2877), NOT ridden by a LANEd hook, which spawns its own instead; set `attachPolicy: "global-fallback"` to restore the pre-#2877 behavior where native hooks attach to a manual daemon by default. Set `1`/`true` to also attach to *lane'd* unarmed listeners anyway: any code/lane-compatible listener becomes attachable regardless of watchdog state (including pre-#1330 builds that report no `watchdog` field at all). `"native": { "attachExternal": true }` in the config file does the same; the env var wins over the file value. Note: `attachExternal` governs only the *lifecycle gate* for **lane'd** daemons — it does not open or close attachment to a user-zone (manual) daemon; that axis is `attachPolicy` / `attachUrl`. Default is closed (for lane'd instances). Full mechanics (reuse rules, listener table, escape hatch): [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660). | | `BILI_ZCODE_ROUTE` | zcode native-plugin routing scope (#1622): `all` (default — every provider entry with a usable http(s) baseURL rides compression, pi/dsh parity), `plans` (pre-#1622 bigmodel coding-plan whitelist), `none` (opt out; the bootstrap leaves the store direct). Compat escape hatch — there is **no** file equivalent; routing is on by default. | | `BILI_ZONE_PORT` | Base of the self-managed port zone (#1660, default `18787`): every *lane-spawned* proxy (claude/zcode native hooks, launcher lanes riding port 0) tries the lane's sticky record first, else this base; port collisions resolve via the child's +1 ladder — except when the holder is a same-lane predecessor running a different build (an upgrade-restart overlap), which the child waits out (up to 5s) and then rebinds the SAME port instead of drifting (#1723) — and the settled port is recorded sticky under `/port-zone.json` so later launches follow drift automatically. Manual `bili start` keeps its own default (`8787`) — the user zone is never touched by lanes. | | `BILI_ZCODE_PORT` | Pin an **exact** port for the zcode native lane's proxy (#1660): the launch becomes strict-port — a squatter is refused loudly instead of hopping — and wrappers written into the shared store survive session restarts even without handoff. Without it the lane rides the self-managed zone (`BILI_ZONE_PORT` base + sticky drift following). | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 59bf5b3780..e7dbcf71ce 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -118,6 +118,8 @@ | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | 面向缓存感知路由选择的提示词缓存路由姿态。 | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | 允许无启动器的原生插件挂到外部(车道化、未武装看门狗)守护进程,而不是自行派生。 | | `native.attachLanePriority` | string[] | [] (own lane → user zone → spawn) | — | 本 lane 没有自己的实例时可搭车的外部 lane 名字有序列表(#2905)。本 lane 永远第一;用户区(手动 bili start、8787 全局)永远最后;未列出的 lane 仍不可挂。仅配置文件,无 env。 | +| `native.attachPolicy` | "own-lane" \| "global-fallback" | own-lane | BILI_NATIVE_ATTACH_POLICY | native hook 附着的 lane 亲和,也是是否发生跨 lane 搭车的总闸(#2877)。own-lane(默认):lane 型 hook 只搭同 lane 的守护;没有时自行派生,而不是回落到无 lane / 手动启动的 bili start 守护或其他 lane 的守护(那种汇聚会把所有 agent 钉死在一台守护的版本上并双写会话);已武装的无 lane 守护(受管共享代理,#1225)在两种策略下都可被搭车。global-fallback 恢复 #2877 之前的行为:先同 lane,再兼容的无 lane/用户区守护,以及(配 attachLanePriority)列出的外部 lane。 | +| `native.attachUrl` | string | unset (discover per lane) | BILI_MCP_PROXY | native hook 附着的显式目标源(任意 URL)。设置后,hook 只附着到该精确 origin 而不是自动发现,若其不在线则自行派生;仍需代码兼容并通过生命周期门禁。BILI_MCP_PROXY 环境变量(CLI --origin 亦会设置它)优先于此文件值;空/空白视为未设置。 | | `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 段。 | @@ -331,6 +333,7 @@ | `BILI_MCP_PROXY` | string | unset | — | 派生通道:插件宿主工具的 MCP 代理目标。 | | `BILI_PARENT_PID` | number | unset | — | 派生通道:父进程 id,用于生命周期监管。 | | `BILI_STRICT_PORT` | number | unset | — | 派生通道:精确端口要求(被占用时响亮拒绝而非跳端口)。 | +| `BILI_UPGRADE_REPLACEMENT` | boolean-ish | unset | — | 派生通道:标记自重启替换进程——必须独占被释放的精确端口,否则直接退出而非跳端口(#3044)。 | | `BILI_OPENCODE_ACP_SPEC` | string | unset | — | 派生通道:opencode 原生车道的 ACP 规格标记。 | | `BILI_LAUNCHER_MODEL_WINDOWS` | string | unset | — | 启动器通道:传入被派生客户端的模型窗口覆盖。 | | `BILI_LAUNCHER_LANE` | string | unset | — | 启动器通道:派生方 bili 进程的车道身份。 | @@ -708,11 +711,15 @@ ### `native` -- **类型:** `{ attachExternal?: boolean; attachLanePriority?: string[] }` -- **默认值:** `{}`(lane'd 实例的 attach 门关闭;无外部 lane 列表) +- **类型:** `{ attachExternal?: boolean; attachLanePriority?: string[]; attachPolicy?: "own-lane" | "global-fallback"; attachUrl?: string }` +- **默认值:** `{}`(own-lane 策略;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"] }`。 +- **说明:** native hook 附着选择(#1335、#1660、#2905、#2877)。当 native hook 代码兼容且通过生命周期门禁(`watchdog.armed == true`,或 `attachExternal: true`)时,可搭车一个已在运行的代理而不是自行派生。四个独立开关决定它搭哪台: + - **`attachPolicy`**(默认 `"own-lane"`,env `BILI_NATIVE_ATTACH_POLICY`)—— lane 亲和,也是“是否发生跨 lane 搭车”的总闸。`"own-lane"`:lane 型 hook 只搭同 lane 的守护;没有时**自行派生**,而不是回落到无 lane / 手动启动的 `bili start` 守护或其他 lane 的守护(那种汇聚会把所有 agent 钉死在一台守护的版本上并双写会话,#2877)。一台**已武装**的无 lane 守护(受管共享代理,#1225)在两种策略下都可被搭车。`"global-fallback"` 恢复 #2877 之前的行为:先同 lane,再兼容的无 lane/用户区守护(配 `attachLanePriority` 时还含列出的外部 lane)。 + - **`attachLanePriority`**(#2905,仅配置文件,无 env)—— 本 hook 在没有自己 lane 的实例时可搭车的**外部 lane** 名字有序列表。当跨 lane 搭车被允许时(即 `global-fallback` 下),attach 优先级为:本 lane 第一 → 按列表顺序的外部 lane → 用户区**永远最后**。未列出的 lane 仍不可挂(泳道隔离 #1225/#1232)。默认 `[]` = 本 lane → 用户区 → spawn。刻意做成显式 opt-in:外部实例的 MITM 白名单未必覆盖你的 provider,否则模型流量会盲隧道、所有压缩工具调用都会失败。对所有 lane 感知的 attach 点生效(launcher 各 lane + hermes 原生插件的发现路径)。示例:`"native": { "attachLanePriority": ["dsh"] }`。 + - **`attachUrl`**(env `BILI_MCP_PROXY`,同样接受 `--origin`;env 优先)—— 显式目标 origin(任意本地或远程 URL)。设置后,发现只附着到该确切 origin(绕过策略过滤);若它不可达或不兼容,hook 自行派生而非硬失败。这是宿主把自己钉到某台特定常驻守护的方式。 + - **`attachExternal`**(env `BILI_NATIVE_ATTACH_EXTERNAL`)—— 生命周期门禁逃生舱:`true` 时也附着到 *lane 型* 未武装 listener(任何 code/lane 兼容者无论看门狗状态,含 pre-#1330 构建),并整体绕过 `own-lane` 亲和过滤(完全宽松)。它不改变优先哪个 lane 的守护 —— 那是 `attachPolicy`。优先级:`1` 即使文件关闭也开门;`0` 即使文件宽松也关门。 + - **行为变更(#2877):** 默认从「lane 型 hook 回落到搭乘兼容的无 lane/手动守护」翻转为「自行派生」。若你依赖一台手动 `bili start` 守护服务所有 native agent,请设 `native.attachPolicy: "global-fallback"`(或保留 `BILI_NATIVE_ATTACH_EXTERNAL=1`)。完整机制见 [TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md#代理复用与附着门禁122513351232)。 ### `pi` @@ -1644,10 +1651,12 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `BILI_LOG_MASK_HOSTS` | `maskHosts` | true | | `BILI_MAX_SESSIONS` | `sessions.max` | 256 | | `BILI_MAX_SHRINK_PER_COMPRESS` | `network.maxShrinkPerCompress` | unset | +| `BILI_MCP_PROXY` | `native.attachUrl` | unset (discover per lane) | | `BILI_MITM` | `mitm.enabled` | true | | `BILI_MITM_DOMAINS` | `mitm.domains` | [] | | `BILI_MITM_HANDSHAKE_TIMEOUT_MS` | `mitm.handshakeTimeoutMs` | 10000 | | `BILI_NATIVE_ATTACH_EXTERNAL` | `native.attachExternal` | false | +| `BILI_NATIVE_ATTACH_POLICY` | `native.attachPolicy` | own-lane | | `BILI_NON_HTTP_PROVIDERS` | `compactionOptIn` | false | | `BILI_NO_CACHE_CONTROL` | `compat.noCacheControl` | false | | `BILI_PERSIST` | `persist.enabled` | true | @@ -1787,7 +1796,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `BILI_LAUNCHER_MODEL_WINDOWS` | 内部使用:launcher 把客户端自身配置里的逐模型上下文窗口(pi `models.json`、omp `models.yml`、opencode `models..limit`、codex `model_context_window`)以 JSON 传给自己拉起的代理,让 nudge 分母对自托管模型也用真实窗口。只有 launcher 会设置,无需用户配置。 | | `BILI_LAUNCHER_PLUGIN` | 设 `0` 关闭 launcher 为 claude/codex 注入 bili MCP 服务器(退回纯 wire 模式);设 `1` 强制插件模式。默认注入——但 codex 上游为本地/私网地址时自动退回 wire 模式(sglang/vllm/ollama 不解析 codex 的 namespace 工具类型)。见[启动器参考](#启动器参考)。 | | `BILI_LAUNCHER_DIRECT` | 设 `1` 启用 launcher 直连 URL 路由(放弃 MITM/CA 信任)。见[启动器参考](#启动器参考)。 | -| `BILI_NATIVE_ATTACH_EXTERNAL` | 附着门禁逃生舱(#1335)。lane 型原生 hook 只附着于报告了 armed 会话生命周期看门狗(`/__bili/health` 里 `watchdog.armed == true`)的代理——未武装的 lane 型代理(崩溃会话的孤儿、或生命周期状态无法核验的实例)被大声拒绝而不是被静默搭乘。#1660:**手工 `bili start` 守护进程**(无 lane、无 launch token)按定义属于用户主权区——原生 hook 默认直接附着,刻意运行的常驻守护进程无需此变量即可被共用;其寿命与版本由你自己负责。设 `1`/`true` 可以连 lane 型未武装监听者也一并附着:任何 code/lane 兼容的监听者无论看门狗状态都可附着(包括根本不报 `watchdog` 字段的 pre-#1330 构建)。配置文件里 `"native": { "attachExternal": true }` 等效;环境变量优先(`0`/`false` 即使文件开着也关门禁——对用户区守护进程同样生效,强制各 lane 自拉新代理)。默认关闭(针对 lane 型实例)。完整机制(复用规则、监听者表、逃生舱)见 [TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md#代理复用与附着门禁122513351232)。 | +| `BILI_NATIVE_ATTACH_EXTERNAL` | 附着门禁逃生舱(#1335)。lane 型原生 hook 只附着于报告了 armed 会话生命周期看门狗(`/__bili/health` 里 `watchdog.armed == true`)的代理——未武装的 lane 型代理(崩溃会话的孤儿、或生命周期状态无法核验的实例)被大声拒绝而不是被静默搭乘。#1660:**手工 `bili start` 守护进程**(无 lane、无 launch token)按定义属于用户主权区——一台**已武装**的用户区守护(受管共享代理,#1225)仍会被任何兼容 client lane 搭车;但一台**未武装**的手动守护在默认(`attachPolicy: "own-lane"`,#2877)下**不会**被 lane 型 hook 搭车 —— 它自行派生;设 `attachPolicy: "global-fallback"` 恢复 #2877 之前「原生 hook 默认附着手动守护」的行为。无论哪种情况,其寿命与版本都由你自己负责。设 `1`/`true` 可以连 lane 型未武装监听者也一并附着:任何 code/lane 兼容的监听者无论看门狗状态都可附着(包括根本不报 `watchdog` 字段的 pre-#1330 构建)。配置文件里 `"native": { "attachExternal": true }` 等效;环境变量优先于文件值。注意:`attachExternal` 只管辖 **lane 型**守护的*生命周期门禁* —— 它并不开/关对 user-zone(手动)守护的附着;那个轴是 `attachPolicy` / `attachUrl`。默认关闭(针对 lane 型实例)。完整机制(复用规则、监听者表、逃生舱)见 [TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md#代理复用与附着门禁122513351232)。 | | `BILI_ZCODE_ROUTE` | zcode 原生插件路由范围(#1622):`all`(默认 —— 每个有可用 http(s) baseURL 的 provider 条目都吃压缩,pi/dsh 对齐)、`plans`(#1622 前的 bigmodel coding-plan 白名单)、`none`(整体退出,bootstrap 不碰 store)。兼容逃生舱 —— **没有**文件等效项;路由默认即开启。 | | `BILI_ZONE_PORT` | 自管端口区基准(#1660,默认 `18787`):所有 lane 拉起的代理(claude/zcode 原生 hook、跑 0 号口的 launcher lane)先试该 lane 的粘性记录,否则这个基准口;端口碰撞由子进程 +1 阶梯解决(例外:占用者是同 lane 的旧版本实例——升级重启重叠时——子进程最多等 5 秒让它释放并复用同一端口,而不是漂移,#1723),落定的口记录在 `/port-zone.json` 粘性表里,后续拉起自动跟随漂移。手工 `bili start` 保持自己的默认口(`8787`)——lane 永不碰用户主权区。 | | `BILI_ZCODE_PORT` | 为 zcode 原生通道钉死**确切端口**(#1660):启动变为严格端口——占用者被大声拒绝而不是跳口——共享 store 里的包装也因此跨会话重启存活,无需交接。不设则通道骑自管区(`BILI_ZONE_PORT` 基准 + 粘性漂移跟随)。 | diff --git a/TECHNICAL-NOTES.md b/TECHNICAL-NOTES.md index 56462d23ba..3a4402bbe2 100644 --- a/TECHNICAL-NOTES.md +++ b/TECHNICAL-NOTES.md @@ -23,12 +23,12 @@ A native hook may attach to an already-running proxy instead of spawning its own |---|---|---| | Proxy spawned by this session | ✅ | armed at birth | | Another session's armed shared proxy (watcher set, #1186) | ✅ | sharing is by design | -| Manually started `bili start` daemon (user zone, #1660) | ✅ by default | **user-zone** instance (no lane, no launch token): deliberately maintained by the user — you own its lifetime and version; refused only when `BILI_NATIVE_ATTACH_EXTERNAL=0/false` explicitly closes the gate | +| Manually started `bili start` daemon (user zone, #1660) | 🔶 conditional | **user-zone** instance (no lane, no launch token): an **armed** one (a managed shared proxy, #1225) is ridden by any compatible client lane; an **unarmed** manual one is, by default (`attachPolicy: own-lane`, #2877), NOT ridden by a LANEd hook — it spawns its own instead. Ridden instead under `attachPolicy: global-fallback` (pre-#2877) or `attachExternal=1`. You own its lifetime and version either way | | Unarmed **lane'd** proxy (crashed-session orphan; pre-#1330 unverifiable) | ❌ loudly refused | lifecycle-drift symptom (#1335): riding it would silently reuse a proxy no live session owns | -The hook probes each candidate's `/__bili/health` before attaching: armed → attach and register a watcher (unchanged); a **user-zone** candidate attaches by default regardless of watchdog state (#1660) — the user deliberately maintains that daemon; an unarmed **lane'd** candidate (a crashed session's orphan, or a pre-#1330 build that reports no `watchdog` field at all — unverifiable, treated as unarmed) is refused **loudly**, and the session spawns its own proxy in the self-managed port zone (base `18787`, or the lane's sticky drift record; armed at birth, dies with the last session, #1186 watcher semantics). Version skew stays fixed: the code-fingerprint check runs first, so a rebuilt or updated install never rides a stale daemon even through the user-zone exemption. Cost: one extra short-lived proxy process per session when nothing attachable exists (session state is shared on disk, so compression continuity is unaffected); the multi-instance warning (#394) becomes correspondingly more common. **Escape hatch:** `native.attachExternal: true` in the config file or `BILI_NATIVE_ATTACH_EXTERNAL=1` extends attaching to *lane'd* listeners regardless of watchdog state (including pre-#1330 builds) — you then own those daemons' lifetimes and versions; `0`/`false` closes the gate for everyone, including user-zone daemons, forcing fresh zone spawns. Explicit user-directed attaches (`BILLION_CONTEXT_ATTACH` / preset `BILLION_CONTEXT_PROXY` for kimi/dsh) bypass discovery entirely and are exempt by construction. +The hook probes each candidate's `/__bili/health` before attaching: armed → attach and register a watcher (unchanged); an **armed user-zone** candidate attaches regardless of the lane-affinity policy (a managed shared proxy, #1225); an **unarmed user-zone** (manual) candidate attaches only under `attachPolicy: global-fallback` (pre-#2877) or `attachExternal=1` — by default (`own-lane`) a LANEd hook spawns its own (#2877); an unarmed **lane'd** candidate (a crashed session's orphan, or a pre-#1330 build that reports no `watchdog` field at all — unverifiable, treated as unarmed) is refused **loudly**, and the session spawns its own proxy in the self-managed port zone (base `18787`, or the lane's sticky drift record; armed at birth, dies with the last session, #1186 watcher semantics). Version skew stays fixed: the code-fingerprint check runs first, so a rebuilt or updated install never rides a stale daemon even through the user-zone exemption. Cost: one extra short-lived proxy process per session when nothing attachable exists (session state is shared on disk, so compression continuity is unaffected); the multi-instance warning (#394) becomes correspondingly more common. **Escape hatch:** `native.attachExternal: true` in the config file or `BILI_NATIVE_ATTACH_EXTERNAL=1` extends attaching to *lane'd* listeners regardless of watchdog state (including pre-#1330 builds) — you then own those daemons' lifetimes and versions; `attachExternal` governs only the *lifecycle gate* for **lane'd** daemons (it does not open or close user-zone attachment — that axis is `attachPolicy`); `attachUrl` (env `BILI_MCP_PROXY` / `--origin`) pins an explicit target origin. Explicit user-directed attaches (`BILLION_CONTEXT_ATTACH` / preset `BILLION_CONTEXT_PROXY` for kimi/dsh) bypass discovery entirely and are exempt by construction. -Attach discovery is lane-aware across **all** live instances (#1232): the launcher probes every live entry in the instance registry, not just the single instance file (last-writer-wins — under concurrent multi-client use it can point at another client's proxy), and applies the gate above to every candidate. Among compatible candidates the newest instance with the launcher's own declared lane wins; an instance without a lane (a user-zone daemon) is wildcard-compatible on the lane axis and gate-exempt by default (#1660). The `another bili instance is running` warning (#394) is lane-aware too: it fires for same-lane or lane-less coexistence, but stays silent between two *different* declared lanes, whose session files are disjoint. +Attach discovery is lane-aware across **all** live instances (#1232): the launcher probes every live entry in the instance registry, not just the single instance file (last-writer-wins — under concurrent multi-client use it can point at another client's proxy), and applies the gate above to every candidate. Among compatible candidates the newest instance with the launcher's own declared lane wins; an instance without a lane (a user-zone daemon) is wildcard-compatible on the lane axis and gate-exempt by default (#1660) — but whether a LANEd hook actually falls back onto it is governed by `attachPolicy`: `own-lane` (default) does not ride an *unarmed* manual daemon (#2877), while `global-fallback` restores the pre-#2877 wildcard ride. The `another bili instance is running` warning (#394) is lane-aware too: it fires for same-lane or lane-less coexistence, but stays silent between two *different* declared lanes, whose session files are disjoint. ## Shared state dir and multi-instance security boundary (#394, #1724) diff --git a/TECHNICAL-NOTES.zh-CN.md b/TECHNICAL-NOTES.zh-CN.md index cd412c7c39..b7be534347 100644 --- a/TECHNICAL-NOTES.zh-CN.md +++ b/TECHNICAL-NOTES.zh-CN.md @@ -14,10 +14,10 @@ README 三种使用方式背后的机制级说明。README 里每种方式只保 |---|---|---| | 本会话拉起的代理 | ✅ | 出生即 armed | | 其他会话的 armed 共享代理(watcher 集,#1186) | ✅ | 共享本就是设计 | -| 手工 `bili start` 常驻守护进程(用户主权区,#1660) | ✅ 默认附着 | **用户主权区**实例(无 lane、无 launch token):用户刻意维护 —— 其寿命与版本由你自己负责;仅当 `BILI_NATIVE_ATTACH_EXTERNAL=0/false` 显式关门时才拒绝 | +| 手工 `bili start` 常驻守护进程(用户主权区,#1660) | 🔶 视情况 | **用户主权区**实例(无 lane、无 launch token):一台**已武装**的(受管共享代理,#1225)会被任何兼容 client lane 搭车;一台**未武装**的手动守护在默认(`attachPolicy: own-lane`,#2877)下**不会**被 lane 型 hook 搭车 —— 它自行派生。仅在 `attachPolicy: global-fallback`(pre-#2877)或 `attachExternal=1` 下被搭。无论哪种,寿命与版本由你自己负责 | | 未武装的 **lane 型**代理(崩溃会话孤儿;pre-#1330 不可验证) | ❌ 大声拒绝 | 生命周期漂移症状(#1335):搭乘等于静默复用无人管理的代理 | -hook 附着前先探测候选者的 `/__bili/health`:armed → 附着并注册 watcher(现状不变);**用户主权区**候选无论看门狗状态默认附着(#1660)—— 用户刻意维护该守护进程;未武装的 **lane 型**候选(崩溃会话孤儿,或 pre-#1330 构建根本不报 `watchdog` 字段 —— 不可验证,按 unarmed 处理)被**大声拒绝**,本会话在自管端口区自拉起代理(基准口 `18787` 或该 lane 粘性漂移记录;出生即 armed、随最后一个会话消亡,#1186 watcher 语义)。版本偏斜仍被修住:代码指纹检查先行,重建/更新后的安装即使经用户主权区豁免也永不搭乘陈旧守护进程。代价:无可附着实例时每会话多一个短命代理进程(会话状态在磁盘上共享,压缩连续性不受影响);多实例告警(#394)相应变多。**逃生舱:** 配置文件 `"native": { "attachExternal": true }` 或 `BILI_NATIVE_ATTACH_EXTERNAL=1` 把附着扩展到 *lane 型*监听者(无论看门狗状态,含 pre-#1330 构建)—— 那些守护进程的寿命与版本由你自己负责;`0`/`false` 对所有人关门,包括用户主权区守护进程,强制各 lane 自拉新代理。kimi/dsh 的显式用户指定附着(`BILLION_CONTEXT_ATTACH` / 预置 `BILLION_CONTEXT_PROXY`)完全不经过发现路径,构造上豁免。 +hook 附着前先探测候选者的 `/__bili/health`:armed → 附着并注册 watcher(现状不变);一台**已武装的用户主权区**候选无论 lane 亲和策略都附着(受管共享代理,#1225);一台**未武装的用户主权区**(手动)候选仅在 `attachPolicy: global-fallback`(pre-#2877)或 `attachExternal=1` 下附着 —— 默认(`own-lane`)lane 型 hook 自行派生(#2877);未武装的 **lane 型**候选(崩溃会话孤儿,或 pre-#1330 构建根本不报 `watchdog` 字段 —— 不可验证,按 unarmed 处理)被**大声拒绝**,本会话在自管端口区自拉起代理(基准口 `18787` 或该 lane 粘性漂移记录;出生即 armed、随最后一个会话消亡,#1186 watcher 语义)。版本偏斜仍被修住:代码指纹检查先行,重建/更新后的安装即使经用户主权区豁免也永不搭乘陈旧守护进程。代价:无可附着实例时每会话多一个短命代理进程(会话状态在磁盘上共享,压缩连续性不受影响);多实例告警(#394)相应变多。**逃生舱:** 配置文件 `"native": { "attachExternal": true }` 或 `BILI_NATIVE_ATTACH_EXTERNAL=1` 把附着扩展到 *lane 型*监听者(无论看门狗状态,含 pre-#1330 构建)—— 那些守护进程的寿命与版本由你自己负责;`attachExternal` 只管辖 **lane 型**守护的*生命周期门禁*(它并不开/关对 user-zone 的附着 —— 那个轴是 `attachPolicy`);`attachUrl`(env `BILI_MCP_PROXY` / `--origin`)钉住显式目标 origin。kimi/dsh 的显式用户指定附着(`BILLION_CONTEXT_ATTACH` / 预置 `BILLION_CONTEXT_PROXY`)完全不经过发现路径,构造上豁免。 附着发现在**所有**存活实例间是 lane 感知的(#1232):启动器探测实例注册表里的每一条存活记录,而不只是单个实例文件(last-writer-wins —— 并发多客户端下它可能指向别的客户端的代理),并对每个候选应用上面的门禁。兼容候选中,lane 与启动器自身声明一致的最新实例胜出;未声明 lane 的实例(用户主权区守护进程)在 lane 轴上通配,且门禁默认豁免(#1660)。`another bili instance is running` 告警(#394)也是 lane 感知的:同 lane 或无 lane 共存时触发,两个*不同声明* lane 之间保持沉默(它们的会话文件互不相交)。 diff --git a/src/config.ts b/src/config.ts index 83687febd6..87e60d6f63 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1719,26 +1719,39 @@ type FileConfig = { * BILI_ROLLOUT_=0/1 (UPPER_SNAKE name) wins over everything, * including `enabled`. */ rollout?: RolloutFileConfig; - /** 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[]; - }; + /** Native-hook attach behavior. + * `attachExternal` (#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. + * `attachLanePriority` (#2905): 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). + * `attachPolicy` (#2877): how a LANEd hook discovers an existing daemon + * when none of its own lane is running. "own-lane" (default) rides ONLY a + * same-lane daemon and otherwise spawns its own — it never falls back to a + * lane-less / user-zone / other-lane daemon (the manual `bili start` global + * that used to get ridden by every lane, #2877). "global-fallback" restores + * the pre-#2877 behavior (own lane first, then any compatible user-zone + * daemon). Env BILI_NATIVE_ATTACH_POLICY wins over the file. + * `attachUrl` (#2877): an explicit target origin (any URL, local or remote) + * to attach to instead of discovering; when set it overrides attachPolicy + * (the hook attaches only to that origin, else spawns). Env BILI_MCP_PROXY + * (also set by --origin) wins over this file value. */ + native?: { + attachExternal?: boolean; + attachLanePriority?: string[]; + attachPolicy?: "own-lane" | "global-fallback"; + attachUrl?: 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 @@ -2210,6 +2223,32 @@ export function resolveNativeAttachLanePriority(): string[] { return out; } +/** #2877: the native-hook discovery policy. "own-lane" (default) rides only a + * same-lane daemon and never falls back to a lane-less / user-zone one; + * "global-fallback" restores the pre-#2877 fallback. Env + * BILI_NATIVE_ATTACH_POLICY wins over the file's native.attachPolicy; any + * unrecognized value leaves the default "own-lane". */ +export function resolveNativeAttachPolicy(env: NodeJS.ProcessEnv = process.env): "own-lane" | "global-fallback" { + const norm = (v: string | undefined) => (v ?? "").trim().toLowerCase(); + const fromEnv = norm(env.BILI_NATIVE_ATTACH_POLICY); + if (fromEnv === "global-fallback" || fromEnv === "global") return "global-fallback"; + if (fromEnv === "own-lane" || fromEnv === "ownlane" || fromEnv === "strict") return "own-lane"; + const file = norm(loadConfigFile().native?.attachPolicy); + if (file === "global-fallback" || file === "global") return "global-fallback"; + return "own-lane"; +} + +/** #2877: an explicit attach target origin (any URL, local or remote). When + * present a hook attaches only to that origin instead of discovering. Env + * BILI_MCP_PROXY (also set by --origin) wins over the file's native.attachUrl; + * empty/whitespace values are treated as unset. */ +export function resolveNativeAttachUrl(env: NodeJS.ProcessEnv = process.env): string | undefined { + const fromEnv = (env.BILI_MCP_PROXY ?? "").trim(); + if (fromEnv.length > 0) return fromEnv; + const file = (loadConfigFile().native?.attachUrl ?? "").trim(); + return file.length > 0 ? file : undefined; +} + /** 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 * can't guess your provider, so we don't put a fake one. Fill it in per diff --git a/src/instance.ts b/src/instance.ts index 00cf3233da..d1485f2c24 100644 --- a/src/instance.ts +++ b/src/instance.ts @@ -165,6 +165,28 @@ export function findSameLanePredecessor( return undefined; } +/** #3044 follow-up: a live holder on the same lane running OUR build — a + * twin, not a predecessor. Nothing is draining (it is healthy and serving), + * so waiting cannot help; laddering +1 strands the newcomer as an orphan + * nobody routes to while the twin keeps serving (the second trigger path of + * #3044: a host respawn racing a live instance). The newcomer must exit + * loudly instead — the duplicate loses, the serving instance wins. Missing + * fingerprints never match: an unknown build is not our twin. */ +export function findSameLaneTwin( + entries: RegistryEntry[], + port: number, + lane: string | undefined, + ownFingerprint: string | undefined, +): RegistryEntry | undefined { + if (!lane || !ownFingerprint) return undefined; + for (const e of entries) { + if (e.port !== port || e.lane !== lane) continue; + if (!isPidAlive(e.pid)) continue; + if (e.codeFingerprint === ownFingerprint) return e; + } + return undefined; +} + /** #1225: content identity of a bili entry script (sha256 of its bytes). * The spawned child records this for ITS script; an attaching launcher * compares it against the hash of the script it would spawn — so "same diff --git a/src/launcher.ts b/src/launcher.ts index 588ee8fc58..277147a78c 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -66,7 +66,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, resolveNativeAttachLanePriority, resolveMitmDomains, resolveNonHttpProviders, type ProviderRoutes } from "./config.js"; +import { allowDshCompactionState, loadRoutes, resolveConfiguredContextLimit, lookupContextLimit, resolveNativeAttachExternal, resolveNativeAttachLanePriority, resolveNativeAttachPolicy, resolveNativeAttachUrl, resolveMitmDomains, resolveNonHttpProviders, type ProviderRoutes } from "./config.js"; import { discoverMitmDomains } from "./discover.js"; import { contextFromRegistry } from "./registry.js"; @@ -260,6 +260,14 @@ export interface LauncherDeps { * `native.attachLanePriority`). Default [] = own lane → user zone → * spawn, no cross-lane attach. */ attachLanePriority?: () => readonly string[]; + /** #2877: resolves the discovery policy ("own-lane" | "global-fallback"). + * Default reads env BILI_NATIVE_ATTACH_POLICY > config native.attachPolicy + * > "own-lane". */ + resolveAttachPolicy?: () => "own-lane" | "global-fallback"; + /** #2877: resolves an explicit attach target origin (any URL, local or + * remote), or undefined to discover. Default reads env BILI_MCP_PROXY > + * config native.attachUrl. */ + resolveAttachUrl?: () => string | undefined; readInstanceFile?: () => ProxyInstanceFile | { origin: string } | undefined; spawnImpl?: SpawnFn; now?: () => number; @@ -3547,16 +3555,28 @@ function attachClass(inst: ProxyInstanceFile, lane: string | undefined, foreignL return foreignLanes.length + 1; } -/** #1232: choose the attach target among healthy candidates. Must be +/** #2877: canonicalize an origin for explicit-target comparison — trim, drop + * trailing slashes, lowercase (scheme/host/port are case-insensitive). */ +function normalizeOrigin(o: string): string { + return o.trim().replace(/\/+$/, "").toLowerCase(); +} + +/** #1232/#2905: choose the attach target among healthy candidates. Must be * compatible (code fingerprint + config shape + lane rules) and, under * strictPort, bound to our exact port. Class ordering per attachClass — * same declared lane first, listed foreign lanes next, user zone last — - * newest within class. */ + * newest within class. #2877: when attachUrl is set only that exact origin is + * considered (explicit targeting overrides the policy below); otherwise + * "own-lane" restricts a LANEd hook to its own lane's daemon (no fallback to a + * lane-less / user-zone daemon), while "global-fallback" keeps the pre-#2877 + * wildcard fallback. */ function pickAttachable( candidates: Array<{ inst: ProxyInstanceFile; health: HealthInfo }>, opts: LaunchOptions, codeFingerprint: string | undefined, attachExternal: boolean, + attachPolicy: "own-lane" | "global-fallback", + attachUrl: string | undefined, refusedLog: Set, diag?: (msg: string) => void, foreignLanes: readonly string[] = [], @@ -3565,9 +3585,31 @@ function pickAttachable( let bestClass = Number.MAX_SAFE_INTEGER; let bestStartedAt = Number.NEGATIVE_INFINITY; for (const c of candidates) { + // #2877: explicit target origin wins over discovery — any other origin + // is skipped before compat/gate even run (cross-lane state-sharing still + // stays blocked by instanceCompatible's lane-mismatch rule below). + if (attachUrl && normalizeOrigin(c.inst.origin) !== normalizeOrigin(attachUrl)) { + diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not the explicit attachUrl target`); + continue; + } 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; } + const sameLane = opts.lane !== undefined && c.inst.lane === opts.lane; + // #2877: default "own-lane" — a LANEd hook rides only its own lane's + // daemon. Falling back to a lane-less (user-zone) daemon is what made + // every agent converge on one manual `bili start` (#2877), so that + // fallback is off by default — EXCEPT a deliberately ARMED lane-less + // daemon (#1225, managed shared proxy stays shareable). A lane-less + // initiator has no own lane to protect and keeps the legacy wildcard + // attach. Two things bypass this filter entirely: an explicit attachUrl + // target, and attachExternal=true (the pre-existing #1335 permissive + // opt-in — keeping it fully permissive means existing users of that + // flag see NO change from this flip). + if (!attachUrl && !attachExternal && attachPolicy === "own-lane" && opts.lane !== undefined && !sameLane && c.health.watchdog?.armed !== true) { + diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not own lane and not an armed shared daemon (attachPolicy=own-lane)`); + continue; + } // #1335: lifecycle gate — an unarmed (or unverifiable) listener is // never an attach target by default; log the refusal once per origin. // #1660: a user-zone instance (manual `bili start`) is exempt — the @@ -3606,13 +3648,15 @@ async function waitForStarterInstance( opts: LaunchOptions, codeFingerprint: string | undefined, attachExternal: boolean, + attachPolicy: "own-lane" | "global-fallback", + attachUrl: string | undefined, 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, foreignLanes); + pickAttachable(await probeLiveInstances(readInstance, fetchHealthInfo, diag), opts, codeFingerprint, attachExternal, attachPolicy, attachUrl, refusedLog, diag, foreignLanes); let inst: ProxyInstanceFile | undefined; while (now() < deadline) { await sleepImpl(HEALTH_POLL_INTERVAL_MS); @@ -3635,9 +3679,11 @@ export async function findLiveAttachableInstance( const fetchHealthInfo = deps.fetchHealthInfo ?? fetchHealthInfoDefault; const readInstance = deps.readInstanceFile ?? readProxyInstanceFile; const attachExternal = (deps.resolveAttachExternal ?? resolveNativeAttachExternal)(); + const attachPolicy = (deps.resolveAttachPolicy ?? resolveNativeAttachPolicy)(); + const attachUrl = (deps.resolveAttachUrl ?? resolveNativeAttachUrl)(); 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, foreignLanes); + return pickAttachable(probed, opts, entryScriptFingerprint(deps.scriptPath ?? process.argv[1]), attachExternal, attachPolicy, attachUrl, new Set(), deps.attachDiag, foreignLanes); } export function findFreePort(preferred: number, host = LAUNCHER_DEFAULT_HOST): Promise { @@ -3871,6 +3917,10 @@ export async function ensureProxyRunning( // #2905: ordered cross-lane attach fallbacks, resolved once per bring-up // (file only; default [] = own lane → user zone → spawn). const foreignLanes = (deps.attachLanePriority ?? resolveNativeAttachLanePriority)(); + // #2877: discovery policy + optional explicit target, resolved once per + // bring-up like the gate above. + const attachPolicy = (deps.resolveAttachPolicy ?? resolveNativeAttachPolicy)(); + const attachUrl = (deps.resolveAttachUrl ?? resolveNativeAttachUrl)(); // 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(); @@ -3905,7 +3955,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, foreignLanes); + const existing = pickAttachable(probed, opts, codeFingerprint, attachExternal, attachPolicy, attachUrl, 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 @@ -3934,7 +3984,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, foreignLanes); + const waited = await waitForStarterInstance(readInstance, fetchHealthInfo, now, sleepImpl, opts, codeFingerprint, attachExternal, attachPolicy, attachUrl, refusedLog, attachDiag, foreignLanes); if (waited) { return attachTo(waited); } @@ -4207,7 +4257,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, foreignLanes); + const late = pickAttachable(probedAgain, opts, codeFingerprint, attachExternal, attachPolicy, attachUrl, 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); diff --git a/src/listen-policy.ts b/src/listen-policy.ts new file mode 100644 index 0000000000..4b0e7a2bee --- /dev/null +++ b/src/listen-policy.ts @@ -0,0 +1,73 @@ +/** + * EADDRINUSE retry policy for the proxy's own listen socket (#407/#964/#1723/#3044). + * Pure decision table extracted from the server's 'error' handler so every + * branch can be pinned without booting a server. + * + * #3044: a self-restart replacement must own EXACTLY the port its predecessor + * freed. Hopping +1 strands it serving no client while the prior instance + * keeps holding the real port — the orphan-leak shape reported in #3044. It + * gets the bounded same-port predecessor wait (#1723 overlap: slow release), + * then fails fast instead of laddering. + * + * #3044 follow-up: a live holder running OUR build on the same lane is a + * twin, not a predecessor — nothing is draining, so the newcomer exits loudly + * instead of hopping (the duplicate loses; the serving instance keeps serving + * and the next launch attaches to it). Applies to marked AND unmarked spawns. + */ +/** Internal spawn-channel env set by performSelfRestart onto its replacement + * (#3044): the marked process must bind-or-die on exactly the freed port. */ +export const UPGRADE_REPLACEMENT_ENV = "BILI_UPGRADE_REPLACEMENT"; + +type EaddrinuseAction = + | { kind: "wait-predecessor"; port: number } + /** nextPort 0 = ask the OS for an ephemeral port (ladder exhausted). */ + | { kind: "ladder"; nextPort: number } + | { kind: "fail-fast"; reason: "upgrade-replacement" | "strict-port" | "port-busy" | "twin-collision" }; + +export interface EaddrinuseContext { + /** #3044: this process is a self-restart replacement (BILI_UPGRADE_REPLACEMENT). */ + upgradeReplacement: boolean; + /** #3044 follow-up: a live same-lane instance running our build holds the port. */ + twinHolds: boolean; + launchToken: boolean; + strictPort: boolean; + attempts: number; + maxAttempts: number; + predecessorTicksLeft: number; + predecessorHolds: boolean; + lastTriedPort: number; +} + +export function decideEaddrinuse(ctx: EaddrinuseContext): EaddrinuseAction { + // The twin rule outranks everything else: a healthy same-build peer is + // serving real traffic on that port, so no wait/ladder variant may touch + // it — the newcomer dies loudly regardless of its own spawn rights. + if (ctx.twinHolds) return { kind: "fail-fast", reason: "twin-collision" }; + if (ctx.upgradeReplacement) { + if (ctx.predecessorTicksLeft > 0 && ctx.predecessorHolds) { + return { kind: "wait-predecessor", port: ctx.lastTriedPort }; + } + return { kind: "fail-fast", reason: "upgrade-replacement" }; + } + if (!ctx.launchToken || ctx.strictPort || ctx.attempts >= ctx.maxAttempts) { + return { kind: "fail-fast", reason: ctx.strictPort ? "strict-port" : "port-busy" }; + } + if (ctx.predecessorTicksLeft > 0 && ctx.predecessorHolds) { + return { kind: "wait-predecessor", port: ctx.lastTriedPort }; + } + const nextAttempts = ctx.attempts + 1; + return { kind: "ladder", nextPort: nextAttempts === ctx.maxAttempts ? 0 : ctx.lastTriedPort + 1 }; +} + +/** #3044/#2941: ladder rights for the POST-BIND claim check (port-owner's + * resolvePortClaim). A launcher-spawned child that finds a foreign live + * listener on its just-bound port may move +1 off the contested port (#2941); + * strict-port and manual launches never did. A marked upgrade replacement must + * not either, even though it inherits its parent's launch token: hopping is + * exactly the orphan shape #3044 kills, and this is the second path where a + * replacement could hop — on socket semantics that tolerate a concurrent bind + * onto an actively-listening port, a successful bind does not exclude the + * still-draining predecessor or a racing host respawn (#707/libuv#1360). */ +export function postBindCanLadder(hasLaunchToken: boolean, strictPort: boolean, upgradeReplacement: boolean): boolean { + return hasLaunchToken && !strictPort && !upgradeReplacement; +} diff --git a/src/responses-ws.ts b/src/responses-ws.ts index c87fd939e8..26fc975101 100644 --- a/src/responses-ws.ts +++ b/src/responses-ws.ts @@ -185,7 +185,7 @@ export class ResponsesWsUpstream { private history = new ResponsesWsHistory(); private active?: { fail: (error: Error, reason?: string) => void }; - constructor(private readonly log: DiagnosticLog = () => {}, private readonly requestBytes = MAX_REQUEST_BYTES, private readonly hopStamp?: string) {} + constructor(private readonly log: DiagnosticLog = () => {}, private readonly requestBytes = MAX_REQUEST_BYTES, private readonly hopStamp?: string, private readonly forwardTransportFields = false) {} private resetHistory(reason: string): void { this.history.clear(); @@ -259,7 +259,20 @@ export class ResponsesWsUpstream { if (options.method !== "POST" || !new URL(url).pathname.endsWith("/responses") || bodyText === undefined) throw new Error("Unsupported request in Responses WebSocket transport"); const parsed: unknown = JSON.parse(bodyText); if (!object(parsed) || !Array.isArray(parsed.input)) throw new Error("Invalid Responses WebSocket request"); - const { stream, stream_options: _streamOptions, background: _background, previous_response_id: _previous, type: _type, ...body } = parsed; + const { stream, stream_options: streamOptions, background: _background, previous_response_id: _previous, type: _type, ...body } = parsed; + // #3063 wire fidelity (WC-017): the codex lane admits stream/stream_options from + // the client and must forward them verbatim — real codex create frames always carry + // stream:true (required field), and dropping it made chatgpt.com answer with a + // zero-output completed turn. Gated on forwardTransportFields (the codec's + // allowStreamFlag) rather than field presence: the session layer injects + // stream:true into EVERY frame before fetch(), so presence cannot distinguish a + // client-sent field from an internal one. The opencode lane (WC-013) refuses both + // fields at admission, so its egress stays byte-identical to before. + const egressTransportFields: JsonObject = {}; + if (this.forwardTransportFields) { + if (stream !== undefined) egressTransportFields.stream = stream; + if (streamOptions !== undefined) egressTransportFields.stream_options = streamOptions; + } const socket = await this.connect(url, options); if (this.active) throw new Error("Responses WebSocket exchange already active"); const request = this.history.continuation(body); @@ -323,7 +336,7 @@ export class ResponsesWsUpstream { retryFull = false; this.resetHistory("continuation-rejected"); this.log("debug", "upstream retry reason=continuation-rejected action=resend-full"); - socket.send(JSON.stringify({ ...body, type: "response.create" })); + socket.send(JSON.stringify({ ...body, ...egressTransportFields, type: "response.create" })); return; } clean(); @@ -375,7 +388,7 @@ export class ResponsesWsUpstream { options.signal?.addEventListener("abort", aborted, { once: true }); if (options.signal?.aborted) aborted(); else { - try { socket.send(JSON.stringify({ ...request, type: "response.create" })); } + try { socket.send(JSON.stringify({ ...request, ...egressTransportFields, type: "response.create" })); } catch (error) { fail(error instanceof Error ? error : new Error("Responses WebSocket send failed"), "send-failed"); } } }); @@ -481,7 +494,7 @@ class ResponsesWsSession implements WsBridgeSession { private busy = false; constructor(private readonly context: WsBridgeContext) { - this.transport = new ResponsesWsUpstream(context.log, undefined, context.instanceId); + this.transport = new ResponsesWsUpstream(context.log, undefined, context.instanceId, context.codec.allowStreamFlag === true); context.log("info", "Responses socket connected (ACP request pipeline)"); } diff --git a/src/restart.ts b/src/restart.ts index 806a833d12..9e05d8318a 100644 --- a/src/restart.ts +++ b/src/restart.ts @@ -37,6 +37,17 @@ * (#414) and logs wherever the parent does. The #414 group-kill rationale is * moot on win32 — stopProxy() relies on the BILI_PARENT_PID watchdog there, * never a group kill — so detaching costs nothing there. + * + * #3044 handover contract: the replacement is marked BILI_UPGRADE_REPLACEMENT + * so it binds-or-dies on exactly the port freed here (no +1 ladder — hopping + * stranded replacements serving no client while the prior instance kept the + * real port). The parent verifies the child through its OWN registry record + * (pid + actual bound port) rather than trusting a raw TCP answer on the port + * (a racing host respawn could masquerade as the child), terminates any + * misplaced or still-starting child and VERIFIES the kill, and exits instead + * of resuming when another live bili instance has taken over the port + * (resuming would ladder-drift this old-code copy onto a fresh port — the + * zombie half of the leak). */ import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process"; import net from "node:net"; @@ -49,6 +60,8 @@ import { flushAllSessions, totalInFlight } from "./session.js"; import { flushConversations } from "./plugin.js"; import { flushPrefixAffinity } from "./affinity-persist.js"; import { findInstallDir, isVersionNewer, verifyInstallLoadable } from "./update.js"; +import { isPidAlive, listInstances } from "./instance.js"; +import { UPGRADE_REPLACEMENT_ENV } from "./listen-policy.js"; const MARKER_FILE = path.join(cacheDir(), ".auto-restart"); @@ -66,6 +79,10 @@ const READY_TIMEOUT_MS = 20_000; const POLL_MS = 200; /** Grace for the close callback after force-closing idle sockets down. */ const FORCE_CLOSE_GRACE_MS = 1_000; +/** #3044: how long to wait for a killed replacement to actually die before + * escalating to a loud manual-cleanup error — an unverified kill is how the + * orphan processes of that report survived their parent's timeout. */ +const KILL_VERIFY_MS = 2_000; type AutoRestartInput = { enabled: boolean; @@ -197,6 +214,9 @@ type SelfRestartDeps = { * startServer() (restartForceCloseOf); returns how many were destroyed. * Absent for plain servers (tests) — force-close stays as before. */ destroyLingeringSockets?: () => number; + /** Kill-verification window in ms after terminating a failed replacement + * (#3044). Injectable for tests; defaults to KILL_VERIFY_MS. */ + killVerifyMs?: number; }; type SelfRestartResult = { ok: boolean; error?: string; childPid?: number }; @@ -292,10 +312,16 @@ export async function performSelfRestart(deps: SelfRestartDeps): Promise { exitReason = String(err); }); + // Readiness signal ladder (#3044). The authoritative proof that the + // handover landed is the replacement's OWN registry record (its pid plus + // the port it ACTUALLY bound, written on announceListening). A raw TCP + // answer on our port can come from a racing peer (a host respawn during + // our drain window) — trusting it made us exit believing the upgrade had + // landed while the real replacement idled on a drifted port serving no + // client. The TCP probe remains as fallback only (pre-registry children, + // and children that have not announced yet). + type HandoverOutcome = + | { kind: "ready" } + | { kind: "misplaced"; boundPort: number } + | { kind: "superseded"; peerPid: number } + | { kind: "not-ready"; exitReason?: string }; + const childPid = child.pid; const readyDeadline = Date.now() + readyTimeoutMs; - let ready = false; + let outcome: HandoverOutcome = { kind: "not-ready", exitReason }; while (Date.now() < readyDeadline) { - if (exitReason !== undefined) break; - if (await probeReady(probeHostFor(host), port)) { ready = true; break; } + if (exitReason !== undefined) { outcome = { kind: "not-ready", exitReason }; break; } + const ownRecord = childPid !== undefined ? listInstances().find((e) => e.pid === childPid) : undefined; + if (ownRecord !== undefined) { + outcome = ownRecord.port === port + ? { kind: "ready" } + : { kind: "misplaced", boundPort: ownRecord.port }; + break; + } + if (await probeReady(probeHostFor(host), port)) { + // Our OWN registry record (written at our announceListening) still + // claims this port while we drain — without excluding process.pid a + // healthy not-yet-announced replacement reads as "superseded by us" + // and gets killed (pinned by the #2895 tunnel handover test). + const foreignPeer = listInstances().find((e) => e.port === port && e.pid !== childPid && e.pid !== process.pid && isPidAlive(e.pid)); + if (foreignPeer !== undefined) { + outcome = { kind: "superseded", peerPid: foreignPeer.pid }; + } else { + outcome = { kind: "ready" }; + } + break; + } await sleep(POLL_MS); } - if (!ready) { - try { child.kill(); } catch { /* already gone */ } - log("warn", `[restart] aborted: replacement did not become ready within ${readyTimeoutMs / 1000}s${exitReason ? ` (${exitReason})` : ""} — resuming service`); - resumeListening(server, host, port, log); - return { ok: false, error: exitReason ?? "replacement-not-ready" }; + if (outcome.kind === "ready") { + log("info", `[restart] replacement is up (pid ${childPid ?? "?"}) — handing over v${deps.runningVersion} -> v${deps.diskVersion}, exiting`); + (deps.finish ?? defaultFinish)(); + return { ok: true, childPid }; + } + if (outcome.kind === "misplaced") { + log("error", `[restart] replacement bound port ${outcome.boundPort} instead of ${port} — terminating it; a drifted replacement serves no client while the prior instance keeps the real port (#3044)`); + } else if (outcome.kind === "superseded") { + log("warn", `[restart] port ${port} is already served by another bili instance (pid ${outcome.peerPid}) — treating the upgrade as landed there; terminating our still-starting replacement`); + } else { + log("warn", `[restart] aborted: replacement did not become ready within ${readyTimeoutMs / 1000}s${outcome.exitReason ? ` (${outcome.exitReason})` : ""}`); } + await killAndVerify(child, childPid, deps.killVerifyMs ?? KILL_VERIFY_MS, log); + // Terminal decision (#3044): if another LIVE bili instance now owns our + // port, resuming THIS old-code copy would ladder-drift it onto a fresh + // port nobody routes to — the zombie half of the reported leak. The + // upgrade effectively landed elsewhere; exit cleanly instead. A foreign + // non-bili squatter keeps today's resume behavior. + const biliPeer = listInstances().find((e) => e.port === port && e.pid !== process.pid && isPidAlive(e.pid)); + if (biliPeer !== undefined) { + log("warn", `[restart] port ${port} is served by bili instance pid ${biliPeer.pid} — exiting instead of resuming (a resumed old-code copy would drift to a new port and leak, #3044)`); + (deps.finish ?? defaultFinish)(); + return { ok: true, childPid }; + } + log("warn", "[restart] resuming service"); + resumeListening(server, host, port, log); + return { + ok: false, + error: outcome.kind === "misplaced" + ? `replacement-misplaced:${outcome.boundPort}` + : outcome.kind === "superseded" + ? "superseded-by-peer" + : (outcome.exitReason ?? "replacement-not-ready"), + }; +} - log("info", `[restart] replacement is up (pid ${child.pid ?? "?"}) — handing over v${deps.runningVersion} -> v${deps.diskVersion}, exiting`); - (deps.finish ?? defaultFinish)(); - return { ok: true, childPid: child.pid }; +/** Terminate a failed replacement and verify it actually died (#3044): a + * kill that silently no-ops leaves exactly the orphan processes that report + * describes — idle, holding a port nobody routes to, accumulating memory. */ +async function killAndVerify(child: ChildProcess, pid: number | undefined, verifyMs: number, log: Logger): Promise { + try { child.kill(); } catch { /* already gone */ } + if (pid === undefined) return; + const deadline = Date.now() + verifyMs; + while (Date.now() < deadline) { + if (!isPidAlive(pid)) return; + await sleep(POLL_MS); + } + log("error", `[restart] replacement pid ${pid} is still alive after SIGTERM — manual cleanup required (kill ${pid}); until it dies it keeps leaking CPU/memory on a port nobody routes to (#3044)`); } function resumeListening(server: http.Server, host: string, port: number, log: Logger): void { diff --git a/src/server.ts b/src/server.ts index 2d1726751e..09aee84b5a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -58,6 +58,7 @@ import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcil import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "./session-self-heal.js"; import { getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, snapshotMessages, ensureCanonicalId, storeEffectiveConfig, foldCoverage, postRebuildAnchorTokens, setPostRebuildAnchor, tickPostRebuildAnchor, splitSessionWarnings, RESPONSES_TURN_SEPARATOR_ID_PREFIX } from "./session.js"; import { detectStaleInstall } from "./update.js"; +import { decideEaddrinuse, postBindCanLadder, UPGRADE_REPLACEMENT_ENV } from "./listen-policy.js"; import { getAdvisoryState, cannotResolveTarget } from "./advisory.js"; import { PACKAGE_NAME, VERSION } from "./version.js"; import { @@ -97,7 +98,7 @@ import { getStore } from "./persist.js"; import { log as loggerLog, configureLogger, getLogPath, closeLogger, isFileLoggingActive, isStreamWriteError, isBenignSocketRaceError, enterSessionContext, muteStderrLeg } from "./logger.js"; import { queryLogLines } from "./web/logs-query.js"; import { configFile, defaultLogFile, stateDir } from "./paths.js"; -import { atomicWriteInstanceFile, clearProxyInstanceFile, entryScriptFingerprint, findSameLanePredecessor, isPidAlive, listInstances, readProxyInstanceFile, registerInstanceAndWarn, unregisterInstance, warnOnNewPeers, type ProxyInstanceFile } from "./instance.js"; +import { atomicWriteInstanceFile, clearProxyInstanceFile, entryScriptFingerprint, findSameLanePredecessor, findSameLaneTwin, isPidAlive, listInstances, readProxyInstanceFile, registerInstanceAndWarn, unregisterInstance, warnOnNewPeers, type ProxyInstanceFile, type RegistryEntry } from "./instance.js"; import { mayClobberPointer, probeOwnerInfo, resolvePortClaim } from "./port-owner.js"; import { hoistTrappedToolItems } from "./tool-pair-order.js"; import { computeAnthropicMessageMarks, stampAnthropicSystemCacheControl, anthropicToolsCarryCacheControl } from "./loop/cache-control.js"; @@ -911,6 +912,11 @@ export async function startServer(opts: ProxyOptions): Promise { // "success" would strand every model request on the dead original port. const launchToken = process.env.BILI_LAUNCH_TOKEN?.trim(); const strictPort = process.env.BILI_STRICT_PORT === "1"; + // #3044: a self-restart replacement must own exactly the port its + // predecessor freed — it fails fast instead of inheriting the +1 ladder + // (hopping strands it serving no client while the old instance keeps the + // real port: the orphan leak #3044 reports). + const upgradeReplacement = process.env[UPGRADE_REPLACEMENT_ENV] === "1"; // #1225: lane identity + code fingerprint recorded into the instance file // so later launches can decide reuse by WHO started us and WHICH code we // run — not just config shape (same-version stale dist kept serving after @@ -1121,7 +1127,7 @@ export async function startServer(opts: ProxyOptions): Promise { const outcome = await resolvePortClaim({ origin: boundOrigin(addr.port), ownPid: process.pid, - canLadder: Boolean(launchToken) && !strictPort, + canLadder: postBindCanLadder(Boolean(launchToken), strictPort, upgradeReplacement), listenAttempts, maxListenAttempts: MAX_LISTEN_ATTEMPTS, }); @@ -1166,23 +1172,43 @@ export async function startServer(opts: ProxyOptions): Promise { // graceful-shutdown flush can run. Catch, log a human-readable message, // flush sessions, and exit cleanly (exit code 1 so callers/scripts notice). server.on("error", (err: NodeJS.ErrnoException) => { - if (err.code === "EADDRINUSE" && launchToken && !strictPort && listenAttempts < MAX_LISTEN_ATTEMPTS) { - if (predecessorTicksLeft > 0 && sameLanePredecessorHolds(lastTriedPort)) { + let busyReason: "upgrade-replacement" | "strict-port" | "port-busy" | "twin-collision" | undefined; + let twin: RegistryEntry | undefined; + if (err.code === "EADDRINUSE") { + twin = findSameLaneTwin(listInstances(), lastTriedPort, launcherLane, ownFingerprint); + const action = decideEaddrinuse({ + upgradeReplacement, + twinHolds: twin !== undefined, + launchToken: launchToken !== undefined, + strictPort, + attempts: listenAttempts, + maxAttempts: MAX_LISTEN_ATTEMPTS, + predecessorTicksLeft, + predecessorHolds: sameLanePredecessorHolds(lastTriedPort), + lastTriedPort, + }); + if (action.kind === "wait-predecessor") { predecessorTicksLeft -= 1; - setTimeout(() => attemptListen(lastTriedPort), PREDECESSOR_WAIT_MS); + setTimeout(() => attemptListen(action.port), PREDECESSOR_WAIT_MS); return; } - listenAttempts += 1; - const next = listenAttempts === MAX_LISTEN_ATTEMPTS ? 0 : lastTriedPort + 1; - log("warn", `port ${lastTriedPort} busy — ${next === 0 ? "retrying on an ephemeral port" : `retrying on port ${next}`}`); - attemptListen(next); - return; + if (action.kind === "ladder") { + listenAttempts += 1; + log("warn", `port ${lastTriedPort} busy — ${action.nextPort === 0 ? "retrying on an ephemeral port" : `retrying on port ${action.nextPort}`}`); + attemptListen(action.nextPort); + return; + } + busyReason = action.reason; } const hint = err.code === "EADDRINUSE" - ? strictPort - ? ` — port ${lastTriedPort} is pinned (strict-port mode) but already in use. Free it or point the client at another port (e.g. BILI_CLAUDE_NATIVE_PORT for the claude native posture).` - : ` — port ${lastTriedPort} is already in use. Stop the other process or use --port .` + ? busyReason === "twin-collision" + ? ` — port ${lastTriedPort} is already served by a same-build bili instance (pid ${twin?.pid}, lane ${launcherLane}) — exiting instead of hopping: the duplicate loses and the serving instance keeps serving; the next launch will attach to it (#3044).` + : busyReason === "upgrade-replacement" + ? ` — this process is an upgrade-restart replacement (#3044): it must own port ${lastTriedPort} exactly, but the prior instance still holds it. Exiting instead of hopping to ${lastTriedPort + 1} — a drifted replacement serves no client and leaks while the prior instance keeps serving; the upgrade retries on the next cooldown cycle.` + : busyReason === "strict-port" + ? ` — port ${lastTriedPort} is pinned (strict-port mode) but already in use. Free it or point the client at another port (e.g. BILI_CLAUDE_NATIVE_PORT for the claude native posture).` + : ` — port ${lastTriedPort} is already in use. Stop the other process or use --port .` : err.code === "EACCES" ? ` — port ${lastTriedPort} requires privileges. Use a port >= 1024.` : ""; diff --git a/tests/auto-restart.test.ts b/tests/auto-restart.test.ts index 8758ff8746..6bbf7987f7 100644 --- a/tests/auto-restart.test.ts +++ b/tests/auto-restart.test.ts @@ -15,6 +15,8 @@ import { startServer as startBiliServer, restartForceCloseOf } from "../src/serv import type { ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { isPidAlive } from "../src/instance.ts"; +import { UPGRADE_REPLACEMENT_ENV } from "../src/listen-policy.ts"; const root = mkdtempSync(path.join(tmpdir(), "bc-auto-restart-")); process.env.XDG_CACHE_HOME = path.join(root, "cache"); @@ -464,10 +466,16 @@ test("performSelfRestart: hands the platform-specific spawn options through to s finish: () => {}, }); assert.equal(result.ok, true, JSON.stringify(result)); + const baseOpts = selfRestartSpawnOptions(platform); assert.deepEqual( record.options, - selfRestartSpawnOptions(platform), - `${platform}: spawn must be called with the platform-specific options`, + { + ...baseOpts, + // #3044: the replacement is marked so it cannot inherit the + // launcher's +1 ladder rights (bind-or-die on the freed port). + env: { ...(baseOpts.env as NodeJS.ProcessEnv), [UPGRADE_REPLACEMENT_ENV]: "1" }, + }, + `${platform}: spawn must be called with the platform-specific options plus the #3044 replacement marker`, ); } finally { record.child?.kill(); @@ -520,3 +528,168 @@ test("readLastRestart: tolerant of missing/corrupt markers", async () => { await writeFile(path.join(markerDir, ".auto-restart"), JSON.stringify({ ts: 12345, from: "1.0.0", to: "1.0.1" })); assert.equal(await readLastRestart(), 12345); }); + +// --------------------------------------------------------------------------- +// #3044: occupied target port must never strand an orphan replacement. The +// old shape: a replacement that hit EADDRINUSE on the freed port silently +// hopped +1 and idled serving no client while the prior instance kept the +// real port — accumulating one zombie per upgrade cycle. Pinned here at the +// parent side (readiness verification + terminal decision); the child side +// (bind-or-die) is pinned in listen-policy.test.ts and port-zone-live.test.ts. +// --------------------------------------------------------------------------- + +function instancesDir(): string { + return path.join(process.env.XDG_STATE_HOME ?? "", "billion-context", "instances"); +} + +function writeRegistryEntry(entry: Record): void { + mkdirSync(instancesDir(), { recursive: true }); + const id = typeof entry.instanceId === "string" ? entry.instanceId : "anon"; + writeFileSync(path.join(instancesDir(), `${id}.json`), JSON.stringify(entry)); +} + +// resumeListening is fire-and-forget (as in production): give the rebind a +// bounded chance to complete before asserting on the listener state. +async function waitForListening(server: { listening: boolean }, ms = 3000): Promise { + const deadline = Date.now() + ms; + while (!server.listening && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 25)); + } + return server.listening; +} + +test("performSelfRestart: replacement spawn env carries the bind-or-die marker without mutating the parent env (#3044)", { timeout: 30_000 }, async () => { + const { server, port } = await startServer(); + const { log } = makeLog(); + const record: SpawnRecord = {}; + process.env.BILI_TEST_SENTINEL = "sentinel-value"; + try { + const result = await performSelfRestart({ + server, host: "127.0.0.1", port, + installDir: makeInstall("1.0.1"), + runningVersion: "1.0.0", diskVersion: "1.0.1", + log, inFlightProvider: () => 0, + platform: "linux", + spawnImpl: makeSpawn(makeReadyStub("stub-marker.mjs"), port, record), + settleMs: 500, readyTimeoutMs: 5000, + finish: () => {}, + }); + assert.equal(result.ok, true, JSON.stringify(result)); + const env = record.options?.env as NodeJS.ProcessEnv | undefined; + assert.ok(env, "spawn options carry an env"); + assert.equal(env[UPGRADE_REPLACEMENT_ENV], "1", "replacement marked so it binds-or-dies on the freed port (#3044)"); + assert.equal(env.BILI_TEST_SENTINEL, "sentinel-value", "inherited env survives the merge"); + assert.equal(process.env[UPGRADE_REPLACEMENT_ENV], undefined, "the parent's own env must not be mutated"); + } finally { + delete process.env.BILI_TEST_SENTINEL; + record.child?.kill(); + server.closeAllConnections?.(); + await new Promise((r) => server.close(() => r())); + } +}); + +test("performSelfRestart: replacement that binds the WRONG port is terminated and service resumes (#3044)", { timeout: 30_000 }, async () => { + const { server, port } = await startServer(); + const { log, entries } = makeLog(); + const record: SpawnRecord = {}; + try { + const pending = performSelfRestart({ + server, host: "127.0.0.1", port, + installDir: makeInstall("1.0.1"), + runningVersion: "1.0.0", diskVersion: "1.0.1", + log, inFlightProvider: () => 0, + // The stub listens on port+9 instead of the freed port: it models a + // replacement that drifted via the old ladder after EADDRINUSE. + spawnImpl: makeSpawn(makeReadyStub("stub-misplaced.mjs"), port + 9, record), + settleMs: 500, readyTimeoutMs: 5000, + finish: () => assert.fail("must not finish when the replacement drifted"), + }); + for (let i = 0; i < 500 && record.child?.pid === undefined; i++) { + await new Promise((r) => setTimeout(r, 10)); + } + assert.ok(record.child?.pid, "replacement spawned"); + // The drifted replacement announces itself on the wrong port — exactly + // what the parent's readiness loop must catch instead of trusting TCP. + writeRegistryEntry({ instanceId: "stub-misplaced", pid: record.child.pid, port: port + 9, origin: `http://127.0.0.1:${port + 9}`, startedAt: Date.now(), lane: "dsh" }); + const result = await pending; + assert.equal(result.ok, false, JSON.stringify(result)); + assert.equal(result.error, `replacement-misplaced:${port + 9}`); + assert.match(entries.join("\n"), /bound port \d+ instead of \d+ — terminating/s); + assert.equal(await waitForListening(server), true, "original listener must be resumed"); + assert.equal(await requestOk(port), true, "resumed listener must serve"); + if (record.child?.pid !== undefined) { + for (let i = 0; i < 100 && isPidAlive(record.child.pid); i++) await new Promise((r) => setTimeout(r, 20)); + assert.equal(isPidAlive(record.child.pid), false, "misplaced replacement must be gone — no orphan left behind"); + } + } finally { + record.child?.kill("SIGKILL"); + server.closeAllConnections?.(); + await new Promise((r) => server.close(() => r())); + } +}); + +test("performSelfRestart: port taken over by another bili instance → parent exits instead of resuming (#3044)", { timeout: 30_000 }, async () => { + const { server, port } = await startServer(); + const { log, entries } = makeLog(); + const record: SpawnRecord = {}; + let finished = 0; + // A live non-listening process standing in for a peer bili instance. + const sleeper = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000);"], { stdio: "ignore" }); + try { + assert.ok(sleeper.pid, "sleeper pid for the fake peer"); + // A live bili peer now owns our port (e.g. a host respawn that beat the + // replacement): resuming THIS old-code copy would ladder-drift it onto + // a fresh port nobody routes to — the zombie half of the leak. + writeRegistryEntry({ instanceId: "superseding-peer", pid: sleeper.pid, port, origin: `http://127.0.0.1:${port}`, startedAt: Date.now(), lane: "dsh" }); + const result = await performSelfRestart({ + server, host: "127.0.0.1", port, + installDir: makeInstall("1.0.1"), + runningVersion: "1.0.0", diskVersion: "1.0.1", + log, inFlightProvider: () => 0, + spawnImpl: makeSpawn(makeCrashStub("stub-superseded.mjs"), port, record), + settleMs: 500, readyTimeoutMs: 3000, + finish: () => { finished++; }, + }); + assert.equal(result.ok, true, "the upgrade landed elsewhere — handover achieved, parent exits cleanly"); + assert.equal(finished, 1, "finish seam called exactly once"); + assert.equal(server.listening, false, "no resume: the old-code copy must not drift onto a new port"); + assert.match(entries.join("\n"), /served by bili instance pid \d+ — exiting instead of resuming/s); + } finally { + record.child?.kill(); + try { sleeper.kill("SIGKILL"); } catch {} + server.closeAllConnections?.(); + await new Promise((r) => server.close(() => r())); + } +}); + +test("performSelfRestart: a replacement that survives SIGTERM is escalated loudly (#3044)", { timeout: 30_000 }, async () => { + const { server, port } = await startServer(); + const { log, entries } = makeLog(); + const record: SpawnRecord = {}; + const stubborn = path.join(root, "stub-stubborn.mjs"); + writeFileSync(stubborn, [ + "process.on('SIGTERM', () => {});", + "setInterval(() => {}, 1000);", + ].join("\n")); + try { + const result = await performSelfRestart({ + server, host: "127.0.0.1", port, + installDir: makeInstall("1.0.1"), + runningVersion: "1.0.0", diskVersion: "1.0.1", + log, inFlightProvider: () => 0, + spawnImpl: makeSpawn(stubborn, port, record), + settleMs: 500, readyTimeoutMs: 800, killVerifyMs: 400, + finish: () => assert.fail("must not finish while the replacement is stuck"), + }); + assert.equal(result.ok, false, JSON.stringify(result)); + assert.equal(result.error, "replacement-not-ready"); + // An unverified kill was how the orphans of #3044 survived their + // parent's timeout — the loud escalation is the point of this test. + assert.match(entries.join("\n"), /still alive after SIGTERM — manual cleanup required \(kill \d+\)/s); + assert.equal(await waitForListening(server), true, "service resumes regardless"); + } finally { + record.child?.kill("SIGKILL"); + server.closeAllConnections?.(); + await new Promise((r) => server.close(() => r())); + } +}); diff --git a/tests/claude-native.test.ts b/tests/claude-native.test.ts index 440f85f8af..e094643cb2 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, resolveNativeAttachLanePriority } from "../src/config.ts"; +import { ZONE_PORT_BASE, resolveClaudeNativePort, resolveNativeAttachExternal, resolveNativeAttachLanePriority, resolveNativeAttachPolicy, resolveNativeAttachUrl } 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"; @@ -262,6 +262,69 @@ test("resolveNativeAttachLanePriority: ordered unique list; garbage degrades to } }); +// #2877: discovery policy + explicit target — env wins over the config file; +// default "own-lane" (a LANEd hook rides only its own lane, else spawns); +// attachUrl unset unless an explicit origin is pinned. +test("resolveNativeAttachPolicy: default own-lane; env/file select global-fallback", () => { + const prev = process.env.XDG_CONFIG_HOME; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-attachpol-")); + 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.equal(resolveNativeAttachPolicy({}), "own-lane", "no env, no file → own-lane default"); + assert.equal(resolveNativeAttachPolicy({ BILI_NATIVE_ATTACH_POLICY: "global-fallback" }), "global-fallback"); + assert.equal(resolveNativeAttachPolicy({ BILI_NATIVE_ATTACH_POLICY: "GLOBAL-FALLBACK" }), "global-fallback", "case-insensitive + trimmed"); + assert.equal(resolveNativeAttachPolicy({ BILI_NATIVE_ATTACH_POLICY: "global" }), "global-fallback", "shorthand alias"); + assert.equal(resolveNativeAttachPolicy({ BILI_NATIVE_ATTACH_POLICY: "own-lane" }), "own-lane"); + assert.equal(resolveNativeAttachPolicy({ BILI_NATIVE_ATTACH_POLICY: "strict" }), "own-lane", "strict == own-lane"); + assert.equal(resolveNativeAttachPolicy({ BILI_NATIVE_ATTACH_POLICY: "bogus" }), "own-lane", "junk env falls back to default"); + + fs.writeFileSync(cfgFile, JSON.stringify({ native: { attachPolicy: "global-fallback" } })); + assert.equal(resolveNativeAttachPolicy({}), "global-fallback", "file selects global-fallback"); + assert.equal(resolveNativeAttachPolicy({ BILI_NATIVE_ATTACH_POLICY: "strict" }), "own-lane", "env wins over file"); + + fs.writeFileSync(cfgFile, JSON.stringify({ native: { attachPolicy: "nonsense" } })); + assert.equal(resolveNativeAttachPolicy({}), "own-lane", "junk file value → default own-lane"); + + fs.rmSync(cfgFile); + assert.equal(resolveNativeAttachPolicy({}), "own-lane", "absent file → default own-lane"); + } finally { + if (prev === undefined) delete process.env.XDG_CONFIG_HOME; + else process.env.XDG_CONFIG_HOME = prev; + rmrf(dir); + } +}); + +test("resolveNativeAttachUrl: env BILI_MCP_PROXY wins over file native.attachUrl; blank → unset", () => { + const prev = process.env.XDG_CONFIG_HOME; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-attachurl-")); + 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.equal(resolveNativeAttachUrl({}), undefined, "no env, no file → unset (discover)"); + assert.equal(resolveNativeAttachUrl({ BILI_MCP_PROXY: "http://127.0.0.1:9999" }), "http://127.0.0.1:9999", "env pin"); + assert.equal(resolveNativeAttachUrl({ BILI_MCP_PROXY: " " }), undefined, "blank env → unset"); + + fs.writeFileSync(cfgFile, JSON.stringify({ native: { attachUrl: "http://remote.example:8787" } })); + assert.equal(resolveNativeAttachUrl({}), "http://remote.example:8787", "file value used when env absent"); + assert.equal(resolveNativeAttachUrl({ BILI_MCP_PROXY: "http://127.0.0.1:18788" }), "http://127.0.0.1:18788", "env wins over file"); + + fs.writeFileSync(cfgFile, JSON.stringify({ native: { attachUrl: " " } })); + assert.equal(resolveNativeAttachUrl({}), undefined, "whitespace file value → unset"); + + fs.rmSync(cfgFile); + assert.equal(resolveNativeAttachUrl({}), undefined, "absent file → unset"); + } 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/codex-responses-ws.test.ts b/tests/codex-responses-ws.test.ts index 820ca1f765..cc31b88cb3 100644 --- a/tests/codex-responses-ws.test.ts +++ b/tests/codex-responses-ws.test.ts @@ -14,6 +14,7 @@ import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; import { peekSession } from "../src/session.ts"; import type { ProxyOptions } from "../src/config.ts"; +import { validateCodexResponsesWsCreate } from "./wire-contract-fakes.ts"; type Item = Record; @@ -42,6 +43,8 @@ async function fixture() { const wss = new WebSocketServer({ server: upstream }); wss.on("connection", (peer, req) => { upstreamConnections.push(req.headers); peer.on("error", e => console.error("[FAKE-UPSTREAM-PEER-ERR]", e.message)); peer.on("message", raw => { const request = JSON.parse(raw.toString()) as Item; + const violations = validateCodexResponsesWsCreate(request); + if (violations.length) { peer.send(JSON.stringify({ type: "error", status: 400, error: { code: "invalid_request", message: violations.join("; ") } })); return; } rows.push({ request, headers: req.headers }); const id = `resp_codex_${++serial}`; const send = (type: string, fields: Item): void => peer.send(JSON.stringify({ type, ...fields })); @@ -141,6 +144,11 @@ test("codex WS: prewarm probe plus full-replay turns ride the prefix lane throug assert.equal(f.rows[0].headers.authorization, "Bearer fake-credential"); assert.equal(f.rows[0].headers["session-id"], f.sid); assert.match(String(f.rows[0].headers["user-agent"]), /^codex_exec\//); + // #3063: the client's transport fields must ride the upstream frame + // verbatim — dropping stream made chatgpt.com answer with a zero-output + // completed turn. + assert.equal(f.rows[0].request.stream, true); + assert.equal(f.rows[1].request.stream, true); // The real turn is a full replay the pipeline processed: bili's ACP // tools ride alongside codex's own (empty) tool list. assert.ok(Array.isArray(f.rows[1].request.tools) && (f.rows[1].request.tools as Item[]).some(t => t.name === "acp_status" || t.name === "compress"), JSON.stringify((f.rows[1].request.tools as Item[] | undefined)?.map?.((t: Item) => t.name))); @@ -400,6 +408,10 @@ test("codex WS: stream_options delivery hints are admitted (codex 0.160.0 shape, // Admitted through the ACP pipeline: probe row + one processed turn row, no error frame. assert.equal(f.rows.length, 2); assert.ok(JSON.stringify(f.rows[1].request.input).includes("stream-options-turn")); + // #3063: admitted is not enough — the hint must also reach upstream verbatim. + assert.equal(f.rows[0].request.stream, true); + assert.equal(f.rows[1].request.stream, true); + assert.deepEqual(f.rows[1].request.stream_options, { reasoning_summary_delivery: "sequential_cutoff" }); } finally { await f.close(); } }); diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index 0876d8b003..67f25fa56d 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -1247,6 +1247,11 @@ test("ensureProxyRunning: attaches a late-publishing instance after the spawned registerWatcher: async (origin, pid) => { registrations.push([origin, pid]); return "refused"; }, attachDiag: () => {}, scriptPath: FP_SCRIPT, + // #2877: this scenario is a lane-less (manual) daemon being ridden by a + // LANEd launch — the pre-#2877 cross-zone fallback. Pin it to the + // legacy policy so it keeps exercising the post-exit re-discovery + // mechanism (its actual subject) rather than the new own-lane default. + resolveAttachPolicy: () => "global-fallback", }, ); assert.equal(handle.attached, true, "attached to the late publisher instead of failing"); @@ -1469,7 +1474,38 @@ test("ensureProxyRunning: unarmed LANE'D listener is not attached by default — assert.equal(registered, 0, "no watcher registration is attempted against the refused daemon"); }); -test("ensureProxyRunning: unarmed USER-ZONE daemon (manual `bili start`) is attached by default (#1660)", async () => { +// #2877 flipped the default: an unarmed USER-ZONE daemon (manual `bili start`, +// no lane) is no longer ridden by a LANEd launch — every agent converging on one +// manual proxy was the bug (#2877). The hook now spawns its own session proxy. +test("ensureProxyRunning: unarmed USER-ZONE daemon (manual `bili start`) is NOT ridden by default — spawns its own (#2877)", async () => { + let spawnCalls = 0; + let childToken = ""; + let spawned = false; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, lane: "pi" }, + { + spawnImpl: (_cmd, _args, options) => { + spawned = true; + childToken = options.env?.BILI_LAUNCH_TOKEN ?? ""; + spawnCalls++; + return makeFakeChild(42505); + }, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "manual-1", watchdog: { armed: false } }), + readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "manual-1" })), + registerWatcher: async () => "ok", + sleep: () => new Promise((r) => setTimeout(r, 0)), + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(spawnCalls, 1, "the manual user-zone daemon is no longer ridden by default (#2877)"); + assert.ok(handle.child); + assert.equal(handle.attached, undefined); +}); + +// The pre-#2877 behavior (ride the user-maintained daemon) is preserved behind +// the explicit legacy policy (#1660). +test("ensureProxyRunning: unarmed USER-ZONE daemon (manual `bili start`) is attached when attachPolicy=global-fallback (#1660/#2877)", async () => { let spawnCalls = 0; let registered = 0; const handle = await ensureProxyRunning( @@ -1477,7 +1513,7 @@ test("ensureProxyRunning: unarmed USER-ZONE daemon (manual `bili start`) is atta { spawnImpl: () => { spawnCalls++; - return makeFakeChild(42505); + return makeFakeChild(42506); }, fetchImpl: async () => ({ ok: true }), fetchHealthInfo: async () => ({ ok: true, instanceId: "manual-1", watchdog: { armed: false } }), @@ -1488,6 +1524,7 @@ test("ensureProxyRunning: unarmed USER-ZONE daemon (manual `bili start`) is atta }, sleep: () => new Promise((r) => setTimeout(r, 0)), scriptPath: FP_SCRIPT, + resolveAttachPolicy: () => "global-fallback", }, ); assert.equal(spawnCalls, 0, "the user-maintained daemon is reused, not doubled"); @@ -2067,7 +2104,82 @@ test("runLaunch: explicit ACP_PORT still attaches to a compatible proxy already } }); -test("runLaunch: omitted ACP_PORT keeps the legacy selection (still attaches a user-zone daemon on any port) (#2177)", async () => { +// #2877: pickAttachable discovery policy. Default "own-lane" rides only a +// same-lane daemon and never falls back to a lane-less / user-zone one; +// "global-fallback" restores the pre-#2877 fallback; an explicit attachUrl +// targets one origin regardless of policy. +test("findLiveAttachableInstance: own-lane (default) does NOT fall back to a lane-less user-zone daemon (#2877)", async () => { + const inst = await findLiveAttachableInstance( + { host: "127.0.0.1", port: 0, passthrough: false, debug: false, lane: "pi" }, + { + fetchHealthInfo: async () => ({ ok: true, watchdog: { armed: false } }), + readInstanceFile: () => recordedInstance({ origin: "http://127.0.0.1:8787", port: 8787 }), + resolveAttachPolicy: () => "own-lane", + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(inst, undefined, "lane-less user-zone daemon is not a same-lane match → no fallback"); +}); + +test("findLiveAttachableInstance: global-fallback DOES ride a lane-less user-zone daemon (#2877)", async () => { + const inst = await findLiveAttachableInstance( + { host: "127.0.0.1", port: 0, passthrough: false, debug: false, lane: "pi" }, + { + fetchHealthInfo: async () => ({ ok: true, watchdog: { armed: false } }), + readInstanceFile: () => recordedInstance({ origin: "http://127.0.0.1:8787", port: 8787 }), + resolveAttachPolicy: () => "global-fallback", + scriptPath: FP_SCRIPT, + }, + ); + assert.ok(inst, "global-fallback restores the pre-#2877 ride"); + assert.equal(inst?.origin, "http://127.0.0.1:8787"); +}); + +test("findLiveAttachableInstance: same-lane daemon still attaches under default own-lane (#2877)", async () => { + const inst = await findLiveAttachableInstance( + { host: "127.0.0.1", port: 0, passthrough: false, debug: false, lane: "pi" }, + { + fetchHealthInfo: async () => ({ ok: true, watchdog: { armed: true } }), + readInstanceFile: () => recordedInstance({ origin: "http://127.0.0.1:18788", port: 18788, lane: "pi" }), + resolveAttachPolicy: () => "own-lane", + scriptPath: FP_SCRIPT, + }, + ); + assert.ok(inst, "a same-lane armed daemon is always rideable"); + assert.equal(inst?.origin, "http://127.0.0.1:18788"); +}); + +test("findLiveAttachableInstance: explicit attachUrl targets one daemon despite own-lane (#2877)", async () => { + const inst = await findLiveAttachableInstance( + { host: "127.0.0.1", port: 0, passthrough: false, debug: false, lane: "pi" }, + { + fetchHealthInfo: async () => ({ ok: true, watchdog: { armed: false } }), + readInstanceFile: () => recordedInstance({ origin: "http://127.0.0.1:8787", port: 8787 }), + resolveAttachPolicy: () => "own-lane", + // trailing slash exercises normalizeOrigin + resolveAttachUrl: () => "http://127.0.0.1:8787/", + scriptPath: FP_SCRIPT, + }, + ); + assert.ok(inst, "explicit target bypasses the policy filter"); + assert.equal(inst?.origin, "http://127.0.0.1:8787"); +}); + +test("findLiveAttachableInstance: attachUrl pointing elsewhere leaves no candidate (#2877)", async () => { + const inst = await findLiveAttachableInstance( + { host: "127.0.0.1", port: 0, passthrough: false, debug: false, lane: "pi" }, + { + fetchHealthInfo: async () => ({ ok: true, watchdog: { armed: false } }), + readInstanceFile: () => recordedInstance({ origin: "http://127.0.0.1:8787", port: 8787 }), + resolveAttachPolicy: () => "own-lane", + resolveAttachUrl: () => "http://127.0.0.1:9999", + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(inst, undefined, "target mismatch → nothing to attach to"); +}); + +test("runLaunch: omitted ACP_PORT rides a lane-less user-zone daemon only when attachPolicy=global-fallback (#2877)", async () => { const env = piLaunchEnv(); const st = isoStateDir(); const ex = stubProcessExit(); @@ -2089,6 +2201,7 @@ test("runLaunch: omitted ACP_PORT keeps the legacy selection (still attaches a u spawnImpl, sleep: () => Promise.resolve(), scriptPath: FP_SCRIPT, + resolveAttachPolicy: () => "global-fallback", }, ); assert.equal(spawnCalls, 0, "no explicit port → free to attach to the user-zone daemon (pre-existing behavior)"); diff --git a/tests/listen-policy.test.ts b/tests/listen-policy.test.ts new file mode 100644 index 0000000000..79aa11ff23 --- /dev/null +++ b/tests/listen-policy.test.ts @@ -0,0 +1,90 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { decideEaddrinuse, postBindCanLadder, UPGRADE_REPLACEMENT_ENV, type EaddrinuseContext } from "../src/listen-policy.ts"; + +const base: EaddrinuseContext = { + upgradeReplacement: false, + twinHolds: false, + launchToken: true, + strictPort: false, + attempts: 0, + maxAttempts: 17, + predecessorTicksLeft: 10, + predecessorHolds: false, + lastTriedPort: 18787, +}; + +test("decideEaddrinuse: upgrade replacement never ladders (#3044)", () => { + // No predecessor recognized (foreign squatter, same-code peer, or no lane): + // fail fast on the first hit — the +1 ladder is exactly what stranded the + // orphan processes of #3044. + assert.deepEqual( + decideEaddrinuse({ ...base, upgradeReplacement: true }), + { kind: "fail-fast", reason: "upgrade-replacement" }, + ); + // A same-lane DIFFERENT-code holder gets the bounded same-port wait + // (#1723 overlap: the prior instance may still be releasing)... + assert.deepEqual( + decideEaddrinuse({ ...base, upgradeReplacement: true, predecessorHolds: true }), + { kind: "wait-predecessor", port: 18787 }, + ); + // ...but once the budget is spent it still fails fast instead of laddering. + assert.deepEqual( + decideEaddrinuse({ ...base, upgradeReplacement: true, predecessorHolds: true, predecessorTicksLeft: 0 }), + { kind: "fail-fast", reason: "upgrade-replacement" }, + ); + // The replacement contract does not depend on launch token or attempt count. + assert.deepEqual( + decideEaddrinuse({ ...base, upgradeReplacement: true, launchToken: false, attempts: 5 }), + { kind: "fail-fast", reason: "upgrade-replacement" }, + ); +}); + +test("decideEaddrinuse: legacy launcher-child behavior is unchanged", () => { + // Predecessor overlap still waits out the draining old build on the SAME port. + assert.deepEqual( + decideEaddrinuse({ ...base, predecessorHolds: true }), + { kind: "wait-predecessor", port: 18787 }, + ); + // Plain contention ladders +1... + assert.deepEqual(decideEaddrinuse(base), { kind: "ladder", nextPort: 18788 }); + // ...and the final attempt asks for an ephemeral port. + assert.deepEqual( + decideEaddrinuse({ ...base, attempts: 16 }), + { kind: "ladder", nextPort: 0 }, + ); + // Exhausted attempts fall through to fail-fast. + assert.deepEqual( + decideEaddrinuse({ ...base, attempts: 17 }), + { kind: "fail-fast", reason: "port-busy" }, + ); +}); + +test("decideEaddrinuse: strict-port and manual launches keep their fail-fast reasons", () => { + assert.deepEqual( + decideEaddrinuse({ ...base, strictPort: true }), + { kind: "fail-fast", reason: "strict-port" }, + ); + // A manual launch (no launch token) was always fail-fast; unchanged. + assert.deepEqual( + decideEaddrinuse({ ...base, launchToken: false }), + { kind: "fail-fast", reason: "port-busy" }, + ); +}); + +test("decideEaddrinuse: env marker name is stable (#3044)", () => { + assert.equal(UPGRADE_REPLACEMENT_ENV, "BILI_UPGRADE_REPLACEMENT"); +}); + +test("postBindCanLadder: a marked upgrade replacement never gains post-bind ladder rights (#3044/#2941)", () => { + // Launcher child on a contested just-bound port keeps today's move-off + // right (#2941). + assert.equal(postBindCanLadder(true, false, false), true); + // Strict-port and manual launches never laddered; unchanged. + assert.equal(postBindCanLadder(true, true, false), false); + assert.equal(postBindCanLadder(false, false, false), false); + // #3044: the replacement inherits its parent's launch token but must die + // on a contested port instead of hopping — the orphan shape, via the + // second hop path. + assert.equal(postBindCanLadder(true, false, true), false); +}); diff --git a/tests/port-zone-live.test.ts b/tests/port-zone-live.test.ts index bdc7e5b8c9..475579a71a 100644 --- a/tests/port-zone-live.test.ts +++ b/tests/port-zone-live.test.ts @@ -1,13 +1,14 @@ import test, { after } from "node:test"; import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; import fs from "node:fs"; import net from "node:net"; import os from "node:os"; import path from "node:path"; import { ensureProxyRunning } from "../src/launcher.ts"; -import { portZoneFilePath, readZonePort } from "../src/instance.ts"; +import { isPidAlive, portZoneFilePath, readZonePort } from "../src/instance.ts"; import { ZONE_PORT_BASE } from "../src/config.ts"; +import { UPGRADE_REPLACEMENT_ENV } from "../src/listen-policy.ts"; // #1660 live regression: the sticky-zone lifecycle against REAL proxy // processes — real spawn handshake, real EADDRINUSE ladder, real attach @@ -63,6 +64,17 @@ function killNow(pid: number | undefined): void { } } +function portOpen(port: number): Promise { + return new Promise((resolve) => { + const s = net.connect({ host: "127.0.0.1", port }); + s.once("connect", () => { + s.destroy(); + resolve(true); + }); + s.once("error", () => resolve(false)); + }); +} + function freePort(): Promise { return new Promise((resolve, reject) => { const srv = net.createServer(); @@ -331,3 +343,96 @@ test( }); }, ); + +// --------------------------------------------------------------------------- +// #3044: the orphan shape end-to-end. A self-restart replacement that cannot +// grab the freed port must DIE LOUDLY instead of hopping +1 and idling as an +// orphan nobody routes to. Spawned directly (not through ensureProxyRunning) +// so the exact replacement env is under test control: launch token + lane +// (which would earn it the #407 ladder pre-#3044) plus the bind-or-die marker. +// --------------------------------------------------------------------------- + +test( + "zone live: marked upgrade-replacement fails fast on an occupied port instead of hopping (#3044)", + { timeout: 240_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + // A non-bili squatter holds the zone base: no same-lane predecessor + // is recognized, so the marked child gets no wait budget at all — + // first EADDRINUSE must be its last breath. Under the pre-#3044 + // ladder this exact spawn drifted to base+1 and idled there. + const squatter = await squatted(ZONE_PORT_BASE); + const child = spawn( + process.execPath, + [distCli, "start", "--host", "127.0.0.1", "--port", String(ZONE_PORT_BASE)], + { + env: { + ...process.env, + BILI_LAUNCH_TOKEN: "3044-live-test", + BILI_LAUNCHER_LANE: "zcode", + [UPGRADE_REPLACEMENT_ENV]: "1", + }, + stdio: "ignore", + detached: true, + }, + ); + trackKill(child.pid); + try { + const exitCode = await new Promise((resolve) => { + child.once("exit", (code) => resolve(code)); + setTimeout(() => resolve(undefined), 120_000).unref(); + }); + assert.equal(exitCode, 1, "the marked replacement must fail fast with exit code 1 (upgrade pending, host decides retry)"); + assert.equal(await portOpen(ZONE_PORT_BASE + 1), false, "nothing may have hopped onto the next port — that idle hopper IS the #3044 orphan shape"); + assert.equal(await portOpen(ZONE_PORT_BASE), true, "the squatter still owns the base port"); + squatter.close(); + } finally { + killNow(child.pid); + } + }); + }, +); + +test( + "zone live: unmarked lane'd spawn against a LIVE same-build twin exits instead of hopping (#3044)", + { timeout: 240_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + // The 2026-10-13 recurrence shape: a host respawn raced an attach + // scan and spawned while an identical instance already served the + // lane's port. Before this fix that child laddered to base+1 and + // idled as an orphan; now the duplicate must lose loudly. Spawned + // directly (unmarked, exactly what the launcher produces) because + // ensureProxyRunning would attach to the twin and never spawn. + const h1 = await launch({ lane: "zcode" }); + const daemon1 = h1.child?.pid; + trackKill(daemon1); + assert.equal(h1.port, ZONE_PORT_BASE, "precondition: the twin serves the zone base"); + const child = spawn( + process.execPath, + [distCli, "start", "--host", "127.0.0.1", "--port", String(ZONE_PORT_BASE)], + { + env: { ...process.env, BILI_LAUNCH_TOKEN: "3044-twin-test", BILI_LAUNCHER_LANE: "zcode" }, + stdio: "ignore", + detached: true, + }, + ); + trackKill(child.pid); + try { + const exitCode = await new Promise((resolve) => { + child.once("exit", (code) => resolve(code)); + setTimeout(() => resolve(undefined), 120_000).unref(); + }); + assert.equal(exitCode, 1, "the duplicate must fail fast with exit code 1"); + assert.equal(await portOpen(ZONE_PORT_BASE + 1), false, "nothing may have hopped onto the next port — the hopper IS the orphan shape"); + assert.equal(await portOpen(ZONE_PORT_BASE), true, "the serving twin keeps its port"); + assert.ok(daemon1 !== undefined && isPidAlive(daemon1), "the serving twin must still be alive"); + } finally { + killNow(child.pid); + killNow(daemon1); + } + }); + }, +); diff --git a/tests/wire-contract-fakes.ts b/tests/wire-contract-fakes.ts index d130726b68..711f0209da 100644 --- a/tests/wire-contract-fakes.ts +++ b/tests/wire-contract-fakes.ts @@ -21,11 +21,23 @@ export type Wire = "anthropic" | "openai-chat" | "responses" | "google"; interface WireRule { readonly id: string; readonly wire: Wire; + /** Lane scope (e.g. "codex") — the constraint only holds on that client's lane, so its + * enforcement lives in the lane's own fake, not in the wire's shared VALIDATOR. */ + readonly lane?: string; readonly summary: string; readonly provenance: string; } export const WIRE_RULES: readonly WireRule[] = [ + { + id: "WC-017", + wire: "responses", + lane: "codex", + summary: + "codex CLI Responses WebSocket create frames carry stream:true (required field in the client's WS request struct) plus optional stream_options — bili must forward both verbatim on the upstream egress; dropping them made chatgpt.com answer with a zero-output completed turn", + provenance: + "bili #3063 production silent failure (codex 0.162.0-alpha.17.2 through /bili/ prefix routing on bili 0.1.183+: upstream counted input tokens, produced zero output, turn ended completed; identical via --passthrough). Cross-checked against openai/codex source: codex-rs/codex-api/src/common.rs ResponseCreateWsRequest declares stream: bool as a required serialized field (no skip_serializing_if) and serializes stream_options when present; codex-rs/core/tests/suite/client_websockets.rs asserts body[\"stream\"] == true on the wire. Repair: src/responses-ws.ts re-attaches the client's transport fields at egress (egressTransportFields); supersedes WC-013's over-generalized scope for the codex lane.", + }, { id: "WC-016", wire: "anthropic", @@ -44,8 +56,8 @@ export const WIRE_RULES: readonly WireRule[] = [ { id: "WC-013", wire: "responses", - summary: "Responses WebSocket requests use response.create and omit HTTP-only stream/background/stream_options fields", - provenance: "OpenAI WebSocket mode guide https://developers.openai.com/api/docs/guides/websocket-mode/ (transport-specific stream/background fields are not used); OpenCode v2.0.20 open-responses-channel.ts removes these fields; bili #1844 adds a WS transport rather than sending HTTP envelopes verbatim.", + summary: "OpenCode V2 Responses WebSocket requests use response.create and omit HTTP-only stream/background/stream_options fields — that client's contract; the codex CLI lane instead REQUIRES stream on create frames (see WC-017)", + provenance: "OpenAI WebSocket mode guide https://developers.openai.com/api/docs/guides/websocket-mode/ (transport-specific stream/background fields are not used); OpenCode v2.0.20 open-responses-channel.ts removes these fields; bili #1844 adds a WS transport rather than sending HTTP envelopes verbatim. Scope corrected per #3063 (2026-10-13): the rule was over-generalized from the OpenCode V2 client to all WS lanes — the codex CLI's own create frames carry stream:true as a required field, and chatgpt.com answers stream-less frames with a zero-output completed turn.", }, { id: "WC-012", @@ -432,6 +444,16 @@ export function validateResponsesWsCreate(body: unknown): string[] { return ["stream", "stream_options", "background"].filter(key => key in body).map(key => `WC-013: HTTP-only ${key} must not reach WebSocket response.create`); } +/** WC-017 on a codex-lane create frame: stream:true is REQUIRED (the client's request + * struct declares it without skip_serializing_if) — the inverse of WC-013's opencode lane. */ +export function validateCodexResponsesWsCreate(body: unknown): string[] { + if (!isPlainObject(body) || body.type !== "response.create") return ["WC-017: expected response.create WebSocket event"]; + const out: string[] = []; + if (body.stream !== true) out.push("WC-017: codex response.create must carry stream:true — required field in the codex WS request struct; dropping it made chatgpt.com answer with a zero-output completed turn (#3063)"); + if (body.background !== undefined) out.push("WC-017: codex response.create must not carry background"); + return out; +} + /** WC-006 on a Gemini generateContent/streamGenerateContent body. */ function validateGoogleBody(body: unknown): string[] { const out: string[] = []; diff --git a/tests/wire-contract.test.ts b/tests/wire-contract.test.ts index cf7440d31e..ecc68dce6a 100644 --- a/tests/wire-contract.test.ts +++ b/tests/wire-contract.test.ts @@ -52,7 +52,7 @@ import { retrieveToolsFor, IMAGE_FULL_TOOL_GOOGLE, } from "../src/compress-tool.ts"; -import { WIRE_RULES, WIRE_HEADER_RULES, VALIDATORS, startFakeUpstream, validateResponsesWsCreate, validateGoSessionHeaders, type Wire } from "./wire-contract-fakes.ts"; +import { WIRE_RULES, WIRE_HEADER_RULES, VALIDATORS, startFakeUpstream, validateResponsesWsCreate, validateCodexResponsesWsCreate, validateGoSessionHeaders, type Wire } from "./wire-contract-fakes.ts"; type ToolShape = Record; @@ -174,6 +174,7 @@ test("wire-contract ledger: every rule has a live enforcement clause", () => { ], }; for (const rule of WIRE_RULES) { + if (rule.lane) continue; // lane-scoped rules are gated by their own lane's fake — see the lane probe gate below const enforced = probes[rule.wire].some((body) => VALIDATORS[rule.wire](body).some((v) => v.startsWith(rule.id)), ); @@ -181,6 +182,18 @@ test("wire-contract ledger: every rule has a live enforcement clause", () => { } }); +test("wire-contract ledger: every lane-scoped rule has a live enforcement clause", () => { + // Lane-scoped constraints hold on ONE client's lane only — the shared wire validator + // cannot enforce them (WC-013 forbids exactly what WC-017 requires, same frame shape). + const laneProbes: Array<{ ruleId: string; validate: (body: unknown) => string[]; body: unknown }> = [ + { ruleId: "WC-017", validate: validateCodexResponsesWsCreate, body: { type: "response.create", input: [] } }, + ]; + for (const { ruleId, validate, body } of laneProbes) { + assert.ok(validate(body).some(v => v.startsWith(ruleId)), `lane-scoped rule ${ruleId} has no live enforcement clause in its lane fake`); + } + for (const rule of WIRE_RULES) if (rule.lane) assert.ok(laneProbes.some(p => p.ruleId === rule.id), `lane-scoped rule ${rule.id} is missing from the lane probe table`); +}); + test("wire-contract ledger: every header rule has a live enforcement clause", () => { for (const rule of WIRE_HEADER_RULES) { const enforced = validateGoSessionHeaders({}).some((v) => v.startsWith(rule.id)); diff --git a/website/config-reference/env-only.yaml b/website/config-reference/env-only.yaml index 213d4021f5..7b4d0c7b4e 100644 --- a/website/config-reference/env-only.yaml +++ b/website/config-reference/env-only.yaml @@ -154,6 +154,14 @@ entries: group: envonly desc_en: "Spawn channel: exact-port requirement (squatters refused loudly instead of hopping)." desc_zh: "派生通道:精确端口要求(被占用时响亮拒绝而非跳端口)。" + - key: BILI_UPGRADE_REPLACEMENT + type: boolean-ish + default: "unset" + kind: env-only + audience: internal + group: envonly + desc_en: "Spawn channel: marks a self-restart replacement — it must own exactly the freed port or exit without hopping (#3044)." + desc_zh: "派生通道:标记自重启替换进程——必须独占被释放的精确端口,否则直接退出而非跳端口(#3044)。" - key: BILI_OPENCODE_ACP_SPEC type: string default: "unset" diff --git a/website/config-reference/server.yaml b/website/config-reference/server.yaml index f5c5bfbae7..27b192a492 100644 --- a/website/config-reference/server.yaml +++ b/website/config-reference/server.yaml @@ -349,6 +349,20 @@ entries: 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: native.attachPolicy + type: "\"own-lane\" | \"global-fallback\"" + default: "own-lane" + env: BILI_NATIVE_ATTACH_POLICY + group: behavior + desc_en: "Lane affinity for native-hook attach, and the gate on whether any cross-lane riding happens (#2877). own-lane (default): a LANEd hook rides ONLY a same-lane daemon and, with none available, spawns its own instead of falling back onto a lane-less / manually-started bili start daemon or another lane's daemon (that convergence pinned every agent to one daemon's version and double-wrote sessions); an armed lane-less daemon (a managed shared proxy, #1225) stays shareable under either policy. global-fallback restores the pre-#2877 behavior: same-lane first, then a compatible lane-less/user-zone daemon, and (with attachLanePriority) the listed foreign lanes." + desc_zh: "native hook 附着的 lane 亲和,也是是否发生跨 lane 搭车的总闸(#2877)。own-lane(默认):lane 型 hook 只搭同 lane 的守护;没有时自行派生,而不是回落到无 lane / 手动启动的 bili start 守护或其他 lane 的守护(那种汇聚会把所有 agent 钉死在一台守护的版本上并双写会话);已武装的无 lane 守护(受管共享代理,#1225)在两种策略下都可被搭车。global-fallback 恢复 #2877 之前的行为:先同 lane,再兼容的无 lane/用户区守护,以及(配 attachLanePriority)列出的外部 lane。" + - key: native.attachUrl + type: string + default: "unset (discover per lane)" + env: BILI_MCP_PROXY + group: behavior + desc_en: "Explicit target origin for native-hook attach (any URL). When set, a hook attaches ONLY to that exact origin instead of auto-discovering, and spawns its own if it is not live; it must still be code-compatible and pass the lifecycle gate. The BILI_MCP_PROXY env var (also set by CLI --origin) takes precedence over this file value; empty/whitespace means unset." + desc_zh: "native hook 附着的显式目标源(任意 URL)。设置后,hook 只附着到该精确 origin 而不是自动发现,若其不在线则自行派生;仍需代码兼容并通过生命周期门禁。BILI_MCP_PROXY 环境变量(CLI --origin 亦会设置它)优先于此文件值;空/空白视为未设置。" - key: claude.nativePort type: number default: "unset (lane sticky zone port)" From 1ad797190051c806baaa309ea804cbd1d87d1dc8 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 21:38:14 +0800 Subject: [PATCH 04/20] refactor: converge PR diff to repo style and purpose - Drop the repo-wide 4-space-to-tab reformat churn: touched core files (plugin-install, doctor, doctor test) restored to master layout with only the PR's own semantic edits reapplied. - Expand leading tabs back to 4 spaces in the new codex modules and their tests (repo style is 4-space; no formatter config). - Drop the unrelated .scratch/ .gitignore addition. - Keep the real wiring: bili service CLI family, codex install/ remove faces, bootstrap-hook build entry, admin stats field. Part of #3176 (conflict takeover, per owner directive). --- .gitignore | 2 - src/codex-integration/cc-switch.ts | 190 +- src/codex-integration/chatgpt-capability.ts | 16 +- src/codex-integration/hooks.ts | 370 +- src/codex-integration/skill.ts | 128 +- src/codex-integration/status.ts | 294 +- src/codex-integration/toml-field.ts | 410 +- src/codex/bootstrap-hook.ts | 134 +- src/doctor.ts | 978 ++-- src/plugin-install.ts | 5362 +++++++++---------- src/proxy-service/index.ts | 42 +- src/proxy-service/service.ts | 1782 +++--- src/proxy-service/systemd.ts | 222 +- tests/codex-cc-switch.test.ts | 58 +- tests/codex-chatgpt-capability.test.ts | 22 +- tests/codex-hooks-skill.test.ts | 616 +-- tests/codex-install-faces.test.ts | 236 +- tests/codex-route.test.ts | 270 +- tests/doctor.test.ts | 2426 ++++----- tests/proxy-service.test.ts | 1206 ++--- tsup.config.ts | 204 +- 21 files changed, 7467 insertions(+), 7501 deletions(-) diff --git a/.gitignore b/.gitignore index 239a0b30d1..7e2336bcda 100644 --- a/.gitignore +++ b/.gitignore @@ -7,5 +7,3 @@ dist/ tmp/ tests/.pp-stamp-state-*/ .tmp/ -# Local development specifications and ticket drafts (not published) -.scratch/ diff --git a/src/codex-integration/cc-switch.ts b/src/codex-integration/cc-switch.ts index 1257131983..10fc82b7d9 100644 --- a/src/codex-integration/cc-switch.ts +++ b/src/codex-integration/cc-switch.ts @@ -5,118 +5,118 @@ import path from "node:path"; export type CcSwitchMode = "direct" | "routing" | "aggregation" | "unknown"; export interface CcSwitchDetection { - discovered: boolean; - mode: CcSwitchMode; - compatibility: "unsupported" | "config-route-only"; - evidence: string[]; - detail: string; + discovered: boolean; + mode: CcSwitchMode; + compatibility: "unsupported" | "config-route-only"; + evidence: string[]; + detail: string; } function object(value: unknown): Record | undefined { - return value !== null && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : undefined; + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; } function modeValue(root: unknown): string | undefined { - const row = object(root); - if (!row) return undefined; - const apps = object(row.apps); - const codex = object(row.codex) ?? object(apps?.codex); - const values = [ - row.mode, - row.proxyMode, - row.routingMode, - codex?.mode, - codex?.proxyMode, - ]; - for (const candidate of values) { - if (typeof candidate === "string") - return candidate.trim().toLowerCase().replace(/[ _]/g, "-"); - } - return undefined; + const row = object(root); + if (!row) return undefined; + const apps = object(row.apps); + const codex = object(row.codex) ?? object(apps?.codex); + const values = [ + row.mode, + row.proxyMode, + row.routingMode, + codex?.mode, + codex?.proxyMode, + ]; + for (const candidate of values) { + if (typeof candidate === "string") + return candidate.trim().toLowerCase().replace(/[ _]/g, "-"); + } + return undefined; } function normalizeMode(value: string | undefined): CcSwitchMode { - if (value === "direct" || value === "direct-mode") return "direct"; - if (value === "routing" || value === "routing-mode" || value === "proxy") - return "routing"; - if ( - value === "aggregation" || - value === "aggregator" || - value === "aggregation-mode" - ) - return "aggregation"; - return "unknown"; + if (value === "direct" || value === "direct-mode") return "direct"; + if (value === "routing" || value === "routing-mode" || value === "proxy") + return "routing"; + if ( + value === "aggregation" || + value === "aggregator" || + value === "aggregation-mode" + ) + return "aggregation"; + return "unknown"; } export function detectCcSwitchFromText( - settingsText?: string, - liveStateText?: string, + settingsText?: string, + liveStateText?: string, ): CcSwitchDetection { - const evidence: string[] = []; - let mode: CcSwitchMode = "unknown"; - for (const [label, text] of [ - ["settings.json", settingsText], - ["live-state.json", liveStateText], - ] as const) { - if (text === undefined) continue; - evidence.push(label); - try { - const parsed: unknown = JSON.parse(text); - const found = normalizeMode(modeValue(parsed)); - if (found !== "unknown") mode = found; - } catch { - return { - discovered: true, - mode: "unknown", - compatibility: "unsupported", - evidence, - detail: `${label} exists but is not valid JSON; bili did not modify it`, - }; - } - } - if (evidence.length === 0) - return { - discovered: false, - mode: "unknown", - compatibility: "unsupported", - evidence, - detail: "CC Switch was not detected", - }; - return { - discovered: true, - mode, - compatibility: mode === "direct" ? "config-route-only" : "unsupported", - evidence, - detail: - mode === "unknown" - ? "CC Switch state was found but its Codex mode is not recognized; discovery is not proof of routing compatibility" - : mode === "direct" - ? "CC Switch Direct can use a reversible route on the active Codex provider base_url; provider-database synchronization is not integrated" - : `CC Switch reports ${mode} mode; bili does not rewrite its provider state and has no coordination interface, so this is not a compatibility claim`, - }; + const evidence: string[] = []; + let mode: CcSwitchMode = "unknown"; + for (const [label, text] of [ + ["settings.json", settingsText], + ["live-state.json", liveStateText], + ] as const) { + if (text === undefined) continue; + evidence.push(label); + try { + const parsed: unknown = JSON.parse(text); + const found = normalizeMode(modeValue(parsed)); + if (found !== "unknown") mode = found; + } catch { + return { + discovered: true, + mode: "unknown", + compatibility: "unsupported", + evidence, + detail: `${label} exists but is not valid JSON; bili did not modify it`, + }; + } + } + if (evidence.length === 0) + return { + discovered: false, + mode: "unknown", + compatibility: "unsupported", + evidence, + detail: "CC Switch was not detected", + }; + return { + discovered: true, + mode, + compatibility: mode === "direct" ? "config-route-only" : "unsupported", + evidence, + detail: + mode === "unknown" + ? "CC Switch state was found but its Codex mode is not recognized; discovery is not proof of routing compatibility" + : mode === "direct" + ? "CC Switch Direct can use a reversible route on the active Codex provider base_url; provider-database synchronization is not integrated" + : `CC Switch reports ${mode} mode; bili does not rewrite its provider state and has no coordination interface, so this is not a compatibility claim`, + }; } export function detectCcSwitch(home = os.homedir()): CcSwitchDetection { - const root = path.join(home, ".cc-switch"); - const files = ["settings.json", "live-state.json"]; - const contents: Array = files.map((name) => { - try { - return fs.readFileSync(path.join(root, name), "utf8"); - } catch { - return undefined; - } - }); - return detectCcSwitchFromText(contents[0], contents[1]); + const root = path.join(home, ".cc-switch"); + const files = ["settings.json", "live-state.json"]; + const contents: Array = files.map((name) => { + try { + return fs.readFileSync(path.join(root, name), "utf8"); + } catch { + return undefined; + } + }); + return detectCcSwitchFromText(contents[0], contents[1]); } export function isProxyManagedCredential(value: string): boolean { - return ( - value - .trim() - .replace(/^Bearer\s+/i, "") - .trim() - .toUpperCase() === "PROXY_MANAGED" - ); + return ( + value + .trim() + .replace(/^Bearer\s+/i, "") + .trim() + .toUpperCase() === "PROXY_MANAGED" + ); } diff --git a/src/codex-integration/chatgpt-capability.ts b/src/codex-integration/chatgpt-capability.ts index 02a06b7a96..919545aaa9 100644 --- a/src/codex-integration/chatgpt-capability.ts +++ b/src/codex-integration/chatgpt-capability.ts @@ -2,15 +2,15 @@ * This capability record is declarative: it never reads, copies, persists, or * injects auth.json, cookies, session tokens, or desktop credentials. */ export interface ChatGptDesktopCapability { - state: "待完成/可实现"; - credentials: "not-read-not-persisted"; - officialLoginChannels: "preserved"; - desktopMcp: "separate-from-model-routing"; + state: "待完成/可实现"; + credentials: "not-read-not-persisted"; + officialLoginChannels: "preserved"; + desktopMcp: "separate-from-model-routing"; } export const chatGptDesktopCapability: ChatGptDesktopCapability = { - state: "待完成/可实现", - credentials: "not-read-not-persisted", - officialLoginChannels: "preserved", - desktopMcp: "separate-from-model-routing", + state: "待完成/可实现", + credentials: "not-read-not-persisted", + officialLoginChannels: "preserved", + desktopMcp: "separate-from-model-routing", }; diff --git a/src/codex-integration/hooks.ts b/src/codex-integration/hooks.ts index 6c3a14befa..f20aa61c79 100644 --- a/src/codex-integration/hooks.ts +++ b/src/codex-integration/hooks.ts @@ -25,18 +25,18 @@ const FEATURES_KEY = "hooks"; export type CodexHookStage = "session_start"; export interface CodexHookEntry { - kind: CodexHookStage; - command: string; - timeoutSec?: number; + kind: CodexHookStage; + command: string; + timeoutSec?: number; } /** True for a hook command naming bili's own Codex hook script. Path may differ * across installs/upgrades (checkout vs. global npm), so match the script * name, not the absolute path — same rule as the Claude lane. */ export function isBiliCodexHookCommand(command: string): boolean { - return /(?:^|[\\/])codex[\\/]bootstrap-hook\.(?:js|mjs|ts)["']?\s*(?:$|\s)/.test( - command.trim(), - ); + return /(?:^|[\\/])codex[\\/]bootstrap-hook\.(?:js|mjs|ts)["']?\s*(?:$|\s)/.test( + command.trim(), + ); } /** Parse the hook entries out of a `hooks.SessionStart` region. Only `command` @@ -45,33 +45,33 @@ export function isBiliCodexHookCommand(command: string): boolean { * of overwriting it. Handles both `command = "..."` on its own line (the * array-of-tables form bili writes) and inline tables. */ export function readCodexHookCommands(region: string): string[] { - const out: string[] = []; - for (const match of region.matchAll( - /command\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^']*)')/g, - )) { - const raw = match[1]; - if (raw === undefined) continue; - if (raw.startsWith("'")) { - out.push(raw.slice(1, -1)); - continue; - } - try { - const parsed: unknown = JSON.parse(raw); - if (typeof parsed === "string") out.push(parsed); - } catch { - // A malformed escape is not ours to repair; skip the entry. - } - } - return out; + const out: string[] = []; + for (const match of region.matchAll( + /command\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^']*)')/g, + )) { + const raw = match[1]; + if (raw === undefined) continue; + if (raw.startsWith("'")) { + out.push(raw.slice(1, -1)); + continue; + } + try { + const parsed: unknown = JSON.parse(raw); + if (typeof parsed === "string") out.push(parsed); + } catch { + // A malformed escape is not ours to repair; skip the entry. + } + } + return out; } /** Does the config already carry bili's hook entry? */ export function findBiliCodexHook(text: string): string | undefined { - for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { - const command = readCodexHookCommands(region).find(isBiliCodexHookCommand); - if (command !== undefined) return command; - } - return undefined; + for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { + const command = readCodexHookCommands(region).find(isBiliCodexHookCommand); + if (command !== undefined) return command; + } + return undefined; } /** The `[features] hooks` switch, when the user has set one. Scanned by hand @@ -85,24 +85,24 @@ export function findBiliCodexHook(text: string): string | undefined { * "hook execution is not enabled" on a config that plainly said * `hooks = true`, and would have nagged every Windows user. */ export function codexHooksFeature( - text: string, + text: string, ): { value: boolean; raw: string } | undefined { - for (const region of tableRegions(text, FEATURES_TABLE)) { - for (const line of region.split("\n").slice(1)) { - const match = - /^[ \t]*hooks[ \t]*=[ \t]*([^#\s]+)[ \t]*(?:#.*)?\r?$/.exec(line); - if (match === null) continue; - const raw = match[1]; - if (raw === undefined) continue; - return { value: raw.trim().toLowerCase() === "true", raw }; - } - } - return undefined; + for (const region of tableRegions(text, FEATURES_TABLE)) { + for (const line of region.split("\n").slice(1)) { + const match = + /^[ \t]*hooks[ \t]*=[ \t]*([^#\s]+)[ \t]*(?:#.*)?\r?$/.exec(line); + if (match === null) continue; + const raw = match[1]; + if (raw === undefined) continue; + return { value: raw.trim().toLowerCase() === "true", raw }; + } + } + return undefined; } export type CodexHookPlan = - | { action: "install" | "refresh"; text: string; note: string } - | { action: "keep"; text: string; note: string }; + | { action: "install" | "refresh"; text: string; note: string } + | { action: "keep"; text: string; note: string }; /** Render the hook entry bili owns. * @@ -120,7 +120,7 @@ export type CodexHookPlan = * `probe-hooks.mjs` during development, and the regression test that pins this * shape in tests/codex-hooks-skill.test.ts. */ export function codexHookTable(command: string, timeoutSec = 15): string { - return `[[${CODEX_HOOKS_TABLE}]]\nhooks = [{ type = "command", command = ${JSON.stringify(command)}, timeout = ${timeoutSec} }]\n`; + return `[[${CODEX_HOOKS_TABLE}]]\nhooks = [{ type = "command", command = ${JSON.stringify(command)}, timeout = ${timeoutSec} }]\n`; } /** Is this region the nested `MatcherGroup` shape Codex actually registers? @@ -128,42 +128,42 @@ export function codexHookTable(command: string, timeoutSec = 15): string { * (bili's older, silently-invisible output), which must be replaced whole * rather than command-rewritten. */ function isNestedHookRegion(region: string): boolean { - return /^\s*hooks\s*=\s*\[/m.test(region); + return /^\s*hooks\s*=\s*\[/m.test(region); } /** The line ending a config already uses. Follows the repo convention * (src/kimi/toml-edit.ts:21, src/launcher.ts:2466): never convert a user's * file, and never mix endings into it — Codex keeps CRLF on Windows. */ function detectEol(text: string): string { - return text.includes("\r\n") ? "\r\n" : "\n"; + return text.includes("\r\n") ? "\r\n" : "\n"; } /** Replace bili's own entry inside an existing region, leaving every other * entry (and any foreign formatting we cannot parse) untouched: only the * matched `command = "..."` span is rewritten. */ function rewriteBiliHookCommand(region: string, command: string): string { - let replaced = false; - return region.replace( - /command\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^']*)')/g, - (match, raw: string) => { - if (replaced) return match; - let decoded: string | undefined; - if (raw.startsWith("'")) { - decoded = raw.slice(1, -1); - } else { - try { - const parsed: unknown = JSON.parse(raw); - decoded = typeof parsed === "string" ? parsed : undefined; - } catch { - decoded = undefined; - } - } - if (decoded === undefined || !isBiliCodexHookCommand(decoded)) - return match; - replaced = true; - return `command = ${JSON.stringify(command)}`; - }, - ); + let replaced = false; + return region.replace( + /command\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^']*)')/g, + (match, raw: string) => { + if (replaced) return match; + let decoded: string | undefined; + if (raw.startsWith("'")) { + decoded = raw.slice(1, -1); + } else { + try { + const parsed: unknown = JSON.parse(raw); + decoded = typeof parsed === "string" ? parsed : undefined; + } catch { + decoded = undefined; + } + } + if (decoded === undefined || !isBiliCodexHookCommand(decoded)) + return match; + replaced = true; + return `command = ${JSON.stringify(command)}`; + }, + ); } /** Pure planner for the hook face. `command` is the full hook command line @@ -177,54 +177,54 @@ function rewriteBiliHookCommand(region: string, command: string): string { * (a foreign SessionStart entry already present), meant bili's hook silently * never installed. */ export function planCodexHook(text: string, command: string): CodexHookPlan { - const regions = tableRegions(text, CODEX_HOOKS_TABLE); - const owned = regions.find( - (region) => - readCodexHookCommands(region).find(isBiliCodexHookCommand) !== undefined, - ); - if (owned === undefined) { - const eol = detectEol(text); - const prefix = text.length === 0 || text.endsWith("\n") ? text : `${text}${eol}`; - // A foreign entry in the same array is preserved verbatim: we only append. - const suffix = - regions.length > 0 ? " (kept existing SessionStart entries)" : ""; - const entry = codexHookTable(command).replace(/\n$/, "").split("\n").join(eol); - return { - action: "install", - text: `${prefix}${eol}${entry}${eol}`, - note: `SessionStart hook added -> ${CODEX_HOOKS_TABLE}${suffix}`, - }; - } - const existing = readCodexHookCommands(owned).find(isBiliCodexHookCommand); - // Self-heal: an entry bili wrote before the MatcherGroup fix carries - // `type`/`command`/`timeout` directly on the element, which Codex silently - // ignores. Rewriting only the command string would leave it invisible - // forever, so the whole region is replaced with the nested shape. - if (!isNestedHookRegion(owned)) { - const replacement = codexHookTable(command) - .replace(/\n$/, "") - .split("\n") - .join(detectEol(text)); - return { - action: "refresh", - text: text.replace(owned, replacement), - note: "SessionStart hook upgraded to the shape Codex registers", - }; - } - if (existing === command) - return { - action: "keep", - text, - note: "SessionStart hook already installed", - }; - const next = rewriteBiliHookCommand(owned, command); - if (next === owned) - return { action: "keep", text, note: "SessionStart hook left as-is" }; - return { - action: "refresh", - text: text.replace(owned, next), - note: "SessionStart hook refreshed to the current command", - }; + const regions = tableRegions(text, CODEX_HOOKS_TABLE); + const owned = regions.find( + (region) => + readCodexHookCommands(region).find(isBiliCodexHookCommand) !== undefined, + ); + if (owned === undefined) { + const eol = detectEol(text); + const prefix = text.length === 0 || text.endsWith("\n") ? text : `${text}${eol}`; + // A foreign entry in the same array is preserved verbatim: we only append. + const suffix = + regions.length > 0 ? " (kept existing SessionStart entries)" : ""; + const entry = codexHookTable(command).replace(/\n$/, "").split("\n").join(eol); + return { + action: "install", + text: `${prefix}${eol}${entry}${eol}`, + note: `SessionStart hook added -> ${CODEX_HOOKS_TABLE}${suffix}`, + }; + } + const existing = readCodexHookCommands(owned).find(isBiliCodexHookCommand); + // Self-heal: an entry bili wrote before the MatcherGroup fix carries + // `type`/`command`/`timeout` directly on the element, which Codex silently + // ignores. Rewriting only the command string would leave it invisible + // forever, so the whole region is replaced with the nested shape. + if (!isNestedHookRegion(owned)) { + const replacement = codexHookTable(command) + .replace(/\n$/, "") + .split("\n") + .join(detectEol(text)); + return { + action: "refresh", + text: text.replace(owned, replacement), + note: "SessionStart hook upgraded to the shape Codex registers", + }; + } + if (existing === command) + return { + action: "keep", + text, + note: "SessionStart hook already installed", + }; + const next = rewriteBiliHookCommand(owned, command); + if (next === owned) + return { action: "keep", text, note: "SessionStart hook left as-is" }; + return { + action: "refresh", + text: text.replace(owned, next), + note: "SessionStart hook refreshed to the current command", + }; } /** Delete bili's hook entry, keeping foreign entries. Returns the text plus @@ -237,33 +237,33 @@ export function planCodexHook(text: string, command: string): CodexHookPlan { * array-of-tables shape that pattern never matched, and uninstall silently * left a `command = ""` stub hook behind. */ export function stripCodexHook(text: string): { - text: string; - removed: boolean; + text: string; + removed: boolean; } { - let removed = false; - let next = text; - for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { - const ours = readCodexHookCommands(region).find(isBiliCodexHookCommand); - if (ours === undefined) continue; - removed = true; - next = next - .replace(region, "") - .replace(/\n{3,}/g, "\n\n") - .replace(/^\n+/, ""); - if (next.length > 0 && !next.endsWith("\n")) next = `${next}\n`; - } - return { text: next, removed }; + let removed = false; + let next = text; + for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { + const ours = readCodexHookCommands(region).find(isBiliCodexHookCommand); + if (ours === undefined) continue; + removed = true; + next = next + .replace(region, "") + .replace(/\n{3,}/g, "\n\n") + .replace(/^\n+/, ""); + if (next.length > 0 && !next.endsWith("\n")) next = `${next}\n`; + } + return { text: next, removed }; } /** `[features] hooks` must be true for Codex to run the hook. Reports what the * caller has to add, without editing an existing switch the user set. */ export function codexHooksEnabledNote(text: string): string { - const feature = codexHooksFeature(text); - if (feature === undefined) - return `enable hook execution with [${FEATURES_TABLE}] ${FEATURES_KEY} = true`; - if (!feature.value) - return `[${FEATURES_TABLE}] ${FEATURES_KEY} = ${feature.raw} disables hooks — set it to true to activate`; - return ""; + const feature = codexHooksFeature(text); + if (feature === undefined) + return `enable hook execution with [${FEATURES_TABLE}] ${FEATURES_KEY} = true`; + if (!feature.value) + return `[${FEATURES_TABLE}] ${FEATURES_KEY} = ${feature.raw} disables hooks — set it to true to activate`; + return ""; } /** Last line of defence before a hook face is written to a user's real config. @@ -291,52 +291,52 @@ export function codexHooksEnabledNote(text: string): string { * Codex accepts the entry (that needs the app-server `hooks/list` RPC), but it * rules out every shape we have seen it reject or silently ignore. */ export function assertCodexConfigLoads(text: string): string | undefined { - for (const line of text.split("\n")) { - const header = /^\s*(\[\[?[^\]]+\]\]?)\s*(?:#.*)?$/.exec(line); - if (header === null) continue; - const raw = header[1]; - if (raw === undefined) continue; - const inner = raw.replace(/^\[\[?/, "").replace(/\]\]?$/, "").trim(); - // `hooks` spans more than the stage tables bili writes: Codex keeps its - // OWN trust ledger at `[hooks.state.':::']`, written - // as a single-bracket table (it holds key/value pairs, so a table is the - // correct shape and must never be flagged). Matching a bare `hooks` - // prefix treated Codex's own output as a malformed stage table and - // rejected the whole config, which silently skipped the hook face - // whenever a hook had ever been trusted. Only what bili writes is - // inspected: the stage table, plus the flat `[[hooks]]` misuse. - if (inner !== CODEX_HOOKS_TABLE && inner !== "hooks") continue; - // `[[hooks]]` with `event = "..."` is the flat-sequence shape Codex - // rejects with `expected struct HooksToml`: a bare `hooks` array cannot - // hold stage tables keyed by name. - if (inner === "hooks") - return "`[[hooks]]` is not a hook stage — use `[[hooks.SessionStart]]` (Codex expects a struct HooksToml keyed by stage name)"; - if (raw.startsWith("[[")) continue; - return `${raw.trim()} must be [[${inner}]] (Codex reads 'hooks' as a sequence, not a table)`; - } - // A top-level `hooks = ...` assignment would also collapse the sequence. - for (const line of text.split("\n")) { - if (/^\s*\[/.test(line)) break; - if (/^\s*hooks\s*=/.test(line)) - return "a top-level `hooks = ...` key must not be set (Codex reads 'hooks' as a sequence of stage tables)"; - } - for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { - const commands = readCodexHookCommands(region); - if (commands.length === 0) - return `a ${CODEX_HOOKS_TABLE} entry carries no command`; - if (commands.some((command) => command.trim() === "")) - return `a ${CODEX_HOOKS_TABLE} entry carries an empty command`; - // The MatcherGroup shape: handler fields belong INSIDE `hooks = [...]`. - // Without this the entry loads and is silently ignored. - // - // Scoped to OUR entry on purpose. A foreign entry with the wrong shape is - // its owner's bug, and refusing to write bili's own correct entry because - // of it would strand exactly the users who already run another hook tool. - if ( - commands.some(isBiliCodexHookCommand) && - !isNestedHookRegion(region) - ) - return `a ${CODEX_HOOKS_TABLE} entry must nest its handler in a 'hooks = [{ type = "command", ... }]' array (fields set directly on the entry are dropped by Codex, which registers nothing)`; - } - return undefined; + for (const line of text.split("\n")) { + const header = /^\s*(\[\[?[^\]]+\]\]?)\s*(?:#.*)?$/.exec(line); + if (header === null) continue; + const raw = header[1]; + if (raw === undefined) continue; + const inner = raw.replace(/^\[\[?/, "").replace(/\]\]?$/, "").trim(); + // `hooks` spans more than the stage tables bili writes: Codex keeps its + // OWN trust ledger at `[hooks.state.':::']`, written + // as a single-bracket table (it holds key/value pairs, so a table is the + // correct shape and must never be flagged). Matching a bare `hooks` + // prefix treated Codex's own output as a malformed stage table and + // rejected the whole config, which silently skipped the hook face + // whenever a hook had ever been trusted. Only what bili writes is + // inspected: the stage table, plus the flat `[[hooks]]` misuse. + if (inner !== CODEX_HOOKS_TABLE && inner !== "hooks") continue; + // `[[hooks]]` with `event = "..."` is the flat-sequence shape Codex + // rejects with `expected struct HooksToml`: a bare `hooks` array cannot + // hold stage tables keyed by name. + if (inner === "hooks") + return "`[[hooks]]` is not a hook stage — use `[[hooks.SessionStart]]` (Codex expects a struct HooksToml keyed by stage name)"; + if (raw.startsWith("[[")) continue; + return `${raw.trim()} must be [[${inner}]] (Codex reads 'hooks' as a sequence, not a table)`; + } + // A top-level `hooks = ...` assignment would also collapse the sequence. + for (const line of text.split("\n")) { + if (/^\s*\[/.test(line)) break; + if (/^\s*hooks\s*=/.test(line)) + return "a top-level `hooks = ...` key must not be set (Codex reads 'hooks' as a sequence of stage tables)"; + } + for (const region of tableRegions(text, CODEX_HOOKS_TABLE)) { + const commands = readCodexHookCommands(region); + if (commands.length === 0) + return `a ${CODEX_HOOKS_TABLE} entry carries no command`; + if (commands.some((command) => command.trim() === "")) + return `a ${CODEX_HOOKS_TABLE} entry carries an empty command`; + // The MatcherGroup shape: handler fields belong INSIDE `hooks = [...]`. + // Without this the entry loads and is silently ignored. + // + // Scoped to OUR entry on purpose. A foreign entry with the wrong shape is + // its owner's bug, and refusing to write bili's own correct entry because + // of it would strand exactly the users who already run another hook tool. + if ( + commands.some(isBiliCodexHookCommand) && + !isNestedHookRegion(region) + ) + return `a ${CODEX_HOOKS_TABLE} entry must nest its handler in a 'hooks = [{ type = "command", ... }]' array (fields set directly on the entry are dropped by Codex, which registers nothing)`; + } + return undefined; } diff --git a/src/codex-integration/skill.ts b/src/codex-integration/skill.ts index 765f131125..dd8e805071 100644 --- a/src/codex-integration/skill.ts +++ b/src/codex-integration/skill.ts @@ -26,7 +26,7 @@ export const CODEX_SKILL_NAME = "bili"; * another tool) and is never written or deleted — the same content-based rule * the model route and the hook face use. The name alone is not proof. */ export const CODEX_SKILL_MARKER = - ""; + ""; /** The skill document bili installs. Kept as a constant so `codexSkillStatus` * and the installer cannot drift apart. */ @@ -73,23 +73,23 @@ tools below ride along on the \`bili\` MCP server. /** `/skills/bili`. */ export function codexSkillDir(env: NodeJS.ProcessEnv = process.env): string { - return path.join(resolveCodexHome(env), "skills", CODEX_SKILL_NAME); + return path.join(resolveCodexHome(env), "skills", CODEX_SKILL_NAME); } /** `/skills/bili/SKILL.md`. */ export function codexSkillFile(env: NodeJS.ProcessEnv = process.env): string { - return path.join(codexSkillDir(env), "SKILL.md"); + return path.join(codexSkillDir(env), "SKILL.md"); } /** The frontmatter name a skill file declares, when parseable. */ export function readSkillName(text: string): string | undefined { - const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(text); - const body = frontmatter?.[1]; - if (body === undefined) return undefined; - const match = /^name:\s*(.+?)\s*$/m.exec(body); - const name = match?.[1]; - if (name === undefined) return undefined; - return name.replace(/^["']|["']$/g, ""); + const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(text); + const body = frontmatter?.[1]; + if (body === undefined) return undefined; + const match = /^name:\s*(.+?)\s*$/m.exec(body); + const name = match?.[1]; + if (name === undefined) return undefined; + return name.replace(/^["']|["']$/g, ""); } export type CodexSkillState = "installed" | "missing" | "outdated" | "foreign"; @@ -98,72 +98,72 @@ export type CodexSkillState = "installed" | "missing" | "outdated" | "foreign"; * bytes differ (an upgrade is due, or the user edited a bili-managed file); * `foreign` means a same-named skill bili does not own. */ export function codexSkillStatus( - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = process.env, ): CodexSkillState { - let text: string; - try { - text = fs.readFileSync(codexSkillFile(env), "utf8"); - } catch { - return "missing"; - } - if (text === CODEX_SKILL_MARKDOWN) return "installed"; - return text.includes(CODEX_SKILL_MARKER) ? "outdated" : "foreign"; + let text: string; + try { + text = fs.readFileSync(codexSkillFile(env), "utf8"); + } catch { + return "missing"; + } + if (text === CODEX_SKILL_MARKDOWN) return "installed"; + return text.includes(CODEX_SKILL_MARKER) ? "outdated" : "foreign"; } export interface CodexSkillInstall { - state: CodexSkillState | "written"; - note: string; - written: boolean; + state: CodexSkillState | "written"; + note: string; + written: boolean; } /** Install or refresh the skill. A file bili does not own is left alone. */ export function installCodexSkill( - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = process.env, ): CodexSkillInstall { - const file = codexSkillFile(env); - const state = codexSkillStatus(env); - if (state === "installed") - return { - state, - note: "ACP skill already installed", - written: false, - }; - if (state === "foreign") - return { - state, - note: `${file} exists but is not a bili skill — left untouched`, - written: false, - }; - fs.mkdirSync(codexSkillDir(env), { recursive: true }); - fs.writeFileSync(file, CODEX_SKILL_MARKDOWN, { mode: 0o644 }); - return { - state: "written", - note: - state === "missing" - ? `ACP skill installed -> ${file}` - : `ACP skill refreshed -> ${file}`, - written: true, - }; + const file = codexSkillFile(env); + const state = codexSkillStatus(env); + if (state === "installed") + return { + state, + note: "ACP skill already installed", + written: false, + }; + if (state === "foreign") + return { + state, + note: `${file} exists but is not a bili skill — left untouched`, + written: false, + }; + fs.mkdirSync(codexSkillDir(env), { recursive: true }); + fs.writeFileSync(file, CODEX_SKILL_MARKDOWN, { mode: 0o644 }); + return { + state: "written", + note: + state === "missing" + ? `ACP skill installed -> ${file}` + : `ACP skill refreshed -> ${file}`, + written: true, + }; } /** Remove the skill file only when it is ours; drops the directory when empty. */ export function removeCodexSkill(env: NodeJS.ProcessEnv = process.env): { - removed: boolean; - note: string; + removed: boolean; + note: string; } { - const state = codexSkillStatus(env); - if (state === "missing") - return { removed: false, note: "ACP skill not installed" }; - if (state === "foreign") - return { - removed: false, - note: "ACP skill directory is not owned by bili — left untouched", - }; - fs.unlinkSync(codexSkillFile(env)); - try { - fs.rmdirSync(codexSkillDir(env)); - } catch { - // A user may keep notes next to the skill; a non-empty dir stays. - } - return { removed: true, note: "ACP skill removed" }; + const state = codexSkillStatus(env); + if (state === "missing") + return { removed: false, note: "ACP skill not installed" }; + if (state === "foreign") + return { + removed: false, + note: "ACP skill directory is not owned by bili — left untouched", + }; + fs.unlinkSync(codexSkillFile(env)); + try { + fs.rmdirSync(codexSkillDir(env)); + } catch { + // A user may keep notes next to the skill; a non-empty dir stays. + } + return { removed: true, note: "ACP skill removed" }; } diff --git a/src/codex-integration/status.ts b/src/codex-integration/status.ts index e638474d86..c7c47897d3 100644 --- a/src/codex-integration/status.ts +++ b/src/codex-integration/status.ts @@ -6,25 +6,25 @@ import fs from "node:fs"; import path from "node:path"; export type CodexIntegrationState = - | "proxy-ready" - | "configured" - | "verified" - | "bypassed" - | "unknown"; + | "proxy-ready" + | "configured" + | "verified" + | "bypassed" + | "unknown"; export interface CodexIntegrationReport { - state: CodexIntegrationState; - route: "owned" | "foreign" | "absent"; - proxyHealthy: boolean; - observedCodexRequest: boolean; - detail: string; + state: CodexIntegrationState; + route: "owned" | "foreign" | "absent"; + proxyHealthy: boolean; + observedCodexRequest: boolean; + detail: string; } export interface CodexStatusDeps { - env?: NodeJS.ProcessEnv; - fetchImpl?: typeof fetch; - codexConfigText?: string; - origin?: string; + env?: NodeJS.ProcessEnv; + fetchImpl?: typeof fetch; + codexConfigText?: string; + origin?: string; } /** How long a real Codex request keeps counting as evidence. Long enough that a @@ -36,10 +36,10 @@ const CODEX_EVIDENCE_MAX_AGE_MS = 24 * 60 * 60_000; * one of these proves the forwarding path works, never that a USER's Codex is * routed — those fixtures are why this module needs any exclusion at all. */ function isLoopbackUpstream(value: unknown): boolean { - if (typeof value !== "string") return false; - return /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:[/]|$)/i.test( - value.trim(), - ); + if (typeof value !== "string") return false; + return /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:[/]|$)/i.test( + value.trim(), + ); } /** A session that only the native Codex CLI can have created. Two independent @@ -52,156 +52,156 @@ function isLoopbackUpstream(value: unknown): boolean { * A hint naming a DIFFERENT client vetoes the session, so a foreign Responses * client can never be read as Codex evidence. */ function isCodexSession(row: Record): boolean { - const hint = row.clientHint; - if (typeof hint === "string" && hint.length > 0) { - if (!hint.toLowerCase().includes("codex")) return false; - return true; - } - return row.codexClient === true || row.protocol === "responses"; + const hint = row.clientHint; + if (typeof hint === "string" && hint.length > 0) { + if (!hint.toLowerCase().includes("codex")) return false; + return true; + } + return row.codexClient === true || row.protocol === "responses"; } function configText(env: NodeJS.ProcessEnv): string { - try { - return fs.readFileSync( - path.join(resolveCodexHome(env), "config.toml"), - "utf8", - ); - } catch { - return ""; - } + try { + return fs.readFileSync( + path.join(resolveCodexHome(env), "config.toml"), + "utf8", + ); + } catch { + return ""; + } } /** One session row's worth of evidence: a real, recent, non-fixture Codex * request. Kept separate from `isCodexSession` so the shape predicates and the * freshness policy can be read (and tested) independently. */ function isCodexEvidence(row: Record, now: number): boolean { - if (!isCodexSession(row)) return false; - if (isLoopbackUpstream(row.upstream)) return false; - if (typeof row.requests !== "number" || row.requests <= 0) return false; - const lastSeenMs = row.lastSeenMs; - const lastSeen = row.lastSeen; - const seenAt = - typeof lastSeenMs === "number" - ? lastSeenMs - : typeof lastSeen === "string" - ? Date.parse(lastSeen) - : Number.NaN; - const age = now - seenAt; - return age >= 0 && age <= CODEX_EVIDENCE_MAX_AGE_MS; + if (!isCodexSession(row)) return false; + if (isLoopbackUpstream(row.upstream)) return false; + if (typeof row.requests !== "number" || row.requests <= 0) return false; + const lastSeenMs = row.lastSeenMs; + const lastSeen = row.lastSeen; + const seenAt = + typeof lastSeenMs === "number" + ? lastSeenMs + : typeof lastSeen === "string" + ? Date.parse(lastSeen) + : Number.NaN; + const age = now - seenAt; + return age >= 0 && age <= CODEX_EVIDENCE_MAX_AGE_MS; } interface ProxyFacts { - proxyHealthy: boolean; - observedCodexRequest: boolean; + proxyHealthy: boolean; + observedCodexRequest: boolean; } /** Read-only probe of the stable Codex lane origin. Every failure — refused * connection, timeout, malformed payload — reads as "no evidence", never as * negative proof about the user's setup. */ async function probeProxy( - origin: string, - fetchImpl: typeof fetch, + origin: string, + fetchImpl: typeof fetch, ): Promise { - const absent: ProxyFacts = { - proxyHealthy: false, - observedCodexRequest: false, - }; - try { - const response = await fetchImpl(`${origin}/__bili/health`, { - signal: AbortSignal.timeout(1200), - }); - if (!response.ok) return absent; - const health: unknown = await response.json(); - const healthy = - health !== null && - typeof health === "object" && - (health as Record).ok === true; - if (!healthy) return absent; - const stats = await fetchImpl(`${origin}/__bili/stats`, { - signal: AbortSignal.timeout(1600), - }); - if (!stats.ok) return { proxyHealthy: true, observedCodexRequest: false }; - const data: unknown = await stats.json(); - const sessions = - data !== null && typeof data === "object" - ? (data as Record).sessions - : undefined; - if (!Array.isArray(sessions)) - return { proxyHealthy: true, observedCodexRequest: false }; - const now = Date.now(); - return { - proxyHealthy: true, - observedCodexRequest: sessions.some( - (entry) => - entry !== null && - typeof entry === "object" && - isCodexEvidence(entry as Record, now), - ), - }; - } catch { - return absent; - } + const absent: ProxyFacts = { + proxyHealthy: false, + observedCodexRequest: false, + }; + try { + const response = await fetchImpl(`${origin}/__bili/health`, { + signal: AbortSignal.timeout(1200), + }); + if (!response.ok) return absent; + const health: unknown = await response.json(); + const healthy = + health !== null && + typeof health === "object" && + (health as Record).ok === true; + if (!healthy) return absent; + const stats = await fetchImpl(`${origin}/__bili/stats`, { + signal: AbortSignal.timeout(1600), + }); + if (!stats.ok) return { proxyHealthy: true, observedCodexRequest: false }; + const data: unknown = await stats.json(); + const sessions = + data !== null && typeof data === "object" + ? (data as Record).sessions + : undefined; + if (!Array.isArray(sessions)) + return { proxyHealthy: true, observedCodexRequest: false }; + const now = Date.now(); + return { + proxyHealthy: true, + observedCodexRequest: sessions.some( + (entry) => + entry !== null && + typeof entry === "object" && + isCodexEvidence(entry as Record, now), + ), + }; + } catch { + return absent; + } } export async function inspectCodexIntegration( - deps: CodexStatusDeps = {}, + deps: CodexStatusDeps = {}, ): Promise { - const env = deps.env ?? process.env; - const text = deps.codexConfigText ?? configText(env); - const file = path.join(resolveCodexHome(env), "config.toml"); - const route = readCodexRoute( - text, - readCodexRouteRecord(codexRouteRecordPath(file)), - ); - const origin = ( - deps.origin ?? `http://127.0.0.1:${lanePreferredPort("codex", env)}` - ).replace(/\/+$/, ""); - const { proxyHealthy, observedCodexRequest } = await probeProxy( - origin, - deps.fetchImpl ?? fetch, - ); - const report = ( - state: CodexIntegrationState, - detail: string, - routeOverride?: "owned" | "foreign" | "absent", - ): CodexIntegrationReport => ({ - state, - route: - routeOverride ?? - (route.routed ? "owned" : route.conflict ? "foreign" : "absent"), - proxyHealthy, - observedCodexRequest, - detail, - }); - if (observedCodexRequest) - return report("verified", "bili observed a real Codex model request"); - if (route.conflict !== undefined) - return report( - "bypassed", - route.conflict.kind === "shadowed-by-provider" - ? `Codex provider ${route.conflict.provider} owns the effective base_url` - : "openai_base_url is not owned by bili; left untouched", - "foreign", - ); - if (route.routed) - return report( - "configured", - proxyHealthy - ? "bili route is configured; no Codex model request observed yet" - : "bili route is configured; proxy health has not been confirmed", - "owned", - ); - if (proxyHealthy) - return report( - "proxy-ready", - "proxy is healthy; Codex model route is not configured", - "absent", - ); - return report( - "unknown", - text.length === 0 - ? "Codex config is unavailable and no proxy health evidence is available" - : "no route ownership or live proxy evidence is available", - "absent", - ); + const env = deps.env ?? process.env; + const text = deps.codexConfigText ?? configText(env); + const file = path.join(resolveCodexHome(env), "config.toml"); + const route = readCodexRoute( + text, + readCodexRouteRecord(codexRouteRecordPath(file)), + ); + const origin = ( + deps.origin ?? `http://127.0.0.1:${lanePreferredPort("codex", env)}` + ).replace(/\/+$/, ""); + const { proxyHealthy, observedCodexRequest } = await probeProxy( + origin, + deps.fetchImpl ?? fetch, + ); + const report = ( + state: CodexIntegrationState, + detail: string, + routeOverride?: "owned" | "foreign" | "absent", + ): CodexIntegrationReport => ({ + state, + route: + routeOverride ?? + (route.routed ? "owned" : route.conflict ? "foreign" : "absent"), + proxyHealthy, + observedCodexRequest, + detail, + }); + if (observedCodexRequest) + return report("verified", "bili observed a real Codex model request"); + if (route.conflict !== undefined) + return report( + "bypassed", + route.conflict.kind === "shadowed-by-provider" + ? `Codex provider ${route.conflict.provider} owns the effective base_url` + : "openai_base_url is not owned by bili; left untouched", + "foreign", + ); + if (route.routed) + return report( + "configured", + proxyHealthy + ? "bili route is configured; no Codex model request observed yet" + : "bili route is configured; proxy health has not been confirmed", + "owned", + ); + if (proxyHealthy) + return report( + "proxy-ready", + "proxy is healthy; Codex model route is not configured", + "absent", + ); + return report( + "unknown", + text.length === 0 + ? "Codex config is unavailable and no proxy health evidence is available" + : "no route ownership or live proxy evidence is available", + "absent", + ); } diff --git a/src/codex-integration/toml-field.ts b/src/codex-integration/toml-field.ts index c8cc9e0d70..465df9fd10 100644 --- a/src/codex-integration/toml-field.ts +++ b/src/codex-integration/toml-field.ts @@ -8,191 +8,191 @@ /** A located top-level scalar. `line` is a 0-based index into `text.split("\n")`. */ export interface TopLevelScalar { - key: string; - value: string; - line: number; + key: string; + value: string; + line: number; } /** TOML basic (double-quoted) and literal (single-quoted) string bodies. A * line whose value is an array/inline-table/multiline string is NOT a scalar * we can own — it is reported as not-found rather than mis-parsed. */ const SCALAR_RE = - /^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')\s*(?:#.*)?$/; + /^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')\s*(?:#.*)?$/; function decode(raw: string, quoted: "basic" | "literal"): string { - if (quoted === "literal") return raw; - try { - const parsed: unknown = JSON.parse(`"${raw}"`); - return typeof parsed === "string" ? parsed : raw; - } catch { - return raw; - } + if (quoted === "literal") return raw; + try { + const parsed: unknown = JSON.parse(`"${raw}"`); + return typeof parsed === "string" ? parsed : raw; + } catch { + return raw; + } } function preserveInlineComment(original: string, rendered: string): string { - let quote: "basic" | "literal" | undefined; - let escaped = false; - for (let i = 0; i < original.length; i++) { - const char = original[i]!; - if (quote === "basic") { - if (escaped) escaped = false; - else if (char === "\\") escaped = true; - else if (char === '"') quote = undefined; - } else if (quote === "literal") { - if (char === "'") quote = undefined; - } else if (char === '"') quote = "basic"; - else if (char === "'") quote = "literal"; - else if (char === "#") return `${rendered} ${original.slice(i).trimEnd()}`; - } - return rendered; + let quote: "basic" | "literal" | undefined; + let escaped = false; + for (let i = 0; i < original.length; i++) { + const char = original[i]!; + if (quote === "basic") { + if (escaped) escaped = false; + else if (char === "\\") escaped = true; + else if (char === '"') quote = undefined; + } else if (quote === "literal") { + if (char === "'") quote = undefined; + } else if (char === '"') quote = "basic"; + else if (char === "'") quote = "literal"; + else if (char === "#") return `${rendered} ${original.slice(i).trimEnd()}`; + } + return rendered; } /** Locate a top-level scalar, stopping at the first table header: a key after * `[some.table]` belongs to that table, not to the file root. */ export function findTopLevelScalar( - text: string, - key: string, + text: string, + key: string, ): TopLevelScalar | undefined { - const lines = text.split("\n"); - for (let i = 0; i < lines.length; i++) { - const line = lines[i]!.trim(); - if (line.startsWith("[")) return undefined; - if (line === "" || line.startsWith("#")) continue; - const m = SCALAR_RE.exec(line); - if (m === null || m[1] !== key) continue; - return { - key, - value: - m[2] !== undefined ? decode(m[2], "basic") : decode(m[3]!, "literal"), - line: i, - }; - } - return undefined; + const lines = text.split("\n"); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!.trim(); + if (line.startsWith("[")) return undefined; + if (line === "" || line.startsWith("#")) continue; + const m = SCALAR_RE.exec(line); + if (m === null || m[1] !== key) continue; + return { + key, + value: + m[2] !== undefined ? decode(m[2], "basic") : decode(m[3]!, "literal"), + line: i, + }; + } + return undefined; } /** Set (or insert) a top-level scalar. JSON.stringify emits a valid TOML basic * string — both grammars escape `\` and `"` identically — which is the same * serialization plugin-install.ts `codexBlock` relies on. */ export function setTopLevelScalar( - text: string, - key: string, - value: string, + text: string, + key: string, + value: string, ): string { - const rendered = `${key} = ${JSON.stringify(value)}`; - const lines = text.split("\n"); - const existing = findTopLevelScalar(text, key); - if (existing !== undefined) { - lines[existing.line] = preserveInlineComment( - lines[existing.line]!, - rendered, - ); - return lines.join("\n"); - } - // Insert after the last top-level key; with none, at the very top so the - // key can never land inside a nested table. - let at = 0; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]!.trim(); - if (line.startsWith("[")) break; - if (line === "" || line.startsWith("#")) continue; - at = i + 1; - } - lines.splice(at, 0, rendered); - return lines.join("\n"); + const rendered = `${key} = ${JSON.stringify(value)}`; + const lines = text.split("\n"); + const existing = findTopLevelScalar(text, key); + if (existing !== undefined) { + lines[existing.line] = preserveInlineComment( + lines[existing.line]!, + rendered, + ); + return lines.join("\n"); + } + // Insert after the last top-level key; with none, at the very top so the + // key can never land inside a nested table. + let at = 0; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!.trim(); + if (line.startsWith("[")) break; + if (line === "" || line.startsWith("#")) continue; + at = i + 1; + } + lines.splice(at, 0, rendered); + return lines.join("\n"); } /** Delete a top-level scalar line. Only that line goes; surrounding comments * and blank lines are left exactly as the user had them. */ export function removeTopLevelScalar(text: string, key: string): string { - const existing = findTopLevelScalar(text, key); - if (existing === undefined) return text; - const lines = text.split("\n"); - lines.splice(existing.line, 1); - return lines.join("\n"); + const existing = findTopLevelScalar(text, key); + if (existing === undefined) return text; + const lines = text.split("\n"); + lines.splice(existing.line, 1); + return lines.join("\n"); } /** A located scalar inside an exact TOML table. */ export interface TableScalar extends TopLevelScalar { - table: string; + table: string; } export function findTableScalar( - text: string, - table: string, - key: string, + text: string, + table: string, + key: string, ): TableScalar | undefined { - const lines = text.split("\n"); - let active = false; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]!.trim(); - const header = /^\[([^\]]+)\]\s*(?:#.*)?$/.exec(line); - if (header) { - if (active) return undefined; - active = header[1]!.trim() === table; - continue; - } - if (!active || line === "" || line.startsWith("#")) continue; - const match = SCALAR_RE.exec(line); - if (!match || match[1] !== key) continue; - return { - table, - key, - value: - match[2] !== undefined - ? decode(match[2], "basic") - : decode(match[3]!, "literal"), - line: i, - }; - } - return undefined; + const lines = text.split("\n"); + let active = false; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!.trim(); + const header = /^\[([^\]]+)\]\s*(?:#.*)?$/.exec(line); + if (header) { + if (active) return undefined; + active = header[1]!.trim() === table; + continue; + } + if (!active || line === "" || line.startsWith("#")) continue; + const match = SCALAR_RE.exec(line); + if (!match || match[1] !== key) continue; + return { + table, + key, + value: + match[2] !== undefined + ? decode(match[2], "basic") + : decode(match[3]!, "literal"), + line: i, + }; + } + return undefined; } export function setTableScalar( - text: string, - table: string, - key: string, - value: string, + text: string, + table: string, + key: string, + value: string, ): string { - const lines = text.split("\n"); - const rendered = `${key} = ${JSON.stringify(value)}`; - const existing = findTableScalar(text, table, key); - if (existing) { - lines[existing.line] = preserveInlineComment( - lines[existing.line]!, - rendered, - ); - return lines.join("\n"); - } - let tableLine = -1; - let tableEnd = lines.length; - for (let i = 0; i < lines.length; i++) { - const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); - if (!header) continue; - if (tableLine >= 0) { - tableEnd = i; - break; - } - if (header[1]!.trim() === table) tableLine = i; - } - if (tableLine < 0) { - const prefix = - text.length === 0 || text.endsWith("\n") ? text : `${text}\n`; - return `${prefix}\n[${table}]\n${rendered}\n`; - } - lines.splice(tableEnd, 0, rendered); - return lines.join("\n"); + const lines = text.split("\n"); + const rendered = `${key} = ${JSON.stringify(value)}`; + const existing = findTableScalar(text, table, key); + if (existing) { + lines[existing.line] = preserveInlineComment( + lines[existing.line]!, + rendered, + ); + return lines.join("\n"); + } + let tableLine = -1; + let tableEnd = lines.length; + for (let i = 0; i < lines.length; i++) { + const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); + if (!header) continue; + if (tableLine >= 0) { + tableEnd = i; + break; + } + if (header[1]!.trim() === table) tableLine = i; + } + if (tableLine < 0) { + const prefix = + text.length === 0 || text.endsWith("\n") ? text : `${text}\n`; + return `${prefix}\n[${table}]\n${rendered}\n`; + } + lines.splice(tableEnd, 0, rendered); + return lines.join("\n"); } export function removeTableScalar( - text: string, - table: string, - key: string, + text: string, + table: string, + key: string, ): string { - const existing = findTableScalar(text, table, key); - if (!existing) return text; - const lines = text.split("\n"); - lines.splice(existing.line, 1); - return lines.join("\n"); + const existing = findTableScalar(text, table, key); + if (!existing) return text; + const lines = text.split("\n"); + lines.splice(existing.line, 1); + return lines.join("\n"); } /** Insert a raw (already rendered) line inside an exact table, after its last @@ -201,63 +201,63 @@ export function removeTableScalar( * and for array-of-inline-table hook entries. Existing content is untouched; * when the key is already present the caller decides (replace vs. refuse). */ export function insertTableRaw( - text: string, - table: string, - rendered: string, + text: string, + table: string, + rendered: string, ): string { - const lines = text.split("\n"); - let tableLine = -1; - let tableEnd = lines.length; - for (let i = 0; i < lines.length; i++) { - const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); - if (!header) continue; - if (tableLine >= 0) { - tableEnd = i; - break; - } - if (header[1]!.trim() === table) tableLine = i; - } - if (tableLine < 0) { - const prefix = - text.length === 0 || text.endsWith("\n") ? text : `${text}\n`; - return `${prefix}\n[${table}]\n${rendered}\n`; - } - // Land before trailing blank/comment lines so the new scalar stays inside - // the table's own block instead of after a user's separator comment. - let at = tableEnd; - while (at > tableLine + 1) { - const line = lines[at - 1]!.trim(); - if (line !== "" && !line.startsWith("#")) break; - at--; - } - lines.splice(at, 0, rendered); - return lines.join("\n"); + const lines = text.split("\n"); + let tableLine = -1; + let tableEnd = lines.length; + for (let i = 0; i < lines.length; i++) { + const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); + if (!header) continue; + if (tableLine >= 0) { + tableEnd = i; + break; + } + if (header[1]!.trim() === table) tableLine = i; + } + if (tableLine < 0) { + const prefix = + text.length === 0 || text.endsWith("\n") ? text : `${text}\n`; + return `${prefix}\n[${table}]\n${rendered}\n`; + } + // Land before trailing blank/comment lines so the new scalar stays inside + // the table's own block instead of after a user's separator comment. + let at = tableEnd; + while (at > tableLine + 1) { + const line = lines[at - 1]!.trim(); + if (line !== "" && !line.startsWith("#")) break; + at--; + } + lines.splice(at, 0, rendered); + return lines.join("\n"); } /** Replace an entire table header line and its scalars with `rendered` (which * must itself include the `[table]` header). Used for hook tables bili owns * end-to-end; a table with foreign structure is reported, never clobbered. */ export function replaceTable( - text: string, - table: string, - rendered: string, + text: string, + table: string, + rendered: string, ): string { - const lines = text.split("\n"); - let start = -1; - let end = lines.length; - for (let i = 0; i < lines.length; i++) { - const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); - if (!header) continue; - if (start >= 0) { - end = i; - break; - } - if (header[1]!.trim() === table) start = i; - } - if (start < 0) return text; - const block = rendered.replace(/\n+$/, "").split("\n"); - lines.splice(start, end - start, ...block); - return lines.join("\n"); + const lines = text.split("\n"); + let start = -1; + let end = lines.length; + for (let i = 0; i < lines.length; i++) { + const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); + if (!header) continue; + if (start >= 0) { + end = i; + break; + } + if (header[1]!.trim() === table) start = i; + } + if (start < 0) return text; + const block = rendered.replace(/\n+$/, "").split("\n"); + lines.splice(start, end - start, ...block); + return lines.join("\n"); } /** Every region of `text` covered by an exact `[table]` or `[[table]]` header @@ -269,20 +269,20 @@ export function replaceTable( * and a caller that rewrote or dropped the region while leaving `[hooks...]` * behind would silently corrupt the array into a map. */ export function tableRegions(text: string, table: string): string[] { - const lines = text.split("\n"); - const out: string[] = []; - let current: string[] | undefined; - for (const line of lines) { - const header = /^\s*(\[\[?[^\]]+\]\]?)\s*(?:#.*)?$/.exec(line); - if (header) { - if (current !== undefined) out.push(current.join("\n")); - const raw = header[1]; - const inner = raw?.replace(/^\[\[?/, "").replace(/\]\]?$/, "").trim(); - current = inner === table ? [line] : undefined; - continue; - } - if (current !== undefined) current.push(line); - } - if (current !== undefined) out.push(current.join("\n")); - return out.filter((region) => region.trim().startsWith("[")); + const lines = text.split("\n"); + const out: string[] = []; + let current: string[] | undefined; + for (const line of lines) { + const header = /^\s*(\[\[?[^\]]+\]\]?)\s*(?:#.*)?$/.exec(line); + if (header) { + if (current !== undefined) out.push(current.join("\n")); + const raw = header[1]; + const inner = raw?.replace(/^\[\[?/, "").replace(/\]\]?$/, "").trim(); + current = inner === table ? [line] : undefined; + continue; + } + if (current !== undefined) current.push(line); + } + if (current !== undefined) out.push(current.join("\n")); + return out.filter((region) => region.trim().startsWith("[")); } diff --git a/src/codex/bootstrap-hook.ts b/src/codex/bootstrap-hook.ts index 699905b50e..5429fe35bd 100644 --- a/src/codex/bootstrap-hook.ts +++ b/src/codex/bootstrap-hook.ts @@ -15,84 +15,84 @@ import { codexRouteOrigin } from "../codex-integration/route.js"; const HOOK_HEALTH_DEADLINE_MS = 4000; function readStdinPayload(timeoutMs = 5000): Promise> { - return new Promise((resolve) => { - let buf = ""; - let done = false; - const finish = () => { - if (done) return; - done = true; - clearTimeout(timer); - process.stdin.removeAllListeners(); - try { - resolve(JSON.parse(buf) as Record); - } catch { - resolve({}); - } - }; - const timer = setTimeout(finish, timeoutMs); - process.stdin.setEncoding("utf8"); - process.stdin.on("data", (chunk) => { - buf += chunk; - }); - process.stdin.on("end", finish); - }); + return new Promise((resolve) => { + let buf = ""; + let done = false; + const finish = () => { + if (done) return; + done = true; + clearTimeout(timer); + process.stdin.removeAllListeners(); + try { + resolve(JSON.parse(buf) as Record); + } catch { + resolve({}); + } + }; + const timer = setTimeout(finish, timeoutMs); + process.stdin.setEncoding("utf8"); + process.stdin.on("data", (chunk) => { + buf += chunk; + }); + process.stdin.on("end", finish); + }); } /** Any bili process listening on the Codex lane's sticky port. Attach-only: * BILI_CODEX_HOOK_ORIGIN overrides the probe target for tests/odd setups. */ export async function waitForProxyHealthy( - origin: string, - deadlineMs: number, - fetchImpl: typeof fetch = fetch, + origin: string, + deadlineMs: number, + fetchImpl: typeof fetch = fetch, ): Promise { - const deadline = Date.now() + deadlineMs; - for (;;) { - try { - const response = await fetchImpl( - `${origin.replace(/\/+$/, "")}/__bili/health`, - { - signal: AbortSignal.timeout(1200), - }, - ); - if (response.ok) return true; - } catch { - // not up yet (or not ours) - } - if (Date.now() >= deadline) return false; - await new Promise((resolve) => setTimeout(resolve, 250)); - } + const deadline = Date.now() + deadlineMs; + for (;;) { + try { + const response = await fetchImpl( + `${origin.replace(/\/+$/, "")}/__bili/health`, + { + signal: AbortSignal.timeout(1200), + }, + ); + if (response.ok) return true; + } catch { + // not up yet (or not ours) + } + if (Date.now() >= deadline) return false; + await new Promise((resolve) => setTimeout(resolve, 250)); + } } export async function main(): Promise { - if (process.env.NODE_TEST_CONTEXT !== undefined) return; - try { - const payload = await readStdinPayload(); - const origin = - process.env.BILI_CODEX_HOOK_ORIGIN ?? - codexRouteOrigin(process.env) ?? - resolveProxyOrigin(); - if (!(await waitForProxyHealthy(origin, HOOK_HEALTH_DEADLINE_MS))) return; - const model = - typeof payload.model === "string" && payload.model.length > 0 - ? payload.model - : "codex"; - await reportRuntimeInfo(origin, { - agent: "codex", - model, - source: "session-start-hook", - ...(typeof payload.session_id === "string" && - payload.session_id.length > 0 - ? { conversationId: payload.session_id } - : {}), - }); - } catch { - return; - } + if (process.env.NODE_TEST_CONTEXT !== undefined) return; + try { + const payload = await readStdinPayload(); + const origin = + process.env.BILI_CODEX_HOOK_ORIGIN ?? + codexRouteOrigin(process.env) ?? + resolveProxyOrigin(); + if (!(await waitForProxyHealthy(origin, HOOK_HEALTH_DEADLINE_MS))) return; + const model = + typeof payload.model === "string" && payload.model.length > 0 + ? payload.model + : "codex"; + await reportRuntimeInfo(origin, { + agent: "codex", + model, + source: "session-start-hook", + ...(typeof payload.session_id === "string" && + payload.session_id.length > 0 + ? { conversationId: payload.session_id } + : {}), + }); + } catch { + return; + } } if ( - process.argv[1] && - /(?:^|[\\/])bootstrap-hook\.(?:ts|js)$/.test(process.argv[1]) + process.argv[1] && + /(?:^|[\\/])bootstrap-hook\.(?:ts|js)$/.test(process.argv[1]) ) { - runSessionStartHook(main); + runSessionStartHook(main); } diff --git a/src/doctor.ts b/src/doctor.ts index b4f3f85e33..9032dc0886 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -8,165 +8,165 @@ import fs from "node:fs"; import path from "node:path"; import { isPidAlive, listInstances, procMainScript } from "./instance.js"; import { - PLUGIN_AGENTS, - UPDATE_CHANNEL, - claudeDesktopPresent, - inspectLanePresence, - type PluginAgent, + PLUGIN_AGENTS, + UPDATE_CHANNEL, + claudeDesktopPresent, + inspectLanePresence, + type PluginAgent, } from "./plugin-install.js"; import { - findInstallDir, - fetchRegistryVersion, - hostManagedInstall, - isGitWorkingTree, - isVersionNewer, - lastUpdateCheckTime, - normalizeUpdateTag, - staleInstallStatus, + findInstallDir, + fetchRegistryVersion, + hostManagedInstall, + isGitWorkingTree, + isVersionNewer, + lastUpdateCheckTime, + normalizeUpdateTag, + staleInstallStatus, } from "./update.js"; import { - describeAdvisory, - evaluateAdvisories, - type AdvisoryEvaluation, + describeAdvisory, + evaluateAdvisories, + type AdvisoryEvaluation, } from "./advisory.js"; import { claudeRoutingWarningFile } from "./paths.js"; import { - inspectCodexIntegration, - type CodexIntegrationReport, + inspectCodexIntegration, + type CodexIntegrationReport, } from "./codex-integration/status.js"; import { - detectCcSwitch, - type CcSwitchDetection, + detectCcSwitch, + type CcSwitchDetection, } from "./codex-integration/cc-switch.js"; import { - chatGptDesktopCapability, - type ChatGptDesktopCapability, + chatGptDesktopCapability, + type ChatGptDesktopCapability, } from "./codex-integration/chatgpt-capability.js"; type LaneVerdict = "ok" | "stale" | "frozen" | "broken" | "absent"; interface DoctorGlobalInfo { - installDir?: string; - form: "npm" | "checkout" | "host-managed" | "unknown"; - owner?: string; - channel?: string; - diskVersion?: string; - runningVersion: string; - registryVersion?: string; - updateTag: string; - lastCheckTime?: number; - verdict: LaneVerdict; - reason?: string; - /** Read-only advisory evaluation against the on-disk version (#1577). */ - advisory?: AdvisoryEvaluation; + installDir?: string; + form: "npm" | "checkout" | "host-managed" | "unknown"; + owner?: string; + channel?: string; + diskVersion?: string; + runningVersion: string; + registryVersion?: string; + updateTag: string; + lastCheckTime?: number; + verdict: LaneVerdict; + reason?: string; + /** Read-only advisory evaluation against the on-disk version (#1577). */ + advisory?: AdvisoryEvaluation; } export interface DoctorLane { - agent: string; - kind: "reference" | "host-managed"; - installed: boolean; - detail: string; - targetExists?: boolean; - copyVersion?: string; - registryVersion?: string; - channel?: string; - verdict: LaneVerdict; - reason?: string; - /** Advisory notes that do not affect the verdict — e.g. #2290: the claude - * lane is healthy, but a co-installed Claude Desktop will bypass it. */ - warnings?: string[]; + agent: string; + kind: "reference" | "host-managed"; + installed: boolean; + detail: string; + targetExists?: boolean; + copyVersion?: string; + registryVersion?: string; + channel?: string; + verdict: LaneVerdict; + reason?: string; + /** Advisory notes that do not affect the verdict — e.g. #2290: the claude + * lane is healthy, but a co-installed Claude Desktop will bypass it. */ + warnings?: string[]; } export interface DoctorProcess { - instanceId: string; - pid: number; - port: number; - origin: string; - startedAt: number; - alive: boolean; - runningFrom?: string; - staleCopy?: boolean; + instanceId: string; + pid: number; + port: number; + origin: string; + startedAt: number; + alive: boolean; + runningFrom?: string; + staleCopy?: boolean; } export interface DoctorReport { - generatedAt: number; - packageName: string; - global: DoctorGlobalInfo; - lanes: DoctorLane[]; - processes: DoctorProcess[]; - codexIntegration: CodexIntegrationReport; - ccSwitch: CcSwitchDetection; - chatGptDesktop: ChatGptDesktopCapability; + generatedAt: number; + packageName: string; + global: DoctorGlobalInfo; + lanes: DoctorLane[]; + processes: DoctorProcess[]; + codexIntegration: CodexIntegrationReport; + ccSwitch: CcSwitchDetection; + chatGptDesktop: ChatGptDesktopCapability; } interface DoctorOpts { - packageName: string; - runningVersion: string; - resolveProxy?: (url: string) => string | undefined; - updateTag?: string; - advisoryUrl?: string; + packageName: string; + runningVersion: string; + resolveProxy?: (url: string) => string | undefined; + updateTag?: string; + advisoryUrl?: string; } interface LaneCtx { - packageName: string; - global: DoctorGlobalInfo; + packageName: string; + global: DoctorGlobalInfo; } const REFERENCE_LANES = new Set([ - "omp", - "claude", - "codex", - "kimi", - "zcode", - "hermes", + "omp", + "claude", + "codex", + "kimi", + "zcode", + "hermes", ]); function pkgVersionAt(rootDir: string): string | undefined { - try { - const v = ( - JSON.parse( - fs.readFileSync(path.join(rootDir, "package.json"), "utf8"), - ) as { version?: unknown } - ).version; - return typeof v === "string" ? v : undefined; - } catch { - return undefined; - } + try { + const v = ( + JSON.parse( + fs.readFileSync(path.join(rootDir, "package.json"), "utf8"), + ) as { version?: unknown } + ).version; + return typeof v === "string" ? v : undefined; + } catch { + return undefined; + } } /** Pure verdict logic (#1235): absent < broken < frozen < stale < ok. A * missing target beats a local pin because a dead entry means the host is * currently broken, not merely un-updatable. */ export function laneVerdict(args: { - installed: boolean; - targetMissing: boolean; - frozen: boolean; - copyVersion?: string; - registryVersion?: string; + installed: boolean; + targetMissing: boolean; + frozen: boolean; + copyVersion?: string; + registryVersion?: string; }): LaneVerdict { - if (!args.installed) return "absent"; - if (args.targetMissing) return "broken"; - if (args.frozen) return "frozen"; - if ( - args.copyVersion !== undefined && - args.registryVersion !== undefined && - isVersionNewer(args.registryVersion, args.copyVersion) - ) - return "stale"; - return "ok"; + if (!args.installed) return "absent"; + if (args.targetMissing) return "broken"; + if (args.frozen) return "frozen"; + if ( + args.copyVersion !== undefined && + args.registryVersion !== undefined && + isVersionNewer(args.registryVersion, args.copyVersion) + ) + return "stale"; + return "ok"; } export function globalVerdict( - g: Pick, + g: Pick, ): LaneVerdict { - if (g.form === "checkout") return "frozen"; - if ( - g.diskVersion !== undefined && - g.registryVersion !== undefined && - isVersionNewer(g.registryVersion, g.diskVersion) - ) - return "stale"; - return "ok"; + if (g.form === "checkout") return "frozen"; + if ( + g.diskVersion !== undefined && + g.registryVersion !== undefined && + isVersionNewer(g.registryVersion, g.diskVersion) + ) + return "stale"; + return "ok"; } /** #2891 (#953/#1803): dsh resolves bare bundle names installation-anchor-first, so a @@ -174,403 +174,403 @@ export function globalVerdict( * before. Pure decision (no fs). Returns the warning, or undefined when there is no * profile copy, no global copy, or both versions match (harmless). */ export function dshBundleShadowWarning(args: { - packageName: string; - globalInstallDir?: string; - globalDiskVersion?: string; - profileName: string; - bundleInstalled: boolean; - profileCopyVersion?: string; + packageName: string; + globalInstallDir?: string; + globalDiskVersion?: string; + profileName: string; + bundleInstalled: boolean; + profileCopyVersion?: string; }): string | undefined { - if (!args.bundleInstalled || args.profileCopyVersion === undefined) - return undefined; - if (args.globalInstallDir === undefined) return undefined; - if ( - args.globalDiskVersion !== undefined && - args.globalDiskVersion === args.profileCopyVersion - ) - return undefined; - const gv = - args.globalDiskVersion !== undefined - ? `v${args.globalDiskVersion}` - : "version unreadable"; - return `shadowed copy: a machine-global ${args.packageName} (${args.globalInstallDir}, ${gv}) coexists with this profile's own copy (v${args.profileCopyVersion}); dsh resolves bare bundle names installation-anchor-first (#953/#1803) and loads whichever sits in its own install tree — with divergent versions you may be running a build different from what the profile declares (e.g. a pre-#1590 global lacks the dsh.client web face, so the settings-page menu silently vanishes). Verify which copy dsh actually loads: 'dsh --profile ${args.profileName} --dump-config' (read the bundle 'name:' line)`; + if (!args.bundleInstalled || args.profileCopyVersion === undefined) + return undefined; + if (args.globalInstallDir === undefined) return undefined; + if ( + args.globalDiskVersion !== undefined && + args.globalDiskVersion === args.profileCopyVersion + ) + return undefined; + const gv = + args.globalDiskVersion !== undefined + ? `v${args.globalDiskVersion}` + : "version unreadable"; + return `shadowed copy: a machine-global ${args.packageName} (${args.globalInstallDir}, ${gv}) coexists with this profile's own copy (v${args.profileCopyVersion}); dsh resolves bare bundle names installation-anchor-first (#953/#1803) and loads whichever sits in its own install tree — with divergent versions you may be running a build different from what the profile declares (e.g. a pre-#1590 global lacks the dsh.client web face, so the settings-page menu silently vanishes). Verify which copy dsh actually loads: 'dsh --profile ${args.profileName} --dump-config' (read the bundle 'name:' line)`; } export async function runDoctor(opts: DoctorOpts): Promise { - const tag = normalizeUpdateTag(opts.updateTag); - const [installDir, registryVersion, lastCheck] = await Promise.all([ - findInstallDir(opts.packageName), - fetchRegistryVersion( - { resolveProxy: opts.resolveProxy, updateTag: tag }, - opts.packageName, - ).catch(() => undefined), - lastUpdateCheckTime(), - ]); - const gitTree = - installDir !== undefined ? await isGitWorkingTree(installDir) : false; - const managed = - installDir !== undefined ? hostManagedInstall(installDir) : undefined; - const diskVersion = - installDir !== undefined ? pkgVersionAt(installDir) : undefined; - const form: DoctorGlobalInfo["form"] = - installDir === undefined - ? "unknown" - : gitTree - ? "checkout" - : managed !== undefined - ? "host-managed" - : "npm"; - // #1577: read-only advisory check against the on-disk version (what a next - // start would load), independent of the advisoryCheck opt-out — doctor is a - // diagnostic, not the auto-updater. Fail-open: a failed source yields - // { error }, never a throw. - const advisory = await evaluateAdvisories({ - version: diskVersion ?? opts.runningVersion, - advisoryUrl: opts.advisoryUrl, - resolveProxy: opts.resolveProxy, - }); - const g: DoctorGlobalInfo = { - installDir, - form, - owner: managed?.owner, - channel: managed?.channel, - diskVersion, - runningVersion: opts.runningVersion, - registryVersion, - updateTag: tag, - lastCheckTime: lastCheck, - verdict: globalVerdict({ form, diskVersion, registryVersion }), - advisory, - }; - if (g.verdict === "frozen") - g.reason = - "source checkout — rebuild manually (npm run build); bili refuses to auto-update a working tree (#580)"; - else if (g.verdict === "stale") - g.reason = - managed !== undefined - ? `newer on registry ${tag}: update through ${managed.owner}'s updater` - : `newer on registry ${tag}: run 'bili update'`; - else if ( - form !== "unknown" && - staleInstallStatus(diskVersion, opts.runningVersion) === "restart" - ) - g.reason = `running process is behind the on-disk install (v${opts.runningVersion} → v${diskVersion}) — restart bili`; - if (registryVersion === undefined) - g.reason = g.reason - ? `${g.reason}; registry unreachable — freshness unknown` - : "registry unreachable — freshness unknown"; + const tag = normalizeUpdateTag(opts.updateTag); + const [installDir, registryVersion, lastCheck] = await Promise.all([ + findInstallDir(opts.packageName), + fetchRegistryVersion( + { resolveProxy: opts.resolveProxy, updateTag: tag }, + opts.packageName, + ).catch(() => undefined), + lastUpdateCheckTime(), + ]); + const gitTree = + installDir !== undefined ? await isGitWorkingTree(installDir) : false; + const managed = + installDir !== undefined ? hostManagedInstall(installDir) : undefined; + const diskVersion = + installDir !== undefined ? pkgVersionAt(installDir) : undefined; + const form: DoctorGlobalInfo["form"] = + installDir === undefined + ? "unknown" + : gitTree + ? "checkout" + : managed !== undefined + ? "host-managed" + : "npm"; + // #1577: read-only advisory check against the on-disk version (what a next + // start would load), independent of the advisoryCheck opt-out — doctor is a + // diagnostic, not the auto-updater. Fail-open: a failed source yields + // { error }, never a throw. + const advisory = await evaluateAdvisories({ + version: diskVersion ?? opts.runningVersion, + advisoryUrl: opts.advisoryUrl, + resolveProxy: opts.resolveProxy, + }); + const g: DoctorGlobalInfo = { + installDir, + form, + owner: managed?.owner, + channel: managed?.channel, + diskVersion, + runningVersion: opts.runningVersion, + registryVersion, + updateTag: tag, + lastCheckTime: lastCheck, + verdict: globalVerdict({ form, diskVersion, registryVersion }), + advisory, + }; + if (g.verdict === "frozen") + g.reason = + "source checkout — rebuild manually (npm run build); bili refuses to auto-update a working tree (#580)"; + else if (g.verdict === "stale") + g.reason = + managed !== undefined + ? `newer on registry ${tag}: update through ${managed.owner}'s updater` + : `newer on registry ${tag}: run 'bili update'`; + else if ( + form !== "unknown" && + staleInstallStatus(diskVersion, opts.runningVersion) === "restart" + ) + g.reason = `running process is behind the on-disk install (v${opts.runningVersion} → v${diskVersion}) — restart bili`; + if (registryVersion === undefined) + g.reason = g.reason + ? `${g.reason}; registry unreachable — freshness unknown` + : "registry unreachable — freshness unknown"; - const lanes: DoctorLane[] = []; - for (const agent of PLUGIN_AGENTS) { - try { - lanes.push( - ...laneRowsFor(agent, inspectLanePresence(agent), registryVersion, { - packageName: opts.packageName, - global: g, - }), - ); - } catch (err) { - lanes.push({ - agent, - kind: REFERENCE_LANES.has(agent) ? "reference" : "host-managed", - installed: false, - detail: `probe failed: ${err instanceof Error ? err.message : String(err)}`, - channel: UPDATE_CHANNEL[agent], - verdict: "broken", - }); - } - } + const lanes: DoctorLane[] = []; + for (const agent of PLUGIN_AGENTS) { + try { + lanes.push( + ...laneRowsFor(agent, inspectLanePresence(agent), registryVersion, { + packageName: opts.packageName, + global: g, + }), + ); + } catch (err) { + lanes.push({ + agent, + kind: REFERENCE_LANES.has(agent) ? "reference" : "host-managed", + installed: false, + detail: `probe failed: ${err instanceof Error ? err.message : String(err)}`, + channel: UPDATE_CHANNEL[agent], + verdict: "broken", + }); + } + } - const processes = listInstances().map((e) => { - const alive = isPidAlive(e.pid); - const runningFrom = alive ? procMainScript(e.pid) : undefined; - return { - instanceId: e.instanceId, - pid: e.pid, - port: e.port, - origin: e.origin, - startedAt: e.startedAt, - alive, - runningFrom, - staleCopy: - runningFrom !== undefined && - installDir !== undefined && - !runningFrom.startsWith(installDir + path.sep), - }; - }); + const processes = listInstances().map((e) => { + const alive = isPidAlive(e.pid); + const runningFrom = alive ? procMainScript(e.pid) : undefined; + return { + instanceId: e.instanceId, + pid: e.pid, + port: e.port, + origin: e.origin, + startedAt: e.startedAt, + alive, + runningFrom, + staleCopy: + runningFrom !== undefined && + installDir !== undefined && + !runningFrom.startsWith(installDir + path.sep), + }; + }); - const codexIntegration = await inspectCodexIntegration(); - const ccSwitch = detectCcSwitch(); - return { - generatedAt: Date.now(), - packageName: opts.packageName, - global: g, - lanes, - processes, - codexIntegration, - ccSwitch, - chatGptDesktop: chatGptDesktopCapability, - }; + const codexIntegration = await inspectCodexIntegration(); + const ccSwitch = detectCcSwitch(); + return { + generatedAt: Date.now(), + packageName: opts.packageName, + global: g, + lanes, + processes, + codexIntegration, + ccSwitch, + chatGptDesktop: chatGptDesktopCapability, + }; } function laneRowsFor( - agent: PluginAgent, - presence: ReturnType, - registryVersion: string | undefined, - ctx: LaneCtx, + agent: PluginAgent, + presence: ReturnType, + registryVersion: string | undefined, + ctx: LaneCtx, ): DoctorLane[] { - const kind = REFERENCE_LANES.has(agent) ? "reference" : "host-managed"; - const base: Omit< - DoctorLane, - | "agent" - | "installed" - | "detail" - | "targetExists" - | "copyVersion" - | "verdict" - | "reason" - > = { - kind, - registryVersion, - channel: UPDATE_CHANNEL[agent], - }; - if (agent === "dsh" && presence.profiles !== undefined) { - return presence.profiles.map((p) => { - const missing = p.bundleInstalled && p.copyVersion === undefined; - const row: DoctorLane = { - ...base, - agent: `dsh:${p.name}`, - installed: true, - detail: - p.spec !== undefined - ? `dep spec: ${p.spec}${p.pinned ? " (local pin — dev lane, manual)" : ""}` - : "(no dep spec)", - copyVersion: p.copyVersion, - verdict: laneVerdict({ - installed: true, - targetMissing: missing, - frozen: p.pinned, - copyVersion: p.copyVersion, - registryVersion, - }), - }; - if (row.verdict === "frozen") - row.reason = - "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)"; - else if (row.verdict === "broken") - row.reason = - "profile depends on billion-context but the bundle copy is missing — rerun 'bili plugin install dsh'"; - const shadow = dshBundleShadowWarning({ - packageName: ctx.packageName, - globalInstallDir: ctx.global.installDir, - globalDiskVersion: ctx.global.diskVersion, - profileName: p.name, - bundleInstalled: p.bundleInstalled, - profileCopyVersion: p.copyVersion, - }); - if (shadow !== undefined) - row.warnings = [...(row.warnings ?? []), shadow]; - return row; - }); - } - const targetsExist = - presence.targets.length > 0 - ? presence.targets.every((t) => fs.existsSync(t)) - : undefined; - const missingTargets = presence.targets.filter((t) => !fs.existsSync(t)); - let detail = - presence.pointers.length > 0 - ? presence.pointers.join("; ") - : presence.installed - ? "installed" - : "not installed"; - if ( - agent === "pi" && - presence.form === "npm" && - presence.targets.length === 0 - ) - detail += "; pi materializes the npm copy on next startup"; - const row: DoctorLane = { - ...base, - agent, - installed: presence.installed, - detail, - targetExists: targetsExist, - copyVersion: presence.copyVersion, - verdict: laneVerdict({ - installed: presence.installed, - targetMissing: missingTargets.length > 0, - frozen: false, - copyVersion: presence.copyVersion, - registryVersion, - }), - }; - if (row.verdict === "broken") - row.reason = missingTargets.map((t) => `target missing: ${t}`).join("; "); - if (agent === "opencode" && presence.installed && presence.form === "npm") { - // #1234/#2199: the cache copy is bili-owned in place (self-updates via its - // own proxy) — show the actual load path + disk version when resolvable so - // the stale verdict below is honest, not "version not resolvable". - const cp = - presence.copyVersion !== undefined ? ` v${presence.copyVersion}` : ""; - const p = - presence.targets[0] !== undefined ? ` (${presence.targets[0]})` : ""; - row.detail += `; cache copy${p}${cp} is bili-owned and self-updates in place via its own proxy (#1234) — reload/restart OpenCode to activate a disk update`; - } - if (agent === "claude" && presence.installed) { - // #2290: the lane itself is healthy, but a co-installed Claude Desktop - // overrides the managed ANTHROPIC_BASE_URL — desktop sessions then get - // neither bili compression nor native auto-compact. Advisory only: never - // change the verdict. Two sources: standing disk evidence + the last - // hook-detected bypass (its stderr is invisible outside debug mode). - const warnings: string[] = []; - if (claudeDesktopPresent()) { - warnings.push( - "Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL, so desktop sessions bypass bili entirely AND lose native auto-compact (managed block sets DISABLE_AUTO_COMPACT=1) — #2290", - ); - } - try { - const rec = JSON.parse( - fs.readFileSync(claudeRoutingWarningFile(), "utf8"), - ) as { at?: unknown; reasons?: unknown }; - if ( - Array.isArray(rec.reasons) && - rec.reasons.length > 0 && - rec.reasons.every((r) => typeof r === "string") - ) { - const at = - typeof rec.at === "number" - ? ` at ${new Date(rec.at).toISOString()}` - : ""; - warnings.push( - `last SessionStart hook detected a routing bypass${at}: ${(rec.reasons as string[]).join("; ")}`, - ); - } - } catch { - // no marker or unreadable — nothing to surface - } - if (warnings.length > 0) row.warnings = warnings; - } - return [row]; + const kind = REFERENCE_LANES.has(agent) ? "reference" : "host-managed"; + const base: Omit< + DoctorLane, + | "agent" + | "installed" + | "detail" + | "targetExists" + | "copyVersion" + | "verdict" + | "reason" + > = { + kind, + registryVersion, + channel: UPDATE_CHANNEL[agent], + }; + if (agent === "dsh" && presence.profiles !== undefined) { + return presence.profiles.map((p) => { + const missing = p.bundleInstalled && p.copyVersion === undefined; + const row: DoctorLane = { + ...base, + agent: `dsh:${p.name}`, + installed: true, + detail: + p.spec !== undefined + ? `dep spec: ${p.spec}${p.pinned ? " (local pin — dev lane, manual)" : ""}` + : "(no dep spec)", + copyVersion: p.copyVersion, + verdict: laneVerdict({ + installed: true, + targetMissing: missing, + frozen: p.pinned, + copyVersion: p.copyVersion, + registryVersion, + }), + }; + if (row.verdict === "frozen") + row.reason = + "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)"; + else if (row.verdict === "broken") + row.reason = + "profile depends on billion-context but the bundle copy is missing — rerun 'bili plugin install dsh'"; + const shadow = dshBundleShadowWarning({ + packageName: ctx.packageName, + globalInstallDir: ctx.global.installDir, + globalDiskVersion: ctx.global.diskVersion, + profileName: p.name, + bundleInstalled: p.bundleInstalled, + profileCopyVersion: p.copyVersion, + }); + if (shadow !== undefined) + row.warnings = [...(row.warnings ?? []), shadow]; + return row; + }); + } + const targetsExist = + presence.targets.length > 0 + ? presence.targets.every((t) => fs.existsSync(t)) + : undefined; + const missingTargets = presence.targets.filter((t) => !fs.existsSync(t)); + let detail = + presence.pointers.length > 0 + ? presence.pointers.join("; ") + : presence.installed + ? "installed" + : "not installed"; + if ( + agent === "pi" && + presence.form === "npm" && + presence.targets.length === 0 + ) + detail += "; pi materializes the npm copy on next startup"; + const row: DoctorLane = { + ...base, + agent, + installed: presence.installed, + detail, + targetExists: targetsExist, + copyVersion: presence.copyVersion, + verdict: laneVerdict({ + installed: presence.installed, + targetMissing: missingTargets.length > 0, + frozen: false, + copyVersion: presence.copyVersion, + registryVersion, + }), + }; + if (row.verdict === "broken") + row.reason = missingTargets.map((t) => `target missing: ${t}`).join("; "); + if (agent === "opencode" && presence.installed && presence.form === "npm") { + // #1234/#2199: the cache copy is bili-owned in place (self-updates via its + // own proxy) — show the actual load path + disk version when resolvable so + // the stale verdict below is honest, not "version not resolvable". + const cp = + presence.copyVersion !== undefined ? ` v${presence.copyVersion}` : ""; + const p = + presence.targets[0] !== undefined ? ` (${presence.targets[0]})` : ""; + row.detail += `; cache copy${p}${cp} is bili-owned and self-updates in place via its own proxy (#1234) — reload/restart OpenCode to activate a disk update`; + } + if (agent === "claude" && presence.installed) { + // #2290: the lane itself is healthy, but a co-installed Claude Desktop + // overrides the managed ANTHROPIC_BASE_URL — desktop sessions then get + // neither bili compression nor native auto-compact. Advisory only: never + // change the verdict. Two sources: standing disk evidence + the last + // hook-detected bypass (its stderr is invisible outside debug mode). + const warnings: string[] = []; + if (claudeDesktopPresent()) { + warnings.push( + "Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL, so desktop sessions bypass bili entirely AND lose native auto-compact (managed block sets DISABLE_AUTO_COMPACT=1) — #2290", + ); + } + try { + const rec = JSON.parse( + fs.readFileSync(claudeRoutingWarningFile(), "utf8"), + ) as { at?: unknown; reasons?: unknown }; + if ( + Array.isArray(rec.reasons) && + rec.reasons.length > 0 && + rec.reasons.every((r) => typeof r === "string") + ) { + const at = + typeof rec.at === "number" + ? ` at ${new Date(rec.at).toISOString()}` + : ""; + warnings.push( + `last SessionStart hook detected a routing bypass${at}: ${(rec.reasons as string[]).join("; ")}`, + ); + } + } catch { + // no marker or unreadable — nothing to surface + } + if (warnings.length > 0) row.warnings = warnings; + } + return [row]; } function fmtTime(ts: number): string { - return new Date(ts).toISOString(); + return new Date(ts).toISOString(); } function verdictText( - v: LaneVerdict, - row: { oldVersion?: string; registryVersion?: string }, + v: LaneVerdict, + row: { oldVersion?: string; registryVersion?: string }, ): string { - if ( - v === "stale" && - row.oldVersion !== undefined && - row.registryVersion !== undefined - ) - return `stale (v${row.oldVersion} → v${row.registryVersion})`; - return v; + if ( + v === "stale" && + row.oldVersion !== undefined && + row.registryVersion !== undefined + ) + return `stale (v${row.oldVersion} → v${row.registryVersion})`; + return v; } export function renderDoctorReport(report: DoctorReport): string { - const lines: string[] = []; - const g = report.global; - lines.push( - `bili doctor — ${report.packageName} (running v${g.runningVersion})`, - ); - lines.push(`generated ${fmtTime(report.generatedAt)}`); - lines.push(""); - lines.push("global"); - lines.push( - ` form ${g.form}${g.owner !== undefined ? ` (owned by ${g.owner})` : ""}${g.installDir !== undefined ? ` — ${g.installDir}` : " — install dir not found"}`, - ); - lines.push( - ` versions disk ${g.diskVersion ?? "?"} registry[${g.updateTag}] ${g.registryVersion ?? "unreachable"}`, - ); - lines.push( - ` last check ${g.lastCheckTime !== undefined ? fmtTime(g.lastCheckTime) : "never"}`, - ); - lines.push( - ` verdict ${verdictText(g.verdict, { oldVersion: g.diskVersion, registryVersion: g.registryVersion })}${g.reason !== undefined ? ` — ${g.reason}` : ""}`, - ); - if (g.advisory?.active !== undefined) - lines.push( - ` advisory ⚠️ ${describeAdvisory(g.advisory.active, g.advisory.error)}`, - ); - else if (g.advisory?.error !== undefined) - lines.push( - ` advisory check failed (${g.advisory.error}) — status unknown`, - ); - else lines.push(` advisory none`); - lines.push(""); - lines.push("lanes"); - for (const lane of report.lanes) { - const head = ` ${lane.agent.padEnd(12)} ${verdictText(lane.verdict, { oldVersion: lane.copyVersion, registryVersion: lane.registryVersion }).padEnd(34)} ${lane.kind}`; - lines.push(head); - lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.detail}`); - if (lane.channel !== undefined && lane.installed) - lines.push( - ` ${"".padEnd(12)} ${"".padEnd(34)} updates via: ${lane.channel}`, - ); - if (lane.reason !== undefined) - lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.reason}`); - for (const w of lane.warnings ?? []) - lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ⚠️ ${w}`); - } - lines.push(""); - lines.push("codex model route"); - lines.push(` state ${report.codexIntegration.state}`); - lines.push(` route ${report.codexIntegration.route}`); - lines.push( - ` proxy ${report.codexIntegration.proxyHealthy ? "healthy" : "not verified"}`, - ); - lines.push( - ` evidence ${report.codexIntegration.observedCodexRequest ? "Codex request observed" : "no Codex model request observed"}`, - ); - lines.push(` detail ${report.codexIntegration.detail}`); - lines.push(""); - lines.push("CC Switch"); - lines.push(` detected ${report.ccSwitch.discovered ? "yes" : "no"}`); - lines.push(` mode ${report.ccSwitch.mode}`); - lines.push(` compatibility ${report.ccSwitch.compatibility}`); - lines.push(` detail ${report.ccSwitch.detail}`); - lines.push(""); - lines.push("ChatGPT subscription / Desktop"); - lines.push(` state ${report.chatGptDesktop.state}`); - lines.push(` credentials ${report.chatGptDesktop.credentials}`); - lines.push(` official login ${report.chatGptDesktop.officialLoginChannels}`); - lines.push(` Desktop MCP ${report.chatGptDesktop.desktopMcp}`); - lines.push(""); - lines.push("processes"); - if (report.processes.length === 0) { - lines.push(" none registered"); - } else { - for (const p of report.processes) { - const state = p.alive - ? p.staleCopy - ? "STALE COPY" - : "running" - : "zombie (process gone, marker left behind)"; - lines.push( - ` pid ${String(p.pid).padEnd(7)} port ${String(p.port).padEnd(6)} ${p.origin} ${state}`, - ); - if (p.runningFrom !== undefined) - lines.push( - ` ${"".padEnd(12)} runs from ${p.runningFrom}${p.staleCopy ? " (not the current install dir)" : ""}`, - ); - } - } - const counts: Record = { - ok: 0, - stale: 0, - frozen: 0, - broken: 0, - absent: 0, - }; - for (const l of report.lanes) counts[l.verdict]++; - const zombies = report.processes.filter((p) => !p.alive).length; - lines.push(""); - lines.push( - `summary: ${counts.ok} ok, ${counts.stale} stale, ${counts.frozen} frozen, ${counts.broken} broken, ${counts.absent} absent; processes: ${report.processes.length - zombies} live, ${zombies} zombie`, - ); - return lines.join("\n") + "\n"; + const lines: string[] = []; + const g = report.global; + lines.push( + `bili doctor — ${report.packageName} (running v${g.runningVersion})`, + ); + lines.push(`generated ${fmtTime(report.generatedAt)}`); + lines.push(""); + lines.push("global"); + lines.push( + ` form ${g.form}${g.owner !== undefined ? ` (owned by ${g.owner})` : ""}${g.installDir !== undefined ? ` — ${g.installDir}` : " — install dir not found"}`, + ); + lines.push( + ` versions disk ${g.diskVersion ?? "?"} registry[${g.updateTag}] ${g.registryVersion ?? "unreachable"}`, + ); + lines.push( + ` last check ${g.lastCheckTime !== undefined ? fmtTime(g.lastCheckTime) : "never"}`, + ); + lines.push( + ` verdict ${verdictText(g.verdict, { oldVersion: g.diskVersion, registryVersion: g.registryVersion })}${g.reason !== undefined ? ` — ${g.reason}` : ""}`, + ); + if (g.advisory?.active !== undefined) + lines.push( + ` advisory ⚠️ ${describeAdvisory(g.advisory.active, g.advisory.error)}`, + ); + else if (g.advisory?.error !== undefined) + lines.push( + ` advisory check failed (${g.advisory.error}) — status unknown`, + ); + else lines.push(` advisory none`); + lines.push(""); + lines.push("lanes"); + for (const lane of report.lanes) { + const head = ` ${lane.agent.padEnd(12)} ${verdictText(lane.verdict, { oldVersion: lane.copyVersion, registryVersion: lane.registryVersion }).padEnd(34)} ${lane.kind}`; + lines.push(head); + lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.detail}`); + if (lane.channel !== undefined && lane.installed) + lines.push( + ` ${"".padEnd(12)} ${"".padEnd(34)} updates via: ${lane.channel}`, + ); + if (lane.reason !== undefined) + lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.reason}`); + for (const w of lane.warnings ?? []) + lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ⚠️ ${w}`); + } + lines.push(""); + lines.push("codex model route"); + lines.push(` state ${report.codexIntegration.state}`); + lines.push(` route ${report.codexIntegration.route}`); + lines.push( + ` proxy ${report.codexIntegration.proxyHealthy ? "healthy" : "not verified"}`, + ); + lines.push( + ` evidence ${report.codexIntegration.observedCodexRequest ? "Codex request observed" : "no Codex model request observed"}`, + ); + lines.push(` detail ${report.codexIntegration.detail}`); + lines.push(""); + lines.push("CC Switch"); + lines.push(` detected ${report.ccSwitch.discovered ? "yes" : "no"}`); + lines.push(` mode ${report.ccSwitch.mode}`); + lines.push(` compatibility ${report.ccSwitch.compatibility}`); + lines.push(` detail ${report.ccSwitch.detail}`); + lines.push(""); + lines.push("ChatGPT subscription / Desktop"); + lines.push(` state ${report.chatGptDesktop.state}`); + lines.push(` credentials ${report.chatGptDesktop.credentials}`); + lines.push(` official login ${report.chatGptDesktop.officialLoginChannels}`); + lines.push(` Desktop MCP ${report.chatGptDesktop.desktopMcp}`); + lines.push(""); + lines.push("processes"); + if (report.processes.length === 0) { + lines.push(" none registered"); + } else { + for (const p of report.processes) { + const state = p.alive + ? p.staleCopy + ? "STALE COPY" + : "running" + : "zombie (process gone, marker left behind)"; + lines.push( + ` pid ${String(p.pid).padEnd(7)} port ${String(p.port).padEnd(6)} ${p.origin} ${state}`, + ); + if (p.runningFrom !== undefined) + lines.push( + ` ${"".padEnd(12)} runs from ${p.runningFrom}${p.staleCopy ? " (not the current install dir)" : ""}`, + ); + } + } + const counts: Record = { + ok: 0, + stale: 0, + frozen: 0, + broken: 0, + absent: 0, + }; + for (const l of report.lanes) counts[l.verdict]++; + const zombies = report.processes.filter((p) => !p.alive).length; + lines.push(""); + lines.push( + `summary: ${counts.ok} ok, ${counts.stale} stale, ${counts.frozen} frozen, ${counts.broken} broken, ${counts.absent} absent; processes: ${report.processes.length - zombies} live, ${zombies} zombie`, + ); + return lines.join("\n") + "\n"; } diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 490f5ad204..31240aa870 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -43,66 +43,66 @@ import crypto from "node:crypto"; import { execFileSync, spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; import { - applyEdits, - modify as jsoncModify, - parse as jsoncParse, - type ParseError, + applyEdits, + modify as jsoncModify, + parse as jsoncParse, + type ParseError, } from "jsonc-parser"; import { - parseCodexToml, - resolveDshHome, - resolveHermesHome, - resolveKimiHome, - resolvePiHome, + parseCodexToml, + resolveDshHome, + resolveHermesHome, + resolveKimiHome, + resolvePiHome, } from "./client-config.js"; import { resolveClaudeNativePort } from "./config.js"; import { lanePreferredPort, readProxyInstanceFile } from "./instance.js"; import { - DSH_PACKAGE, - dshBundleInstalled, - dshHasLegacyManagedBlock, - dshProfileDependsOnBili, - dshProfileDepSpec, - dshProfileDirs, - isRegistryDepSpec, - planDshSpawn, - refreshDshProfileBundles, - runDshPlugin, - stripLegacyManagedBlock, + DSH_PACKAGE, + dshBundleInstalled, + dshHasLegacyManagedBlock, + dshProfileDependsOnBili, + dshProfileDepSpec, + dshProfileDirs, + isRegistryDepSpec, + planDshSpawn, + refreshDshProfileBundles, + runDshPlugin, + stripLegacyManagedBlock, } from "./dsh-channel.js"; import { piNpmCopyRoot } from "./pi-channel.js"; import { clearOwnerLaneBackoff, fetchRegistryVersion } from "./update.js"; import { detectCcSwitch } from "./codex-integration/cc-switch.js"; import { - assertCodexConfigLoads, - codexHooksEnabledNote, - findBiliCodexHook, - planCodexHook, - stripCodexHook, + assertCodexConfigLoads, + codexHooksEnabledNote, + findBiliCodexHook, + planCodexHook, + stripCodexHook, } from "./codex-integration/hooks.js"; import { - codexSkillFile, - codexSkillStatus, - installCodexSkill, - removeCodexSkill, + codexSkillFile, + codexSkillStatus, + installCodexSkill, + removeCodexSkill, } from "./codex-integration/skill.js"; import { - codexRouteOrigin, - desiredCodexRoute, - planCodexRoute, - readCodexRoute, - readCodexRouteRecord, - removeCodexRouteRecord, - restoreCodexRoute, - codexRouteRecordPath, - writeCodexRouteRecord, + codexRouteOrigin, + desiredCodexRoute, + planCodexRoute, + readCodexRoute, + readCodexRouteRecord, + removeCodexRouteRecord, + restoreCodexRoute, + codexRouteRecordPath, + writeCodexRouteRecord, } from "./codex-integration/route.js"; import { restoreKimiBackup, unrouteKimi } from "./kimi/native.js"; import { inspectZcodeRouting, resolveZcodeDataDir } from "./zcode/json-edit.js"; import { restoreZcodeBackup, unrouteZcode } from "./zcode/native.js"; import { - installProxyService, - removeProxyService, + installProxyService, + removeProxyService, } from "./proxy-service/service.js"; /** Build a SessionStart hook command line that parses in every shell the @@ -136,40 +136,40 @@ import { * the hook later inherits). The `&` fallback below stays for hypothetical * spaced-head callers, but no shipped hook uses it. Exported for tests. */ export function portableHookCommand(exe: string, args: string[] = []): string { - const fwd = (p: string): string => p.replaceAll("\\", "/"); - const quoteArg = (p: string): string => (/\s/.test(p) ? `"${p}"` : p); - const head = fwd(exe); - const tail = args.map((a) => quoteArg(fwd(a))); - return /\s/.test(head) - ? [`& "${head}"`, ...tail].join(" ") - : [head, ...tail].join(" "); + const fwd = (p: string): string => p.replaceAll("\\", "/"); + const quoteArg = (p: string): string => (/\s/.test(p) ? `"${p}"` : p); + const head = fwd(exe); + const tail = args.map((a) => quoteArg(fwd(a))); + return /\s/.test(head) + ? [`& "${head}"`, ...tail].join(" ") + : [head, ...tail].join(" "); } export const PLUGIN_AGENTS = [ - "pi", - "omp", - "claude", - "codex", - "opencode", - "dsh", - "kimi", - "hermes", - "zcode", + "pi", + "omp", + "claude", + "codex", + "opencode", + "dsh", + "kimi", + "hermes", + "zcode", ] as const; export type PluginAgent = (typeof PLUGIN_AGENTS)[number]; export function selfPackageRoot(): string { - // dist/plugin-install.js -> package root two levels up. - const here = fileURLToPath(import.meta.url); - return path.resolve(path.dirname(here), ".."); + // dist/plugin-install.js -> package root two levels up. + const here = fileURLToPath(import.meta.url); + return path.resolve(path.dirname(here), ".."); } function homeFile(rel: string, envOverride?: string): string { - const raw = ( - envOverride !== undefined ? process.env[envOverride] : undefined - )?.trim(); - const base = raw && raw.length > 0 ? raw : os.homedir(); - return path.join(base, rel); + const raw = ( + envOverride !== undefined ? process.env[envOverride] : undefined + )?.trim(); + const base = raw && raw.length > 0 ? raw : os.homedir(); + return path.join(base, rel); } // #1002: backup = the state before bili's LATEST write, but only when the @@ -181,78 +181,78 @@ function homeFile(rel: string, envOverride?: string): string { // `.bili-last` carries the hash of what bili last wrote; "unchanged" // means the on-disk bytes still hash to that value. function hashText(text: string): string { - return crypto.createHash("sha256").update(text).digest("hex"); + return crypto.createHash("sha256").update(text).digest("hex"); } function backupBeforeWrite(file: string): void { - if (!fs.existsSync(file)) return; - const bak = `${file}.bili-bak`; - let cur: string; - try { - cur = hashText(fs.readFileSync(file, "utf8")); - } catch { - return; - } - let prev: string | undefined; - try { - prev = fs.readFileSync(`${file}.bili-last`, "utf8").trim(); - } catch {} - if (prev === cur && fs.existsSync(bak)) return; - fs.copyFileSync(file, bak); + if (!fs.existsSync(file)) return; + const bak = `${file}.bili-bak`; + let cur: string; + try { + cur = hashText(fs.readFileSync(file, "utf8")); + } catch { + return; + } + let prev: string | undefined; + try { + prev = fs.readFileSync(`${file}.bili-last`, "utf8").trim(); + } catch {} + if (prev === cur && fs.existsSync(bak)) return; + fs.copyFileSync(file, bak); } // One writer discipline for every config write bili performs: snapshot per // backupBeforeWrite above, write, then record what we wrote so the NEXT // write can tell bili's own output apart from a user edit. function writeConfigText(file: string, text: string): void { - fs.mkdirSync(path.dirname(file), { recursive: true }); - backupBeforeWrite(file); - fs.writeFileSync(file, text); - try { - fs.writeFileSync(`${file}.bili-last`, `${hashText(text)}\n`); - } catch {} + fs.mkdirSync(path.dirname(file), { recursive: true }); + backupBeforeWrite(file); + fs.writeFileSync(file, text); + try { + fs.writeFileSync(`${file}.bili-last`, `${hashText(text)}\n`); + } catch {} } function readJson(file: string): Record { - let text: string; - try { - text = fs.readFileSync(file, "utf8"); - } catch (err) { - if ((err as { code?: string }).code === "ENOENT") return {}; - throw err; - } - let parsed: unknown; - try { - parsed = JSON.parse(text); - } catch (err) { - throw new Error( - `${file}: not valid JSON (${err instanceof Error ? err.message : String(err)}) — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`, - ); - } - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { - throw new Error( - `${file}: expected a JSON object at top level, refusing to overwrite`, - ); - } - return parsed as Record; + let text: string; + try { + text = fs.readFileSync(file, "utf8"); + } catch (err) { + if ((err as { code?: string }).code === "ENOENT") return {}; + throw err; + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (err) { + throw new Error( + `${file}: not valid JSON (${err instanceof Error ? err.message : String(err)}) — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`, + ); + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error( + `${file}: expected a JSON object at top level, refusing to overwrite`, + ); + } + return parsed as Record; } function writeJson(file: string, data: unknown): void { - writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); + writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); } function requireDistFile(file: string): void { - if (!fs.existsSync(file)) { - process.stderr.write( - `bili plugin: warning: ${file} does not exist yet (run \`npm run build\` in ${selfPackageRoot()}) — the entry will be dead until built\n`, - ); - } + if (!fs.existsSync(file)) { + process.stderr.write( + `bili plugin: warning: ${file} does not exist yet (run \`npm run build\` in ${selfPackageRoot()}) — the entry will be dead until built\n`, + ); + } } // — pi ———————————————————————————————————————————————————————————————— function piSettingsFile(): string { - return path.join(resolvePiHome(process.env), "settings.json"); + return path.join(resolvePiHome(process.env), "settings.json"); } // A packages entry is "ours" if it points at THIS install's package root, @@ -262,12 +262,12 @@ function piSettingsFile(): string { // plugin moved into billion-context itself). install() replaces every match // so exactly one bili plugin is live after `bili plugin install pi`. export function isPiEntry(entry: string, root: string): boolean { - return ( - entry === root || - /^npm:billion-context(-pi)?(@|$)/.test(entry) || - /(^|[/\\])node_modules[/\\]billion-context(-pi)?([/\\]|$)/.test(entry) || - /(^|[/\\])billion-context(-pi)?$/.test(entry) - ); + return ( + entry === root || + /^npm:billion-context(-pi)?(@|$)/.test(entry) || + /(^|[/\\])node_modules[/\\]billion-context(-pi)?([/\\]|$)/.test(entry) || + /(^|[/\\])billion-context(-pi)?$/.test(entry) + ); } // Entries that load THIS package's pi plugin (billion-context proper). @@ -276,12 +276,12 @@ export function isPiEntry(entry: string, root: string): boolean { // BILLION_CONTEXT_PROXY — so treating it as "installed" wrongly suppressed // the launcher's `-e` fallback and left pi with no plugin at all. export function isBiliPiEntry(entry: string, root: string): boolean { - return ( - entry === root || - /^npm:billion-context(@|$)/.test(entry) || - /(^|[/\\])node_modules[/\\]billion-context([/\\]|$)/.test(entry) || - /(^|[/\\])billion-context$/.test(entry) - ); + return ( + entry === root || + /^npm:billion-context(@|$)/.test(entry) || + /(^|[/\\])node_modules[/\\]billion-context([/\\]|$)/.test(entry) || + /(^|[/\\])billion-context$/.test(entry) + ); } // #925 pi form of the npm-standard entry: for npm installs (package root @@ -293,67 +293,67 @@ export function isBiliPiEntry(entry: string, root: string): boolean { export const PI_NPM_ENTRY = "npm:billion-context"; export function piEntryFor(root: string): string { - return isNpmInstallForm(root) ? PI_NPM_ENTRY : root; + return isNpmInstallForm(root) ? PI_NPM_ENTRY : root; } function piInstall(): string { - const root = selfPackageRoot(); - const file = piSettingsFile(); - const settings = readJson(file); - const packages = Array.isArray(settings.packages) - ? (settings.packages as unknown[]).map(String) - : []; - const entry = piEntryFor(root); - if (packages.some((p) => p === entry)) - return `pi: already installed (${file})`; - const removed = packages.filter((p) => isPiEntry(p, root)); - const kept = packages.filter((p) => !isPiEntry(p, root)); - kept.push(entry); - settings.packages = kept; - writeJson(file, settings); - // #788: dropped entries must be visible — silently replacing a documented - // setup (npm:billion-context-pi) left users with no compression and no - // idea their config changed. Project-scope reminder mirrors the opencode - // installer's LOCAL-scope note: a `pi install -l` entry lives in - // /.pi/settings.json, which this global strip never touches. - const note = - removed.length > 0 - ? `\npi: replaced existing entries: ${removed.join(", ")}` + - "\npi: also check /.pi/settings.json — a project-scope billion-context-pi entry (pi install -l) lives there, not in this global settings" - : ""; - const form = - entry === PI_NPM_ENTRY - ? " (pi-managed — pi installs it; the proxy self-refreshes it via `pi update --extension npm:billion-context`, or run that manually)" - : ""; - return `pi: installed -> ${file} packages += ${entry}${form}${note}`; + const root = selfPackageRoot(); + const file = piSettingsFile(); + const settings = readJson(file); + const packages = Array.isArray(settings.packages) + ? (settings.packages as unknown[]).map(String) + : []; + const entry = piEntryFor(root); + if (packages.some((p) => p === entry)) + return `pi: already installed (${file})`; + const removed = packages.filter((p) => isPiEntry(p, root)); + const kept = packages.filter((p) => !isPiEntry(p, root)); + kept.push(entry); + settings.packages = kept; + writeJson(file, settings); + // #788: dropped entries must be visible — silently replacing a documented + // setup (npm:billion-context-pi) left users with no compression and no + // idea their config changed. Project-scope reminder mirrors the opencode + // installer's LOCAL-scope note: a `pi install -l` entry lives in + // /.pi/settings.json, which this global strip never touches. + const note = + removed.length > 0 + ? `\npi: replaced existing entries: ${removed.join(", ")}` + + "\npi: also check /.pi/settings.json — a project-scope billion-context-pi entry (pi install -l) lives there, not in this global settings" + : ""; + const form = + entry === PI_NPM_ENTRY + ? " (pi-managed — pi installs it; the proxy self-refreshes it via `pi update --extension npm:billion-context`, or run that manually)" + : ""; + return `pi: installed -> ${file} packages += ${entry}${form}${note}`; } function piRemove(): string { - const root = selfPackageRoot(); - const file = piSettingsFile(); - const settings = readJson(file); - const packages = Array.isArray(settings.packages) - ? (settings.packages as unknown[]).map(String) - : []; - const removed = packages.filter((p) => isPiEntry(p, root)); - if (removed.length === 0) return `pi: not installed (${file})`; - settings.packages = packages.filter((p) => !isPiEntry(p, root)); - writeJson(file, settings); - // #788: same visibility rule as install — removed entries are reported. - return `pi: removed from ${file}\npi: removed entries: ${removed.join(", ")}`; + const root = selfPackageRoot(); + const file = piSettingsFile(); + const settings = readJson(file); + const packages = Array.isArray(settings.packages) + ? (settings.packages as unknown[]).map(String) + : []; + const removed = packages.filter((p) => isPiEntry(p, root)); + if (removed.length === 0) return `pi: not installed (${file})`; + settings.packages = packages.filter((p) => !isPiEntry(p, root)); + writeJson(file, settings); + // #788: same visibility rule as install — removed entries are reported. + return `pi: removed from ${file}\npi: removed entries: ${removed.join(", ")}`; } function piStatus(): string { - const root = selfPackageRoot(); - const packages = readJson(piSettingsFile()).packages; - const list = Array.isArray(packages) - ? (packages as unknown[]).map(String) - : []; - // Any entry that loads THIS package's plugin counts (npm: form or abs - // root); the legacy billion-context-pi package deliberately does not. - return list.some((p) => isBiliPiEntry(p, root) || p === piEntryFor(root)) - ? "installed" - : "not installed"; + const root = selfPackageRoot(); + const packages = readJson(piSettingsFile()).packages; + const list = Array.isArray(packages) + ? (packages as unknown[]).map(String) + : []; + // Any entry that loads THIS package's plugin counts (npm: form or abs + // root); the legacy billion-context-pi package deliberately does not. + return list.some((p) => isBiliPiEntry(p, root) || p === piEntryFor(root)) + ? "installed" + : "not installed"; } // — omp ——————————————————————————————————————————————————————————————— @@ -372,23 +372,23 @@ const OMP_ENTRY_RE = /[\\/]dist[\\/]agent[\\/]omp(-native)?\.js$/; // to guess). Matching is scoped to this block, so a same-valued line under // any other key is never counted as installed and never removed. function ompExtensionItemLines(text: string): number[] { - const lines = text.split("\n"); - let keyIdx = -1; - for (let i = 0; i < lines.length; i++) { - if (/^extensions:(\s+(#.*)?)?$/.test(lines[i]!)) { - if (keyIdx !== -1) return []; - keyIdx = i; - } - } - if (keyIdx === -1) return []; - const items: number[] = []; - for (let i = keyIdx + 1; i < lines.length; i++) { - const t = lines[i]!.trimStart(); - if (t === "" || t.startsWith("#")) continue; - if (t === "-" || t.startsWith("- ")) items.push(i); - else break; - } - return items; + const lines = text.split("\n"); + let keyIdx = -1; + for (let i = 0; i < lines.length; i++) { + if (/^extensions:(\s+(#.*)?)?$/.test(lines[i]!)) { + if (keyIdx !== -1) return []; + keyIdx = i; + } + } + if (keyIdx === -1) return []; + const items: number[] = []; + for (let i = keyIdx + 1; i < lines.length; i++) { + const t = lines[i]!.trimStart(); + if (t === "" || t.startsWith("#")) continue; + if (t === "-" || t.startsWith("- ")) items.push(i); + else break; + } + return items; } // The config.yml the plugin commands read/write. When PI_CODING_AGENT_DIR @@ -398,144 +398,144 @@ function ompExtensionItemLines(text: string): number[] { // would silently miss the real config. A note is printed so the user sees // which file was actually touched. function ompConfigFile(): string { - const raw = process.env.PI_CODING_AGENT_DIR?.trim(); - if (raw && raw.length > 0) { - if (raw.endsWith("-bili") && raw.length > "-bili".length) { - const realHome = raw.slice(0, -"-bili".length); - process.stderr.write( - `bili plugin: PI_CODING_AGENT_DIR points at the bili overlay ${raw} — operating on the real omp home ${realHome} instead\n`, - ); - return path.join(realHome, "config.yml"); - } - return path.join(raw, "config.yml"); - } - return path.join(os.homedir(), ".omp", "agent", "config.yml"); + const raw = process.env.PI_CODING_AGENT_DIR?.trim(); + if (raw && raw.length > 0) { + if (raw.endsWith("-bili") && raw.length > "-bili".length) { + const realHome = raw.slice(0, -"-bili".length); + process.stderr.write( + `bili plugin: PI_CODING_AGENT_DIR points at the bili overlay ${raw} — operating on the real omp home ${realHome} instead\n`, + ); + return path.join(realHome, "config.yml"); + } + return path.join(raw, "config.yml"); + } + return path.join(os.homedir(), ".omp", "agent", "config.yml"); } function ompExtensionPath(): string { - return path.join(selfPackageRoot(), "dist", "agent", "omp-native.js"); + return path.join(selfPackageRoot(), "dist", "agent", "omp-native.js"); } function ompEntryValue(line: string): string { - return line - .replace(/#.*$/, "") - .trim() - .replace(/^-\s*/, "") - .replace(/^["']|["']$/g, "") - .trim(); + return line + .replace(/#.*$/, "") + .trim() + .replace(/^-\s*/, "") + .replace(/^["']|["']$/g, "") + .trim(); } // A bili omp entry that actually loads: matches our entry shape AND the target // file exists on disk (stale entries from a moved install don't count). function ompEntryLoadable(value: string): boolean { - return OMP_ENTRY_RE.test(value) && fs.existsSync(value); + return OMP_ENTRY_RE.test(value) && fs.existsSync(value); } function ompRemove(): string { - const file = ompConfigFile(); - if (!fs.existsSync(file)) return `omp: not installed (${file})`; - const text = fs.readFileSync(file, "utf8"); - const lines = text.split("\n"); - const drop = new Set( - ompExtensionItemLines(text).filter((i) => - OMP_ENTRY_RE.test(ompEntryValue(lines[i]!)), - ), - ); - if (drop.size === 0) return `omp: not installed (${file})`; - const cleaned = lines.filter((_, i) => !drop.has(i)).join("\n"); - writeConfigText(file, cleaned); - return `omp: removed from ${file}`; + const file = ompConfigFile(); + if (!fs.existsSync(file)) return `omp: not installed (${file})`; + const text = fs.readFileSync(file, "utf8"); + const lines = text.split("\n"); + const drop = new Set( + ompExtensionItemLines(text).filter((i) => + OMP_ENTRY_RE.test(ompEntryValue(lines[i]!)), + ), + ); + if (drop.size === 0) return `omp: not installed (${file})`; + const cleaned = lines.filter((_, i) => !drop.has(i)).join("\n"); + writeConfigText(file, cleaned); + return `omp: removed from ${file}`; } function ompInstall(): string { - const file = ompConfigFile(); - const entry = ompExtensionPath(); - requireDistFile(entry); - fs.mkdirSync(path.dirname(file), { recursive: true }); - let text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; - // Exactly one bili owner after install (#957): a lone native entry → done. - // Any other bili entry — pre-#957 thin dist/agent/omp.js installs or stale - // duplicates — is dropped and replaced by the insert below, so an old - // install upgrades to native mode on re-install. - const replaced: string[] = []; - { - const lines = text.split("\n"); - const ours = new Set(); - for (const i of ompExtensionItemLines(text)) { - const v = ompEntryValue(lines[i]!); - if (!OMP_ENTRY_RE.test(v)) continue; - ours.add(i); - if (v !== entry) replaced.push(v); - } - if ( - ours.size === 1 && - [...ours].every((i) => ompEntryValue(lines[i]!) === entry) - ) { - return `omp: already installed (${file})`; - } - if (ours.size > 0) text = lines.filter((_, i) => !ours.has(i)).join("\n"); - } - const keyCount = (text.match(/^extensions:/gm) ?? []).length; - if (keyCount > 1) - throw new Error( - `${file}: multiple \`extensions:\` keys — fix the file first, refusing to edit`, - ); - if (/^extensions:\s*\S/m.test(text) && !/^extensions:\s*$/m.test(text)) { - throw new Error( - `${file}: \`extensions:\` uses flow style or an inline value; convert it to a block list first, refusing to edit`, - ); - } - let out: string; - const extMatch = /^extensions:\s*$/m.exec(text); - if (extMatch !== null) { - const afterKey = text.indexOf("\n", extMatch.index); - const rest = afterKey < 0 ? "" : text.slice(afterKey + 1); - const firstNonList = rest.search(/^(?!\s*-\s)\S/m); - const existingIndent = /^(\s*)-\s\S/m.exec(rest)?.[1] ?? " "; - let head: string; - let tail: string; - if (firstNonList >= 0) { - head = text.slice(0, afterKey + 1 + firstNonList); - tail = text.slice(afterKey + 1 + firstNonList); - } else { - head = text.length === 0 || text.endsWith("\n") ? text : text + "\n"; - tail = ""; - } - out = `${head}${existingIndent}- ${entry}\n${tail}`; - } else { - out = text.endsWith("\n") || text.length === 0 ? text : text + "\n"; - out += `extensions:\n - ${entry}\n`; - } - const outLines = out.split("\n"); - const occurrences = ompExtensionItemLines(out).filter( - (i) => ompEntryValue(outLines[i]!) === entry, - ).length; - if (occurrences !== 1) { - throw new Error( - `${file}: edit would leave ${occurrences} copies of the entry — aborting without writing`, - ); - } - backupBeforeWrite(file); - fs.writeFileSync(file, out); - try { - fs.writeFileSync(`${file}.bili-last`, `${hashText(out)}\n`); - } catch {} - const note = replaced.length > 0 ? ` (replaced ${replaced.join(", ")})` : ""; - return `omp: installed -> ${file} extensions += ${entry}${note}`; + const file = ompConfigFile(); + const entry = ompExtensionPath(); + requireDistFile(entry); + fs.mkdirSync(path.dirname(file), { recursive: true }); + let text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + // Exactly one bili owner after install (#957): a lone native entry → done. + // Any other bili entry — pre-#957 thin dist/agent/omp.js installs or stale + // duplicates — is dropped and replaced by the insert below, so an old + // install upgrades to native mode on re-install. + const replaced: string[] = []; + { + const lines = text.split("\n"); + const ours = new Set(); + for (const i of ompExtensionItemLines(text)) { + const v = ompEntryValue(lines[i]!); + if (!OMP_ENTRY_RE.test(v)) continue; + ours.add(i); + if (v !== entry) replaced.push(v); + } + if ( + ours.size === 1 && + [...ours].every((i) => ompEntryValue(lines[i]!) === entry) + ) { + return `omp: already installed (${file})`; + } + if (ours.size > 0) text = lines.filter((_, i) => !ours.has(i)).join("\n"); + } + const keyCount = (text.match(/^extensions:/gm) ?? []).length; + if (keyCount > 1) + throw new Error( + `${file}: multiple \`extensions:\` keys — fix the file first, refusing to edit`, + ); + if (/^extensions:\s*\S/m.test(text) && !/^extensions:\s*$/m.test(text)) { + throw new Error( + `${file}: \`extensions:\` uses flow style or an inline value; convert it to a block list first, refusing to edit`, + ); + } + let out: string; + const extMatch = /^extensions:\s*$/m.exec(text); + if (extMatch !== null) { + const afterKey = text.indexOf("\n", extMatch.index); + const rest = afterKey < 0 ? "" : text.slice(afterKey + 1); + const firstNonList = rest.search(/^(?!\s*-\s)\S/m); + const existingIndent = /^(\s*)-\s\S/m.exec(rest)?.[1] ?? " "; + let head: string; + let tail: string; + if (firstNonList >= 0) { + head = text.slice(0, afterKey + 1 + firstNonList); + tail = text.slice(afterKey + 1 + firstNonList); + } else { + head = text.length === 0 || text.endsWith("\n") ? text : text + "\n"; + tail = ""; + } + out = `${head}${existingIndent}- ${entry}\n${tail}`; + } else { + out = text.endsWith("\n") || text.length === 0 ? text : text + "\n"; + out += `extensions:\n - ${entry}\n`; + } + const outLines = out.split("\n"); + const occurrences = ompExtensionItemLines(out).filter( + (i) => ompEntryValue(outLines[i]!) === entry, + ).length; + if (occurrences !== 1) { + throw new Error( + `${file}: edit would leave ${occurrences} copies of the entry — aborting without writing`, + ); + } + backupBeforeWrite(file); + fs.writeFileSync(file, out); + try { + fs.writeFileSync(`${file}.bili-last`, `${hashText(out)}\n`); + } catch {} + const note = replaced.length > 0 ? ` (replaced ${replaced.join(", ")})` : ""; + return `omp: installed -> ${file} extensions += ${entry}${note}`; } function ompStatus(): string { - const file = ompConfigFile(); - const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; - const lines = text.split("\n"); - let broken = false; - for (const i of ompExtensionItemLines(text)) { - const v = ompEntryValue(lines[i]!); - if (!OMP_ENTRY_RE.test(v)) continue; - if (fs.existsSync(v)) return "installed"; - broken = true; - } - return broken ? "broken" : "not installed"; + const file = ompConfigFile(); + const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + const lines = text.split("\n"); + let broken = false; + for (const i of ompExtensionItemLines(text)) { + const v = ompEntryValue(lines[i]!); + if (!OMP_ENTRY_RE.test(v)) continue; + if (fs.existsSync(v)) return "installed"; + broken = true; + } + return broken ? "broken" : "not installed"; } /** True when the given omp home's config.yml carries a bili plugin entry @@ -546,15 +546,15 @@ function ompStatus(): string { * install paths (file gone) don't count: omp fails to load those, so the * launcher must supply the working plugin itself. */ export function ompPluginLoadedFrom(ompHome: string): boolean { - try { - const text = fs.readFileSync(path.join(ompHome, "config.yml"), "utf8"); - const lines = text.split("\n"); - return ompExtensionItemLines(text).some((i) => - ompEntryLoadable(ompEntryValue(lines[i]!)), - ); - } catch { - return false; - } + try { + const text = fs.readFileSync(path.join(ompHome, "config.yml"), "utf8"); + const lines = text.split("\n"); + return ompExtensionItemLines(text).some((i) => + ompEntryLoadable(ompEntryValue(lines[i]!)), + ); + } catch { + return false; + } } // — claude ————————————————————————————————————————————————————————————— @@ -562,7 +562,7 @@ export function ompPluginLoadedFrom(ompHome: string): boolean { const CLAUDE_EXEC_TIMEOUT_MS = 15000; function claudeMcpJson(): string { - return homeFile(".claude.json", "CLAUDE_CONFIG_DIR"); + return homeFile(".claude.json", "CLAUDE_CONFIG_DIR"); } /** ~/.claude/settings.json honoring CLAUDE_CONFIG_DIR (claude replaces the @@ -570,11 +570,11 @@ function claudeMcpJson(): string { * here — env.ANTHROPIC_BASE_URL / env.DISABLE_AUTO_COMPACT / * hooks.SessionStart. */ export function claudeSettingsFile( - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = process.env, ): string { - const raw = env.CLAUDE_CONFIG_DIR?.trim(); - const base = raw && raw.length > 0 ? raw : path.join(os.homedir(), ".claude"); - return path.join(base, "settings.json"); + const raw = env.CLAUDE_CONFIG_DIR?.trim(); + const base = raw && raw.length > 0 ? raw : path.join(os.homedir(), ".claude"); + return path.join(base, "settings.json"); } // #1146: /acp-cache for claude. Claude Code has no in-process command API — @@ -594,21 +594,21 @@ Arguments: $ARGUMENTS /** /commands/acp-cache.md (claude replaces the * whole directory when CLAUDE_CONFIG_DIR is set — same rule as settings.json). */ export function claudeAcpCacheCommandFile( - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = process.env, ): string { - return path.join( - path.dirname(claudeSettingsFile(env)), - "commands", - "acp-cache.md", - ); + return path.join( + path.dirname(claudeSettingsFile(env)), + "commands", + "acp-cache.md", + ); } /** True for an ANTHROPIC_BASE_URL value written by a bili managed block: * loopback /bili/-wrapped upstream. Any port matches — an older install's * port differs from the current one, and both are ours to rewrite. */ export function isBiliClaudeBaseUrl(value: unknown): boolean { - if (typeof value !== "string") return false; - return /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/https?:\/\//.test(value); + if (typeof value !== "string") return false; + return /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/https?:\/\//.test(value); } /** Disk evidence that the Claude Desktop app is installed — the host whose @@ -619,34 +619,34 @@ export function isBiliClaudeBaseUrl(value: unknown): boolean { * as an advisory input and a miss as absence-of-evidence, never an error. * Injectable for tests. */ export function claudeDesktopPresent( - opts: { - platform?: string; - localAppData?: string; - home?: string; - appRoots?: string[]; - } = {}, + opts: { + platform?: string; + localAppData?: string; + home?: string; + appRoots?: string[]; + } = {}, ): boolean { - const platform = opts.platform ?? process.platform; - const home = opts.home ?? os.homedir(); - if (platform === "win32") { - const lad = opts.localAppData ?? process.env.LOCALAPPDATA; - if (lad === undefined || lad.length === 0) return false; - return fs.existsSync(path.join(lad, "Programs", "Claude")); - } - if (platform === "darwin") { - const roots = opts.appRoots ?? ["/Applications"]; - return [...roots, path.join(home, "Applications")].some((r) => - fs.existsSync(path.join(r, "Claude.app")), - ); - } - return false; + const platform = opts.platform ?? process.platform; + const home = opts.home ?? os.homedir(); + if (platform === "win32") { + const lad = opts.localAppData ?? process.env.LOCALAPPDATA; + if (lad === undefined || lad.length === 0) return false; + return fs.existsSync(path.join(lad, "Programs", "Claude")); + } + if (platform === "darwin") { + const roots = opts.appRoots ?? ["/Applications"]; + return [...roots, path.join(home, "Applications")].some((r) => + fs.existsSync(path.join(r, "Claude.app")), + ); + } + return false; } export function claudeNativeBaseUrl( - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = process.env, ): string { - const origin = `http://127.0.0.1:${resolveClaudeNativePort(env) ?? lanePreferredPort("claude", env)}`; - return claudeNativeBaseUrlForOrigin(origin, undefined, env); + const origin = `http://127.0.0.1:${resolveClaudeNativePort(env) ?? lanePreferredPort("claude", env)}`; + return claudeNativeBaseUrlForOrigin(origin, undefined, env); } /** #1660: the wrapped base URL for an arbitrary live origin — the @@ -656,29 +656,29 @@ export function claudeNativeBaseUrl( * UNWRAPPED value of the current settings URL to preserve a relay an * earlier install baked in. */ export function claudeNativeBaseUrlForOrigin( - origin: string, - upstream: string | undefined, - env: NodeJS.ProcessEnv = process.env, + origin: string, + upstream: string | undefined, + env: NodeJS.ProcessEnv = process.env, ): string { - const relay = env.BILI_CLAUDE_UPSTREAM?.trim(); - const base = ( - upstream !== undefined && upstream.length > 0 - ? upstream - : relay && relay.length > 0 - ? relay - : "https://api.anthropic.com" - ).replace(/\/+$/, ""); - const prefix = origin.replace(/\/+$/, "") + "/bili/"; - return base.startsWith(prefix) ? base : prefix + base; + const relay = env.BILI_CLAUDE_UPSTREAM?.trim(); + const base = ( + upstream !== undefined && upstream.length > 0 + ? upstream + : relay && relay.length > 0 + ? relay + : "https://api.anthropic.com" + ).replace(/\/+$/, ""); + const prefix = origin.replace(/\/+$/, "") + "/bili/"; + return base.startsWith(prefix) ? base : prefix + base; } /** The inverse of the wrap: strip a bili wrapper (any loopback port) from a * base URL. Returns undefined for anything not written by us. */ export function unwrapBiliBaseUrl(value: string): string | undefined { - const m = /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/(https?:\/\/.+)$/.exec( - value, - ); - return m ? m[1] : undefined; + const m = /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/(https?:\/\/.+)$/.exec( + value, + ); + return m ? m[1] : undefined; } /** #1660: SessionStart drift-repair — repin the managed block's @@ -690,28 +690,28 @@ export function unwrapBiliBaseUrl(value: string): string | undefined { * fresh across upgrades. Returns the change notes for the hook's log; * never throws, and writes only when the file actually changes. */ export function repinClaudeManagedBaseUrl( - origin: string, - env: NodeJS.ProcessEnv = process.env, + origin: string, + env: NodeJS.ProcessEnv = process.env, ): string[] { - const file = claudeSettingsFile(env); - const settings = readJson(file); - const cur = (settings.env as Record | undefined) - ?.ANTHROPIC_BASE_URL; - const baseUrl = claudeNativeBaseUrlForOrigin( - origin, - typeof cur === "string" ? unwrapBiliBaseUrl(cur) : undefined, - env, - ); - // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. - const hookCommand = portableHookCommand("node", [ - path.join(selfPackageRoot(), "dist", "claude-native-bootstrap.js"), - ]); - const { data, notes } = applyClaudeManagedBlock(settings, { - baseUrl, - hookCommand, - }); - if (JSON.stringify(data) !== JSON.stringify(settings)) writeJson(file, data); - return notes; + const file = claudeSettingsFile(env); + const settings = readJson(file); + const cur = (settings.env as Record | undefined) + ?.ANTHROPIC_BASE_URL; + const baseUrl = claudeNativeBaseUrlForOrigin( + origin, + typeof cur === "string" ? unwrapBiliBaseUrl(cur) : undefined, + env, + ); + // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. + const hookCommand = portableHookCommand("node", [ + path.join(selfPackageRoot(), "dist", "claude-native-bootstrap.js"), + ]); + const { data, notes } = applyClaudeManagedBlock(settings, { + baseUrl, + hookCommand, + }); + if (JSON.stringify(data) !== JSON.stringify(settings)) writeJson(file, data); + return notes; } /** Pure merge of the #964 managed block into parsed settings (install path). @@ -719,75 +719,75 @@ export function repinClaudeManagedBaseUrl( * DISABLE_AUTO_COMPACT is reported and skipped, not overwritten. Returns the * mutated copy plus human notes. Exported for tests. */ export function applyClaudeManagedBlock( - settings: Record, - opts: { baseUrl: string; hookCommand: string }, + settings: Record, + opts: { baseUrl: string; hookCommand: string }, ): { data: Record; notes: string[] } { - const data = structuredClone(settings); - const notes: string[] = []; - const env = ( - data.env !== null && - typeof data.env === "object" && - !Array.isArray(data.env) - ? data.env - : {} - ) as Record; - const cur = env.ANTHROPIC_BASE_URL; - if (cur === undefined || cur === null || isBiliClaudeBaseUrl(cur)) { - if (cur !== opts.baseUrl) { - env.ANTHROPIC_BASE_URL = opts.baseUrl; - notes.push("env.ANTHROPIC_BASE_URL pinned to the bili proxy"); - } - } else { - notes.push( - `env.ANTHROPIC_BASE_URL left untouched (foreign value ${JSON.stringify(cur)} — unset it or set BILI_CLAUDE_UPSTREAM, then reinstall)`, - ); - } - const dac = env.DISABLE_AUTO_COMPACT; - if (dac === undefined || dac === null || dac === "1") { - if (dac !== "1") { - env.DISABLE_AUTO_COMPACT = "1"; - notes.push( - "env.DISABLE_AUTO_COMPACT=1 (bili owns compression; manual /compact survives)", - ); - } - } else { - notes.push( - `env.DISABLE_AUTO_COMPACT left untouched (foreign value ${JSON.stringify(dac)})`, - ); - } - if (Object.keys(env).length > 0) data.env = env; - - const hooks = ( - data.hooks !== null && - typeof data.hooks === "object" && - !Array.isArray(data.hooks) - ? data.hooks - : {} - ) as Record; - const sessionStart = Array.isArray(hooks.SessionStart) - ? hooks.SessionStart - : []; - if (!sessionStart.some(isOursSessionStartEntry)) { - sessionStart.push({ - hooks: [{ type: "command", command: opts.hookCommand }], - }); - hooks.SessionStart = sessionStart; - data.hooks = hooks; - notes.push("hooks.SessionStart += bili proxy bootstrap"); - } else if (refreshOurHookCommands(sessionStart, opts.hookCommand)) { - data.hooks = hooks; - notes.push("hooks.SessionStart refreshed to the current hook command"); - } - return { data, notes }; + const data = structuredClone(settings); + const notes: string[] = []; + const env = ( + data.env !== null && + typeof data.env === "object" && + !Array.isArray(data.env) + ? data.env + : {} + ) as Record; + const cur = env.ANTHROPIC_BASE_URL; + if (cur === undefined || cur === null || isBiliClaudeBaseUrl(cur)) { + if (cur !== opts.baseUrl) { + env.ANTHROPIC_BASE_URL = opts.baseUrl; + notes.push("env.ANTHROPIC_BASE_URL pinned to the bili proxy"); + } + } else { + notes.push( + `env.ANTHROPIC_BASE_URL left untouched (foreign value ${JSON.stringify(cur)} — unset it or set BILI_CLAUDE_UPSTREAM, then reinstall)`, + ); + } + const dac = env.DISABLE_AUTO_COMPACT; + if (dac === undefined || dac === null || dac === "1") { + if (dac !== "1") { + env.DISABLE_AUTO_COMPACT = "1"; + notes.push( + "env.DISABLE_AUTO_COMPACT=1 (bili owns compression; manual /compact survives)", + ); + } + } else { + notes.push( + `env.DISABLE_AUTO_COMPACT left untouched (foreign value ${JSON.stringify(dac)})`, + ); + } + if (Object.keys(env).length > 0) data.env = env; + + const hooks = ( + data.hooks !== null && + typeof data.hooks === "object" && + !Array.isArray(data.hooks) + ? data.hooks + : {} + ) as Record; + const sessionStart = Array.isArray(hooks.SessionStart) + ? hooks.SessionStart + : []; + if (!sessionStart.some(isOursSessionStartEntry)) { + sessionStart.push({ + hooks: [{ type: "command", command: opts.hookCommand }], + }); + hooks.SessionStart = sessionStart; + data.hooks = hooks; + notes.push("hooks.SessionStart += bili proxy bootstrap"); + } else if (refreshOurHookCommands(sessionStart, opts.hookCommand)) { + data.hooks = hooks; + notes.push("hooks.SessionStart refreshed to the current hook command"); + } + return { data, notes }; } /** A hook command naming our bootstrap script. Match on the script name * rather than the whole string: the emitted form changes across releases. */ function isOurHookCommand(command: unknown): command is string { - return ( - typeof command === "string" && - /claude-native-bootstrap\.(?:js|mjs|ts)["']?$/.test(command) - ); + return ( + typeof command === "string" && + /claude-native-bootstrap\.(?:js|mjs|ts)["']?$/.test(command) + ); } /** Rewrite every hook command we own to `command`, in place; true if any @@ -796,38 +796,38 @@ function isOurHookCommand(command: unknown): command is string { * command forever — and a command a client shell cannot run hangs every * session with no log to say why. */ function refreshOurHookCommands( - sessionStart: unknown[], - command: string, + sessionStart: unknown[], + command: string, ): boolean { - let changed = false; - for (const entry of sessionStart) { - if (!isOursSessionStartEntry(entry)) continue; - for (const h of (entry as { hooks: unknown[] }).hooks) { - const hook = h as { command?: unknown }; - const cur = hook.command; - if (isOurHookCommand(cur) && cur !== command) { - hook.command = command; - changed = true; - } - } - } - return changed; + let changed = false; + for (const entry of sessionStart) { + if (!isOursSessionStartEntry(entry)) continue; + for (const h of (entry as { hooks: unknown[] }).hooks) { + const hook = h as { command?: unknown }; + const cur = hook.command; + if (isOurHookCommand(cur) && cur !== command) { + hook.command = command; + changed = true; + } + } + } + return changed; } /** A SessionStart entry we wrote: any hook command naming our bootstrap * script (path may differ across installs/upgrades). */ export function isOursSessionStartEntry(entry: unknown): boolean { - const hooks = - entry !== null && typeof entry === "object" && !Array.isArray(entry) - ? (entry as { hooks?: unknown }).hooks - : undefined; - if (!Array.isArray(hooks)) return false; - return hooks.some( - (h) => - h !== null && - typeof h === "object" && - isOurHookCommand((h as { command?: unknown }).command), - ); + const hooks = + entry !== null && typeof entry === "object" && !Array.isArray(entry) + ? (entry as { hooks?: unknown }).hooks + : undefined; + if (!Array.isArray(hooks)) return false; + return hooks.some( + (h) => + h !== null && + typeof h === "object" && + isOurHookCommand((h as { command?: unknown }).command), + ); } /** Pure strip of the managed block (remove path) — returns the cleaned copy @@ -835,64 +835,64 @@ export function isOursSessionStartEntry(entry: unknown): boolean { * value we wrote ("1"); a .bili-bak with a pre-install value restores it in * the caller. Exported for tests. */ export function stripClaudeManagedBlock(settings: Record): { - data: Record; - removed: string[]; + data: Record; + removed: string[]; } { - const data = structuredClone(settings); - const removed: string[] = []; - const env = ( - data.env !== null && - typeof data.env === "object" && - !Array.isArray(data.env) - ? data.env - : undefined - ) as Record | undefined; - if (env !== undefined) { - if (isBiliClaudeBaseUrl(env.ANTHROPIC_BASE_URL)) { - delete env.ANTHROPIC_BASE_URL; - removed.push("env.ANTHROPIC_BASE_URL"); - } - if (env.DISABLE_AUTO_COMPACT === "1") { - delete env.DISABLE_AUTO_COMPACT; - removed.push("env.DISABLE_AUTO_COMPACT"); - } - if (Object.keys(env).length === 0) delete data.env; - } - const hooks = ( - data.hooks !== null && - typeof data.hooks === "object" && - !Array.isArray(data.hooks) - ? data.hooks - : undefined - ) as Record | undefined; - if (hooks !== undefined && Array.isArray(hooks.SessionStart)) { - const kept = (hooks.SessionStart as unknown[]).filter( - (e) => !isOursSessionStartEntry(e), - ); - if (kept.length !== (hooks.SessionStart as unknown[]).length) { - removed.push("hooks.SessionStart entry"); - if (kept.length > 0) hooks.SessionStart = kept; - else delete hooks.SessionStart; - if (Object.keys(hooks).length === 0) delete data.hooks; - } - } - return { data, removed }; + const data = structuredClone(settings); + const removed: string[] = []; + const env = ( + data.env !== null && + typeof data.env === "object" && + !Array.isArray(data.env) + ? data.env + : undefined + ) as Record | undefined; + if (env !== undefined) { + if (isBiliClaudeBaseUrl(env.ANTHROPIC_BASE_URL)) { + delete env.ANTHROPIC_BASE_URL; + removed.push("env.ANTHROPIC_BASE_URL"); + } + if (env.DISABLE_AUTO_COMPACT === "1") { + delete env.DISABLE_AUTO_COMPACT; + removed.push("env.DISABLE_AUTO_COMPACT"); + } + if (Object.keys(env).length === 0) delete data.env; + } + const hooks = ( + data.hooks !== null && + typeof data.hooks === "object" && + !Array.isArray(data.hooks) + ? data.hooks + : undefined + ) as Record | undefined; + if (hooks !== undefined && Array.isArray(hooks.SessionStart)) { + const kept = (hooks.SessionStart as unknown[]).filter( + (e) => !isOursSessionStartEntry(e), + ); + if (kept.length !== (hooks.SessionStart as unknown[]).length) { + removed.push("hooks.SessionStart entry"); + if (kept.length > 0) hooks.SessionStart = kept; + else delete hooks.SessionStart; + if (Object.keys(hooks).length === 0) delete data.hooks; + } + } + return { data, removed }; } /** True when the managed settings block (the static ANTHROPIC_BASE_URL) is * present — the `bili claude` launcher consults this to override the static * URL with its own ephemeral proxy (coexistence, #964 item 5). */ export function claudeNativeInstalled( - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = process.env, ): boolean { - try { - const data = readJson(claudeSettingsFile(env)); - return isBiliClaudeBaseUrl( - (data.env as Record | undefined)?.ANTHROPIC_BASE_URL, - ); - } catch { - return false; - } + try { + const data = readJson(claudeSettingsFile(env)); + return isBiliClaudeBaseUrl( + (data.env as Record | undefined)?.ANTHROPIC_BASE_URL, + ); + } catch { + return false; + } } // Windows: npm global shims are .cmd/.bat — direct spawn is EINVAL, so @@ -900,21 +900,21 @@ export function claudeNativeInstalled( // detectOpencodeMajor below). % is doubled because cmd.exe still expands // env vars inside quoted tokens. function runClaudeCli(claude: string, args: string[]): void { - if (process.platform === "win32" && /\.(cmd|bat)$/i.test(claude)) { - const q = (s: string) => `"${s.replaceAll("%", "%%")}"`; - execFileSync([claude, ...args].map(q).join(" "), { - shell: true, - stdio: ["ignore", "pipe", "pipe"], - timeout: CLAUDE_EXEC_TIMEOUT_MS, - windowsHide: true, - }); - } else { - execFileSync(claude, args, { - stdio: ["ignore", "pipe", "pipe"], - timeout: CLAUDE_EXEC_TIMEOUT_MS, - windowsHide: true, - }); - } + if (process.platform === "win32" && /\.(cmd|bat)$/i.test(claude)) { + const q = (s: string) => `"${s.replaceAll("%", "%%")}"`; + execFileSync([claude, ...args].map(q).join(" "), { + shell: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: CLAUDE_EXEC_TIMEOUT_MS, + windowsHide: true, + }); + } else { + execFileSync(claude, args, { + stdio: ["ignore", "pipe", "pipe"], + timeout: CLAUDE_EXEC_TIMEOUT_MS, + windowsHide: true, + }); + } } // CLAUDE overrides the claude binary path (absolute path for sandboxed @@ -934,251 +934,251 @@ function runClaudeCli(claude: string, args: string[]): void { * PATH order first, PATHEXT order within each directory. When nothing * carries a PATHEXT extension the old first-hit behavior stands. */ export function resolveClaudeCli( - claude: string, - where?: (name: string) => { stdout: string | null }, - pathext?: string, + claude: string, + where?: (name: string) => { stdout: string | null }, + pathext?: string, ): string { - if (/[\\/]/.test(claude) || /\.[a-z]+$/i.test(claude)) return claude; - const run = - where ?? (process.platform === "win32" ? defaultWhereRunner : undefined); - if (!run) return claude; - try { - const hits = (run(claude).stdout ?? "") - .split(/\r?\n/) - .map((l) => l.trim()) - .filter((l) => l.length > 0); - if (hits.length === 0) return claude; - const exts = (pathext ?? process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") - .split(";") - .map((e) => e.trim().toLowerCase()) - .filter((e) => e.startsWith(".")); - const dirs = new Map(); - for (const hit of hits) { - const base = /[^\\/]+$/.exec(hit)?.[0] ?? hit; - const dir = hit.slice(0, hit.length - base.length); - const list = dirs.get(dir) ?? []; - list.push(hit); - dirs.set(dir, list); - } - for (const perDir of dirs.values()) { - for (const ext of exts) { - const hit = perDir.find((h) => h.toLowerCase().endsWith(ext)); - if (hit) return hit; - } - } - return hits[0]; - } catch { - return claude; - } + if (/[\\/]/.test(claude) || /\.[a-z]+$/i.test(claude)) return claude; + const run = + where ?? (process.platform === "win32" ? defaultWhereRunner : undefined); + if (!run) return claude; + try { + const hits = (run(claude).stdout ?? "") + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => l.length > 0); + if (hits.length === 0) return claude; + const exts = (pathext ?? process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") + .split(";") + .map((e) => e.trim().toLowerCase()) + .filter((e) => e.startsWith(".")); + const dirs = new Map(); + for (const hit of hits) { + const base = /[^\\/]+$/.exec(hit)?.[0] ?? hit; + const dir = hit.slice(0, hit.length - base.length); + const list = dirs.get(dir) ?? []; + list.push(hit); + dirs.set(dir, list); + } + for (const perDir of dirs.values()) { + for (const ext of exts) { + const hit = perDir.find((h) => h.toLowerCase().endsWith(ext)); + if (hit) return hit; + } + } + return hits[0]; + } catch { + return claude; + } } function defaultWhereRunner(name: string): { stdout: string | null } { - const r = spawnSync("where.exe", [name], { - stdio: ["ignore", "pipe", "ignore"], - timeout: 5000, - encoding: "utf8", - windowsHide: true, - }); - return { stdout: r.stdout ?? null }; + const r = spawnSync("where.exe", [name], { + stdio: ["ignore", "pipe", "ignore"], + timeout: 5000, + encoding: "utf8", + windowsHide: true, + }); + return { stdout: r.stdout ?? null }; } function claudeInstall(): string { - if (process.env.BILI_NATIVE_CLAUDE === "0") { - throw new Error( - "claude: install refused — BILI_NATIVE_CLAUDE=0 is set (clear it to install the native posture)", - ); - } - const root = selfPackageRoot(); - const mcpJs = path.join(root, "dist", "mcp.js"); - const bootstrapJs = path.join(root, "dist", "claude-native-bootstrap.js"); - requireDistFile(mcpJs); - requireDistFile(bootstrapJs); - - // Managed block first: the static URL + bootstrap hook + compaction off. - // #964/#1660: the baked URL uses the explicit override - // (BILI_CLAUDE_NATIVE_PORT / claude.nativePort) when set — which also - // makes every later hook launch strict-port — else the current zone - // preference (sticky record > 18787 base). An explicit env-driven port - // can no longer desync from the hook: both resolve through - // resolveClaudeNativePort(), and the SessionStart hook's repin pass - // rewrites the baked URL to the live origin anyway (#1660). - const nativePort = resolveClaudeNativePort() ?? lanePreferredPort("claude"); - const file = claudeSettingsFile(); - const settings = readJson(file); - // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. - const hookCommand = portableHookCommand("node", [bootstrapJs]); - const { data, notes } = applyClaudeManagedBlock(settings, { - baseUrl: claudeNativeBaseUrl(), - hookCommand, - }); - writeJson(file, data); - - // MCP face: same registration path as before, but pinned to the STABLE - // port the hook brings up — never proxyOriginForInstall() (an ephemeral - // launcher proxy would go stale in this static config). - const stableOrigin = `http://127.0.0.1:${nativePort}`; - const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); - try { - runClaudeCli(claude, [ - "mcp", - "add", - "bili", - "--scope", - "user", - "-e", - `BILI_MCP_PROXY=${stableOrigin}`, - "--", - process.execPath, - mcpJs, - ]); - } catch (err) { - const stderr = - err instanceof Error && "stderr" in err - ? String((err as { stderr?: Buffer | string }).stderr ?? "") - : ""; - throw new Error( - `claude: MCP registration failed (${stderr.trim() || (err instanceof Error ? err.message : String(err))}) — is the claude CLI on PATH? (the managed settings block at ${file} was written; rerun after fixing the CLI to complete the MCP face)`, - ); - } - - let cmdNote: string; - const cmdFile = claudeAcpCacheCommandFile(); - try { - fs.mkdirSync(path.dirname(cmdFile), { recursive: true }); - const existing = fs.existsSync(cmdFile) - ? fs.readFileSync(cmdFile, "utf8") - : undefined; - if ( - existing === undefined || - existing.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd() - ) { - fs.writeFileSync(cmdFile, CLAUDE_ACP_CACHE_COMMAND); - cmdNote = `written`; - } else { - cmdNote = `left untouched (foreign content)`; - } - } catch (err) { - throw new Error( - `claude: /acp-cache command write failed (${err instanceof Error ? err.message : String(err)}) — the managed settings block at ${file} and the MCP face were written; fix the permissions and rerun`, - ); - } - return `claude: managed block -> ${file} (${notes.join("; ")}); /acp-cache command -> ${cmdFile} (${cmdNote}); MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin}) — restart claude to activate`; + if (process.env.BILI_NATIVE_CLAUDE === "0") { + throw new Error( + "claude: install refused — BILI_NATIVE_CLAUDE=0 is set (clear it to install the native posture)", + ); + } + const root = selfPackageRoot(); + const mcpJs = path.join(root, "dist", "mcp.js"); + const bootstrapJs = path.join(root, "dist", "claude-native-bootstrap.js"); + requireDistFile(mcpJs); + requireDistFile(bootstrapJs); + + // Managed block first: the static URL + bootstrap hook + compaction off. + // #964/#1660: the baked URL uses the explicit override + // (BILI_CLAUDE_NATIVE_PORT / claude.nativePort) when set — which also + // makes every later hook launch strict-port — else the current zone + // preference (sticky record > 18787 base). An explicit env-driven port + // can no longer desync from the hook: both resolve through + // resolveClaudeNativePort(), and the SessionStart hook's repin pass + // rewrites the baked URL to the live origin anyway (#1660). + const nativePort = resolveClaudeNativePort() ?? lanePreferredPort("claude"); + const file = claudeSettingsFile(); + const settings = readJson(file); + // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. + const hookCommand = portableHookCommand("node", [bootstrapJs]); + const { data, notes } = applyClaudeManagedBlock(settings, { + baseUrl: claudeNativeBaseUrl(), + hookCommand, + }); + writeJson(file, data); + + // MCP face: same registration path as before, but pinned to the STABLE + // port the hook brings up — never proxyOriginForInstall() (an ephemeral + // launcher proxy would go stale in this static config). + const stableOrigin = `http://127.0.0.1:${nativePort}`; + const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); + try { + runClaudeCli(claude, [ + "mcp", + "add", + "bili", + "--scope", + "user", + "-e", + `BILI_MCP_PROXY=${stableOrigin}`, + "--", + process.execPath, + mcpJs, + ]); + } catch (err) { + const stderr = + err instanceof Error && "stderr" in err + ? String((err as { stderr?: Buffer | string }).stderr ?? "") + : ""; + throw new Error( + `claude: MCP registration failed (${stderr.trim() || (err instanceof Error ? err.message : String(err))}) — is the claude CLI on PATH? (the managed settings block at ${file} was written; rerun after fixing the CLI to complete the MCP face)`, + ); + } + + let cmdNote: string; + const cmdFile = claudeAcpCacheCommandFile(); + try { + fs.mkdirSync(path.dirname(cmdFile), { recursive: true }); + const existing = fs.existsSync(cmdFile) + ? fs.readFileSync(cmdFile, "utf8") + : undefined; + if ( + existing === undefined || + existing.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd() + ) { + fs.writeFileSync(cmdFile, CLAUDE_ACP_CACHE_COMMAND); + cmdNote = `written`; + } else { + cmdNote = `left untouched (foreign content)`; + } + } catch (err) { + throw new Error( + `claude: /acp-cache command write failed (${err instanceof Error ? err.message : String(err)}) — the managed settings block at ${file} and the MCP face were written; fix the permissions and rerun`, + ); + } + return `claude: managed block -> ${file} (${notes.join("; ")}); /acp-cache command -> ${cmdFile} (${cmdNote}); MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin}) — restart claude to activate`; } function claudeRemove(): string { - const parts: string[] = []; - const file = claudeSettingsFile(); - const settings = readJson(file); - const { data, removed } = stripClaudeManagedBlock(settings); - if (removed.length > 0) { - // Restore a pre-install DISABLE_AUTO_COMPACT when the backup holds - // one (writeJson snapshotted the pristine file on first install). - const bak = `${file}.bili-bak`; - try { - if (fs.existsSync(bak)) { - const bakData = readJson(bak) as { env?: Record }; - const bakDac = bakData.env?.DISABLE_AUTO_COMPACT; - if ( - removed.includes("env.DISABLE_AUTO_COMPACT") && - bakDac !== undefined - ) { - const env = ( - data.env !== null && - typeof data.env === "object" && - !Array.isArray(data.env) - ? data.env - : {} - ) as Record; - env.DISABLE_AUTO_COMPACT = bakDac; - data.env = env; - } - } - } catch { - // unreadable backup — the value is simply dropped - } - writeJson(file, data); - parts.push(`managed block removed from ${file} (${removed.join(", ")})`); - } - if (claudeMcpInstalled()) { - const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); - try { - runClaudeCli(claude, ["mcp", "remove", "bili", "--scope", "user"]); - parts.push("MCP face removed"); - } catch (err) { - throw new Error( - `claude: MCP removal failed (${err instanceof Error ? err.message : String(err)})${parts.length > 0 ? ` — ${parts.join("; ")} succeeded first` : ""}`, - ); - } - } - const cmdFile = claudeAcpCacheCommandFile(); - try { - if (fs.existsSync(cmdFile)) { - const content = fs.readFileSync(cmdFile, "utf8"); - if (content.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd()) { - fs.unlinkSync(cmdFile); - parts.push("/acp-cache command removed"); - } else { - parts.push( - `/acp-cache command left untouched (${cmdFile} holds foreign content)`, - ); - } - } - } catch (err) { - parts.push( - `/acp-cache command removal skipped (${err instanceof Error ? err.message : String(err)})`, - ); - } - return parts.length > 0 - ? `claude: ${parts.join("; ")}` - : `claude: not installed (${file} / ${claudeMcpJson()})`; + const parts: string[] = []; + const file = claudeSettingsFile(); + const settings = readJson(file); + const { data, removed } = stripClaudeManagedBlock(settings); + if (removed.length > 0) { + // Restore a pre-install DISABLE_AUTO_COMPACT when the backup holds + // one (writeJson snapshotted the pristine file on first install). + const bak = `${file}.bili-bak`; + try { + if (fs.existsSync(bak)) { + const bakData = readJson(bak) as { env?: Record }; + const bakDac = bakData.env?.DISABLE_AUTO_COMPACT; + if ( + removed.includes("env.DISABLE_AUTO_COMPACT") && + bakDac !== undefined + ) { + const env = ( + data.env !== null && + typeof data.env === "object" && + !Array.isArray(data.env) + ? data.env + : {} + ) as Record; + env.DISABLE_AUTO_COMPACT = bakDac; + data.env = env; + } + } + } catch { + // unreadable backup — the value is simply dropped + } + writeJson(file, data); + parts.push(`managed block removed from ${file} (${removed.join(", ")})`); + } + if (claudeMcpInstalled()) { + const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); + try { + runClaudeCli(claude, ["mcp", "remove", "bili", "--scope", "user"]); + parts.push("MCP face removed"); + } catch (err) { + throw new Error( + `claude: MCP removal failed (${err instanceof Error ? err.message : String(err)})${parts.length > 0 ? ` — ${parts.join("; ")} succeeded first` : ""}`, + ); + } + } + const cmdFile = claudeAcpCacheCommandFile(); + try { + if (fs.existsSync(cmdFile)) { + const content = fs.readFileSync(cmdFile, "utf8"); + if (content.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd()) { + fs.unlinkSync(cmdFile); + parts.push("/acp-cache command removed"); + } else { + parts.push( + `/acp-cache command left untouched (${cmdFile} holds foreign content)`, + ); + } + } + } catch (err) { + parts.push( + `/acp-cache command removal skipped (${err instanceof Error ? err.message : String(err)})`, + ); + } + return parts.length > 0 + ? `claude: ${parts.join("; ")}` + : `claude: not installed (${file} / ${claudeMcpJson()})`; } function claudeMcpInstalled(): boolean { - const data = readJson(claudeMcpJson()) as { - mcpServers?: Record; - }; - return isPlainMcpObject(data.mcpServers) && "bili" in data.mcpServers; + const data = readJson(claudeMcpJson()) as { + mcpServers?: Record; + }; + return isPlainMcpObject(data.mcpServers) && "bili" in data.mcpServers; } function claudeStatus(): string { - let block = false; - try { - const data = readJson(claudeSettingsFile()); - block = isBiliClaudeBaseUrl( - (data.env as Record | undefined)?.ANTHROPIC_BASE_URL, - ); - } catch { - block = false; - } - const mcp = (() => { - try { - return claudeMcpInstalled(); - } catch { - return false; - } - })(); - if (block && mcp) return "installed (managed settings block + MCP)"; - if (block) - return "installed (managed settings block; MCP face missing — rerun install)"; - if (mcp) - return "installed (MCP only — legacy companion posture; rerun install for the native block)"; - return "not installed"; + let block = false; + try { + const data = readJson(claudeSettingsFile()); + block = isBiliClaudeBaseUrl( + (data.env as Record | undefined)?.ANTHROPIC_BASE_URL, + ); + } catch { + block = false; + } + const mcp = (() => { + try { + return claudeMcpInstalled(); + } catch { + return false; + } + })(); + if (block && mcp) return "installed (managed settings block + MCP)"; + if (block) + return "installed (managed settings block; MCP face missing — rerun install)"; + if (mcp) + return "installed (MCP only — legacy companion posture; rerun install for the native block)"; + return "not installed"; } // — codex —————————————————————————————————————————————————————————————— function codexToml(): string { - const raw = process.env.CODEX_HOME?.trim(); - if (raw && raw.length > 0) return path.join(raw, "config.toml"); - return homeFile(".codex/config.toml"); + const raw = process.env.CODEX_HOME?.trim(); + if (raw && raw.length > 0) return path.join(raw, "config.toml"); + return homeFile(".codex/config.toml"); } function codexBlock(): string { - // #1660: no baked origin — the MCP shell discovers the live proxy at - // startup (env > live instance file > 8787 user-zone default), so the - // block never goes stale when the proxy's port drifts or the machine - // reboots. BILI_MCP_PROXY in the user's environment still wins. - return `\n[mcp_servers.bili]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(path.join(selfPackageRoot(), "dist", "mcp.js"))}]\n`; + // #1660: no baked origin — the MCP shell discovers the live proxy at + // startup (env > live instance file > 8787 user-zone default), so the + // block never goes stale when the proxy's port drifts or the machine + // reboots. BILI_MCP_PROXY in the user's environment still wins. + return `\n[mcp_servers.bili]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(path.join(selfPackageRoot(), "dist", "mcp.js"))}]\n`; } /** Force every line ending in `text` to the convention `reference` already @@ -1188,12 +1188,12 @@ function codexBlock(): string { * (src/kimi/toml-edit.ts:21, src/launcher.ts:2466): never convert the user's * file, never mix endings into it. */ function normalizeCodexEol(text: string, reference: string): string { - const lf = text.replace(/\r\n/g, "\n"); - return reference.includes("\r\n") ? lf.replace(/\n/g, "\r\n") : lf; + const lf = text.replace(/\r\n/g, "\n"); + return reference.includes("\r\n") ? lf.replace(/\n/g, "\r\n") : lf; } function malformedCodexArgs(block: string): boolean { - return /^[ \t]*args[ \t]*=[ \t]*["']/m.test(block); + return /^[ \t]*args[ \t]*=[ \t]*["']/m.test(block); } /** The model-route face of the codex lane (ticket 01). Distinct from the MCP @@ -1202,68 +1202,68 @@ function malformedCodexArgs(block: string): boolean { * (codex-integration/route.ts) so a user- or CC-Switch-owned * `openai_base_url` is never overwritten — a conflict is REPORTED instead. */ function codexRouteSync( - text: string, - file: string, + text: string, + file: string, ): { - text: string; - note: string; - conflicted: boolean; - record?: ReturnType; + text: string; + note: string; + conflicted: boolean; + record?: ReturnType; } { - const recordPath = codexRouteRecordPath(file); - const previous = readCodexRouteRecord(recordPath); - const defaultHomeConfig = - path.resolve(file).toLowerCase() === - path - .resolve(path.join(os.homedir(), ".codex", "config.toml")) - .toLowerCase(); - const ccSwitchMode = defaultHomeConfig ? detectCcSwitch().mode : "unknown"; - const plan = planCodexRoute(text, { - origin: codexRouteOrigin(process.env), - ownedValue: previous?.writtenValue, - ownedRecord: previous, - ccSwitchMode, - }); - if (plan.action === "keep") - return { - text, - note: `model route: ${plan.note}`, - conflicted: false, - record: previous, - }; - if (plan.action === "conflict") - return { - text, - note: `model route: ${plan.note}`, - conflicted: true, - record: previous, - }; - const value = plan.value!; - const route = value.slice(value.indexOf("/bili/") + "/bili/".length); - const target = plan.target ?? { kind: "top-level" as const }; - const previousTarget = previous?.target ?? { kind: "top-level" as const }; - const targetMatches = - previousTarget.kind === target.kind && - (target.kind === "top-level" || - (previousTarget.kind === "provider" && - previousTarget.provider === target.provider)); - const previousValue = targetMatches - ? (previous?.previousValue ?? null) - : target.kind === "provider" - ? (parseCodexToml(text).providers?.[target.provider]?.baseUrl ?? null) - : (parseCodexToml(text).openaiBaseUrl ?? null); - return { - text: plan.text, - note: `model route: ${plan.note}`, - conflicted: false, - record: { - schemaVersion: 1, - writtenValue: value, - previousValue, - upstream: route, - target, - }, - }; + const recordPath = codexRouteRecordPath(file); + const previous = readCodexRouteRecord(recordPath); + const defaultHomeConfig = + path.resolve(file).toLowerCase() === + path + .resolve(path.join(os.homedir(), ".codex", "config.toml")) + .toLowerCase(); + const ccSwitchMode = defaultHomeConfig ? detectCcSwitch().mode : "unknown"; + const plan = planCodexRoute(text, { + origin: codexRouteOrigin(process.env), + ownedValue: previous?.writtenValue, + ownedRecord: previous, + ccSwitchMode, + }); + if (plan.action === "keep") + return { + text, + note: `model route: ${plan.note}`, + conflicted: false, + record: previous, + }; + if (plan.action === "conflict") + return { + text, + note: `model route: ${plan.note}`, + conflicted: true, + record: previous, + }; + const value = plan.value!; + const route = value.slice(value.indexOf("/bili/") + "/bili/".length); + const target = plan.target ?? { kind: "top-level" as const }; + const previousTarget = previous?.target ?? { kind: "top-level" as const }; + const targetMatches = + previousTarget.kind === target.kind && + (target.kind === "top-level" || + (previousTarget.kind === "provider" && + previousTarget.provider === target.provider)); + const previousValue = targetMatches + ? (previous?.previousValue ?? null) + : target.kind === "provider" + ? (parseCodexToml(text).providers?.[target.provider]?.baseUrl ?? null) + : (parseCodexToml(text).openaiBaseUrl ?? null); + return { + text: plan.text, + note: `model route: ${plan.note}`, + conflicted: false, + record: { + schemaVersion: 1, + writtenValue: value, + previousValue, + upstream: route, + target, + }, + }; } /** The SessionStart-hook face of the codex lane (ticket 08). Codex reads @@ -1272,46 +1272,46 @@ function codexRouteSync( * (codex-integration/hooks.ts). A foreign hook table is REPORTED, never * rewritten — same ownership rule as the model route. */ function codexHookSync( - text: string, - warn: (message: string) => void, + text: string, + warn: (message: string) => void, ): { text: string; note: string; changed: boolean } { - const root = selfPackageRoot(); - const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); - if (!fs.existsSync(hookScript)) { - warn( - `codex: hook script missing at ${hookScript} — skipping the SessionStart hook face (rebuild bili)`, - ); - return { - text, - note: "hook: skipped (dist/codex/bootstrap-hook.js missing)", - changed: false, - }; - } - const command = portableHookCommand("node", [hookScript]); - const plan = planCodexHook(text, command); - const shape = assertCodexConfigLoads(plan.text); - if (shape !== undefined) { - warn(`codex: ${shape} — SessionStart hook NOT written`); - return { - text, - note: `hook: skipped (${shape})`, - changed: false, - }; - } - const featureNote = codexHooksEnabledNote(plan.text); - if (featureNote !== "" && plan.action !== "keep") - warn( - `codex: SessionStart hook written, but hook execution is not enabled — ${featureNote}`, - ); - const note = - featureNote === "" - ? `hook: ${plan.note}` - : `hook: ${plan.note} — ${featureNote}`; - return { - text: plan.text, - note, - changed: plan.action !== "keep", - }; + const root = selfPackageRoot(); + const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); + if (!fs.existsSync(hookScript)) { + warn( + `codex: hook script missing at ${hookScript} — skipping the SessionStart hook face (rebuild bili)`, + ); + return { + text, + note: "hook: skipped (dist/codex/bootstrap-hook.js missing)", + changed: false, + }; + } + const command = portableHookCommand("node", [hookScript]); + const plan = planCodexHook(text, command); + const shape = assertCodexConfigLoads(plan.text); + if (shape !== undefined) { + warn(`codex: ${shape} — SessionStart hook NOT written`); + return { + text, + note: `hook: skipped (${shape})`, + changed: false, + }; + } + const featureNote = codexHooksEnabledNote(plan.text); + if (featureNote !== "" && plan.action !== "keep") + warn( + `codex: SessionStart hook written, but hook execution is not enabled — ${featureNote}`, + ); + const note = + featureNote === "" + ? `hook: ${plan.note}` + : `hook: ${plan.note} — ${featureNote}`; + return { + text: plan.text, + note, + changed: plan.action !== "keep", + }; } /** The ACP-skill face of the codex lane (ticket 08): `/skills/bili/ @@ -1319,12 +1319,12 @@ function codexHookSync( * THIRD face next to mcp/hook, because a skill changes what the model does, * not whether traffic is compressed. */ function codexSkillSync(warn: (message: string) => void): { - note: string; - changed: boolean; + note: string; + changed: boolean; } { - const result = installCodexSkill(process.env); - if (result.state === "foreign") warn(`codex: ${result.note}`); - return { note: `skill: ${result.note}`, changed: result.written }; + const result = installCodexSkill(process.env); + if (result.state === "foreign") warn(`codex: ${result.note}`); + return { note: `skill: ${result.note}`, changed: result.written }; } /** Best-effort service hook for `bili plugin install|remove `. @@ -1342,39 +1342,39 @@ function codexSkillSync(warn: (message: string) => void): { * That keeps this hook from turning a successful config install into a * reported failure. */ async function serviceSync( - action: "install" | "remove", + action: "install" | "remove", ): Promise<{ note: string; warning?: string }> { - try { - const result = - action === "install" - ? await installProxyService() - : await removeProxyService(); - if (result.ok) - return { - note: - result.action === "already-installed" - ? "service: already registered" - : action === "install" - ? "service: registered for logon + started" - : "service: removed", - }; - if (result.action === "already-absent") - return { note: "service: none registered" }; - if (result.action === "unsupported") - return { - note: "service: not applicable", - warning: `${result.message}; start the proxy yourself with \`bili start\``, - }; - return { - note: "service: NOT registered", - warning: `${result.message}; start the proxy yourself with \`bili start\``, - }; - } catch (error) { - return { - note: "service: NOT registered", - warning: `service registration failed (${error instanceof Error ? error.message : String(error)}); start the proxy yourself with \`bili start\``, - }; - } + try { + const result = + action === "install" + ? await installProxyService() + : await removeProxyService(); + if (result.ok) + return { + note: + result.action === "already-installed" + ? "service: already registered" + : action === "install" + ? "service: registered for logon + started" + : "service: removed", + }; + if (result.action === "already-absent") + return { note: "service: none registered" }; + if (result.action === "unsupported") + return { + note: "service: not applicable", + warning: `${result.message}; start the proxy yourself with \`bili start\``, + }; + return { + note: "service: NOT registered", + warning: `${result.message}; start the proxy yourself with \`bili start\``, + }; + } catch (error) { + return { + note: "service: NOT registered", + warning: `service registration failed (${error instanceof Error ? error.message : String(error)}); start the proxy yourself with \`bili start\``, + }; + } } /** `bili plugin install codex`: the config faces PLUS the service face. @@ -1382,173 +1382,173 @@ async function serviceSync( * (and unit-testable without a live scheduler/bus); the CLI layer awaits this * one and prints a single line. */ export async function codexInstallWithService(): Promise { - const base = codexInstall(); - const service = await serviceSync("install"); - return service.warning !== undefined - ? `${base}; ${service.note}\n ! ${service.warning}` - : `${base}; ${service.note}`; + const base = codexInstall(); + const service = await serviceSync("install"); + return service.warning !== undefined + ? `${base}; ${service.note}\n ! ${service.warning}` + : `${base}; ${service.note}`; } /** `bili plugin remove codex`: config faces plus service teardown, so an * uninstall does not leave a proxy running behind the user's back. */ export async function codexRemoveWithService(): Promise { - const base = codexRemove(); - const service = await serviceSync("remove"); - return service.warning !== undefined - ? `${base}; ${service.note}\n ! ${service.warning}` - : `${base}; ${service.note}`; + const base = codexRemove(); + const service = await serviceSync("remove"); + return service.warning !== undefined + ? `${base}; ${service.note}\n ! ${service.warning}` + : `${base}; ${service.note}`; } function codexInstall(): string { - const file = codexToml(); - const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; - const warnings: string[] = []; - const warn = (message: string): void => { - warnings.push(message); - }; - const existing = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text); - let next = text; - let mcpNote: string; - if (existing !== null) { - // End the block at the next TABLE header line (optional indent + `[`), - // matching codexRemove. A plain indexOf("\n[") misses an indented next - // table and lets the block run to EOF, deleting everything after it. - const after = text.slice(existing.index); - const firstNewline = after.indexOf("\n"); - const nextTable = - firstNewline < 0 - ? -1 - : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); - const blockEnd = - nextTable >= 0 - ? existing.index + firstNewline + 1 + nextTable - : text.length; - const block = text.slice(existing.index, blockEnd); - const canonical = codexBlock().replace(/^\n/, ""); - if (block.trimEnd() === canonical.trimEnd()) { - mcpNote = "mcp: already installed"; - } else { - next = - text.slice(0, existing.index) + - canonical + - text.slice(existing.index + block.length); - mcpNote = `mcp: refreshed [mcp_servers.bili]${malformedCodexArgs(block) ? " (repaired args: was not an array)" : ""}`; - } - } else { - fs.mkdirSync(path.dirname(file), { recursive: true }); - next = - text + - (text.endsWith("\n") || text.length === 0 ? "" : "\n") + - codexBlock(); - mcpNote = "mcp: installed [mcp_servers.bili]"; - } - const route = codexRouteSync(next, file); - next = route.text; - const hook = codexHookSync(next, warn); - next = hook.text; - const skill = codexSkillSync(warn); - // Single write exit: every renderer above emits "\n", so normalize once - // against the file we started from. Without this a CRLF config (the norm on - // Windows) came back with a mixed-ending bili block spliced in. - const finalText = normalizeCodexEol(next, text); - if ( - finalText === text && - existing !== null && - mcpNote === "mcp: already installed" && - !hook.changed && - !skill.changed - ) { - return `codex: already installed (${file}) — ${mcpNote}; ${route.note}; ${hook.note}; ${skill.note}`; - } - writeConfigText(file, finalText); - if (route.record !== undefined) - writeCodexRouteRecord(codexRouteRecordPath(file), route.record); - const conflictNote = route.conflicted ? " (NOT routed — see note)" : ""; - const detail = `${mcpNote}; ${route.note}${conflictNote}; ${hook.note}; ${skill.note}`; - const tail = - warnings.length > 0 - ? `\n${warnings.map((w) => ` ! ${w}`).join("\n")}` - : ""; - if (mcpNote.startsWith("mcp: refreshed")) - return `codex: refreshed [mcp_servers.bili] -> ${file} — ${detail}${tail}`; - if (mcpNote.startsWith("mcp: installed")) - return `codex: installed -> ${file} — ${detail}${tail}`; - return `codex: refreshed -> ${file} — ${detail}${tail}`; + const file = codexToml(); + const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + const warnings: string[] = []; + const warn = (message: string): void => { + warnings.push(message); + }; + const existing = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text); + let next = text; + let mcpNote: string; + if (existing !== null) { + // End the block at the next TABLE header line (optional indent + `[`), + // matching codexRemove. A plain indexOf("\n[") misses an indented next + // table and lets the block run to EOF, deleting everything after it. + const after = text.slice(existing.index); + const firstNewline = after.indexOf("\n"); + const nextTable = + firstNewline < 0 + ? -1 + : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); + const blockEnd = + nextTable >= 0 + ? existing.index + firstNewline + 1 + nextTable + : text.length; + const block = text.slice(existing.index, blockEnd); + const canonical = codexBlock().replace(/^\n/, ""); + if (block.trimEnd() === canonical.trimEnd()) { + mcpNote = "mcp: already installed"; + } else { + next = + text.slice(0, existing.index) + + canonical + + text.slice(existing.index + block.length); + mcpNote = `mcp: refreshed [mcp_servers.bili]${malformedCodexArgs(block) ? " (repaired args: was not an array)" : ""}`; + } + } else { + fs.mkdirSync(path.dirname(file), { recursive: true }); + next = + text + + (text.endsWith("\n") || text.length === 0 ? "" : "\n") + + codexBlock(); + mcpNote = "mcp: installed [mcp_servers.bili]"; + } + const route = codexRouteSync(next, file); + next = route.text; + const hook = codexHookSync(next, warn); + next = hook.text; + const skill = codexSkillSync(warn); + // Single write exit: every renderer above emits "\n", so normalize once + // against the file we started from. Without this a CRLF config (the norm on + // Windows) came back with a mixed-ending bili block spliced in. + const finalText = normalizeCodexEol(next, text); + if ( + finalText === text && + existing !== null && + mcpNote === "mcp: already installed" && + !hook.changed && + !skill.changed + ) { + return `codex: already installed (${file}) — ${mcpNote}; ${route.note}; ${hook.note}; ${skill.note}`; + } + writeConfigText(file, finalText); + if (route.record !== undefined) + writeCodexRouteRecord(codexRouteRecordPath(file), route.record); + const conflictNote = route.conflicted ? " (NOT routed — see note)" : ""; + const detail = `${mcpNote}; ${route.note}${conflictNote}; ${hook.note}; ${skill.note}`; + const tail = + warnings.length > 0 + ? `\n${warnings.map((w) => ` ! ${w}`).join("\n")}` + : ""; + if (mcpNote.startsWith("mcp: refreshed")) + return `codex: refreshed [mcp_servers.bili] -> ${file} — ${detail}${tail}`; + if (mcpNote.startsWith("mcp: installed")) + return `codex: installed -> ${file} — ${detail}${tail}`; + return `codex: refreshed -> ${file} — ${detail}${tail}`; } function codexRemove(): string { - const file = codexToml(); - const skill = removeCodexSkill(process.env); - if (!fs.existsSync(file)) - return `codex: not installed (${file}) — skill: ${skill.note}`; - const text = fs.readFileSync(file, "utf8"); - const routeRecordPath = codexRouteRecordPath(file); - const routeRecord = readCodexRouteRecord(routeRecordPath); - const restoredRoute = restoreCodexRoute(text, routeRecord); - const hook = stripCodexHook(restoredRoute.text); - const stripped = hook.text; - const start = (() => { - const m = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(stripped); - return m === null ? -1 : m.index; - })(); - const faces = [ - hook.removed ? "hook removed" : "no hook", - `skill: ${skill.removed ? "removed" : skill.note}`, - ]; - if (start < 0) { - if (stripped === text) - return `codex: not installed (${file}) — ${faces.join("; ")}`; - writeConfigText(file, stripped); - removeCodexRouteRecord(routeRecordPath); - return `codex: model route restored from ${file} (no MCP block present) — ${faces.join("; ")}`; - } - const lineStart = stripped.lastIndexOf("\n", start - 1) + 1; - const after = stripped.slice(start); - const firstNewline = after.indexOf("\n"); - const nextTable = - firstNewline < 0 ? -1 : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); - const end = - nextTable >= 0 ? start + firstNewline + 1 + nextTable : stripped.length; - const cleaned = ( - stripped.slice(0, lineStart).replace(/\n+$/, "\n") + stripped.slice(end) - ).replace(/^\n+/, ""); - writeConfigText(file, cleaned); - removeCodexRouteRecord(routeRecordPath); - return `codex: removed from ${file} — ${faces.join("; ")}`; + const file = codexToml(); + const skill = removeCodexSkill(process.env); + if (!fs.existsSync(file)) + return `codex: not installed (${file}) — skill: ${skill.note}`; + const text = fs.readFileSync(file, "utf8"); + const routeRecordPath = codexRouteRecordPath(file); + const routeRecord = readCodexRouteRecord(routeRecordPath); + const restoredRoute = restoreCodexRoute(text, routeRecord); + const hook = stripCodexHook(restoredRoute.text); + const stripped = hook.text; + const start = (() => { + const m = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(stripped); + return m === null ? -1 : m.index; + })(); + const faces = [ + hook.removed ? "hook removed" : "no hook", + `skill: ${skill.removed ? "removed" : skill.note}`, + ]; + if (start < 0) { + if (stripped === text) + return `codex: not installed (${file}) — ${faces.join("; ")}`; + writeConfigText(file, stripped); + removeCodexRouteRecord(routeRecordPath); + return `codex: model route restored from ${file} (no MCP block present) — ${faces.join("; ")}`; + } + const lineStart = stripped.lastIndexOf("\n", start - 1) + 1; + const after = stripped.slice(start); + const firstNewline = after.indexOf("\n"); + const nextTable = + firstNewline < 0 ? -1 : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); + const end = + nextTable >= 0 ? start + firstNewline + 1 + nextTable : stripped.length; + const cleaned = ( + stripped.slice(0, lineStart).replace(/\n+$/, "\n") + stripped.slice(end) + ).replace(/^\n+/, ""); + writeConfigText(file, cleaned); + removeCodexRouteRecord(routeRecordPath); + return `codex: removed from ${file} — ${faces.join("; ")}`; } function codexStatus(): string { - const file = codexToml(); - const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; - const mcp = /^\[mcp_servers\.bili\]\s*$/m.test(text); - const owned = readCodexRouteRecord(codexRouteRecordPath(file)); - const route = readCodexRoute(text, owned); - const routeText = - route.conflict !== undefined - ? `route blocked (${route.conflict.kind})` - : route.routed - ? route.value === desiredCodexRoute(text, codexRouteOrigin(process.env)) - ? "route installed" - : `route drifted (${route.value})` - : "route not installed"; - const hookInstalled = findBiliCodexHook(text) !== undefined; - const hookText = hookInstalled - ? codexHooksEnabledNote(text) === "" - ? "hook installed" - : `hook installed but disabled (${codexHooksEnabledNote(text)})` - : "hook not installed"; - const skillState = codexSkillStatus(process.env); - const skillText = - skillState === "installed" - ? "skill installed" - : skillState === "outdated" - ? "skill outdated (rerun install)" - : skillState === "foreign" - ? "skill not ours (left untouched)" - : "skill not installed"; - if (!mcp && !route.routed && !hookInstalled && skillState !== "installed") - return "not installed"; - return `${mcp ? "mcp installed" : "mcp missing"}; ${routeText}; ${hookText}; ${skillText}`; + const file = codexToml(); + const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + const mcp = /^\[mcp_servers\.bili\]\s*$/m.test(text); + const owned = readCodexRouteRecord(codexRouteRecordPath(file)); + const route = readCodexRoute(text, owned); + const routeText = + route.conflict !== undefined + ? `route blocked (${route.conflict.kind})` + : route.routed + ? route.value === desiredCodexRoute(text, codexRouteOrigin(process.env)) + ? "route installed" + : `route drifted (${route.value})` + : "route not installed"; + const hookInstalled = findBiliCodexHook(text) !== undefined; + const hookText = hookInstalled + ? codexHooksEnabledNote(text) === "" + ? "hook installed" + : `hook installed but disabled (${codexHooksEnabledNote(text)})` + : "hook not installed"; + const skillState = codexSkillStatus(process.env); + const skillText = + skillState === "installed" + ? "skill installed" + : skillState === "outdated" + ? "skill outdated (rerun install)" + : skillState === "foreign" + ? "skill not ours (left untouched)" + : "skill not installed"; + if (!mcp && !route.routed && !hookInstalled && skillState !== "installed") + return "not installed"; + return `${mcp ? "mcp installed" : "mcp missing"}; ${routeText}; ${hookText}; ${skillText}`; } // — opencode ———————————————————————————————————————————————————————————— @@ -1560,7 +1560,7 @@ function codexStatus(): string { // back to major 1, whose key (`plugin`) 2.x still honors as a legacy alias, // so degradation can never write a dead config line. export function pickPluginKey(major: number): "plugin" | "plugins" { - return major >= 2 ? "plugins" : "plugin"; + return major >= 2 ? "plugins" : "plugin"; } const PLUGIN_KEYS = ["plugin", "plugins"] as const; @@ -1570,47 +1570,47 @@ const ocMajorCache = new Map(); /** Host major version via ` --version` (probe failure → 1). Same * contract as the launcher's probe; honors the BILI_CLIENT_BIN override. */ export function detectOpencodeMajor(): number { - const command = process.env.BILI_CLIENT_BIN?.trim() || "opencode"; - const hit = ocMajorCache.get(command); - if (hit !== undefined) return hit; - let major = 1; - try { - // Windows: npm global shims are .cmd/.bat — execFileSync cannot spawn - // those directly (EINVAL), so route through the shell with explicit - // quoting. Plain exes and POSIX shebang scripts go straight through. - const viaShell = - process.platform === "win32" && /\.(cmd|bat)$/i.test(command); - const out = viaShell - ? execFileSync(`"${command}" --version`, { - shell: true, - timeout: 5000, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }) - : execFileSync(command, ["--version"], { - timeout: 5000, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }); - const m = /(\d+)\s*\./.exec(out); - if (m) major = parseInt(m[1], 10); - } catch (error) { - // Version probing is advisory; the caller falls back to the conservative major. - void error; - } - ocMajorCache.set(command, major); - return major; + const command = process.env.BILI_CLIENT_BIN?.trim() || "opencode"; + const hit = ocMajorCache.get(command); + if (hit !== undefined) return hit; + let major = 1; + try { + // Windows: npm global shims are .cmd/.bat — execFileSync cannot spawn + // those directly (EINVAL), so route through the shell with explicit + // quoting. Plain exes and POSIX shebang scripts go straight through. + const viaShell = + process.platform === "win32" && /\.(cmd|bat)$/i.test(command); + const out = viaShell + ? execFileSync(`"${command}" --version`, { + shell: true, + timeout: 5000, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }) + : execFileSync(command, ["--version"], { + timeout: 5000, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }); + const m = /(\d+)\s*\./.exec(out); + if (m) major = parseInt(m[1], 10); + } catch (error) { + // Version probing is advisory; the caller falls back to the conservative major. + void error; + } + ocMajorCache.set(command, major); + return major; } function pluginEntries(data: Record, key: string): string[] { - const v = data[key]; - if (Array.isArray(v)) - return v.filter((x): x is string => typeof x === "string"); - if (v !== null && typeof v === "object") - return Object.keys(v as Record); - return []; + const v = data[key]; + if (Array.isArray(v)) + return v.filter((x): x is string => typeof x === "string"); + if (v !== null && typeof v === "object") + return Object.keys(v as Record); + return []; } // #927: write target = explicit OPENCODE_CONFIG override, else the @@ -1619,41 +1619,41 @@ function pluginEntries(data: Record, key: string): string[] { // opencode.json. Never spawn a second file next to an existing config — that // splits one logical config across files (#927). function opencodeTargetFile(): string { - const raw = process.env.OPENCODE_CONFIG?.trim(); - if (raw && raw.length > 0) return raw; - const xdg = process.env.XDG_CONFIG_HOME?.trim(); - const dir = - xdg && xdg.length > 0 - ? path.join(xdg, "opencode") - : path.join(os.homedir(), ".config", "opencode"); - for (const name of ["opencode.jsonc", "opencode.json", "config.json"]) { - const p = path.join(dir, name); - if (fs.existsSync(p)) return p; - } - return path.join(dir, "opencode.json"); + const raw = process.env.OPENCODE_CONFIG?.trim(); + if (raw && raw.length > 0) return raw; + const xdg = process.env.XDG_CONFIG_HOME?.trim(); + const dir = + xdg && xdg.length > 0 + ? path.join(xdg, "opencode") + : path.join(os.homedir(), ".config", "opencode"); + for (const name of ["opencode.jsonc", "opencode.json", "config.json"]) { + const p = path.join(dir, name); + if (fs.existsSync(p)) return p; + } + return path.join(dir, "opencode.json"); } // #820 native mode: OpenCode 2.x rejects bare FILE paths in `plugin` — the // entry must be a DIRECTORY whose index.js is the entrypoint (#754 probe). The // wrapper directory lives next to the config so it survives config moves. function opencodePluginDir(configFile: string): string { - return path.join(path.dirname(configFile), "plugins", "billion-context"); + return path.join(path.dirname(configFile), "plugins", "billion-context"); } // #809/N4: opencode.json may carry a non-object `mcp` (e.g. a bare string); // `"bili" in ` throws TypeError. Guard so install/remove/status // degrade gracefully instead of crashing (a crashing remove leaves no cleanup). function isPlainMcpObject(v: unknown): v is Record { - return v !== null && typeof v === "object" && !Array.isArray(v); + return v !== null && typeof v === "object" && !Array.isArray(v); } function readOriginalText(file: string): string { - try { - return fs.readFileSync(file, "utf8"); - } catch (err) { - if ((err as { code?: string }).code === "ENOENT") return ""; - throw err; - } + try { + return fs.readFileSync(file, "utf8"); + } catch (err) { + if ((err as { code?: string }).code === "ENOENT") return ""; + throw err; + } } // JSONC-tolerant parse: the target may be an opencode.jsonc carrying comments @@ -1662,35 +1662,35 @@ function readOriginalText(file: string): string { // is bounded: ANY diagnostic beyond comments/trailing commas means the file // is broken, and a broken config is never overwritten (§7.3). function parseOpencodeConfig( - text: string, - file: string, + text: string, + file: string, ): Record { - const errors: ParseError[] = []; - const parsed = jsoncParse(text, errors, { allowTrailingComma: true }); - if (errors.length > 0 || parsed === undefined) { - const first = errors[0]; - const detail = first ? ` (offset ${first.offset})` : ""; - throw new Error( - `${file}: not valid JSON${detail} — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`, - ); - } - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { - throw new Error( - `${file}: expected a JSON object at top level, refusing to overwrite`, - ); - } - return parsed as Record; + const errors: ParseError[] = []; + const parsed = jsoncParse(text, errors, { allowTrailingComma: true }); + if (errors.length > 0 || parsed === undefined) { + const first = errors[0]; + const detail = first ? ` (offset ${first.offset})` : ""; + throw new Error( + `${file}: not valid JSON${detail} — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`, + ); + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error( + `${file}: expected a JSON object at top level, refusing to overwrite`, + ); + } + return parsed as Record; } function loadOpencodeConfig(file: string): { - original: string; - data: Record; + original: string; + data: Record; } { - const original = readOriginalText(file); - return { - original, - data: original === "" ? {} : parseOpencodeConfig(original, file), - }; + const original = readOriginalText(file); + return { + original, + data: original === "" ? {} : parseOpencodeConfig(original, file), + }; } // Write back preserving everything bili did not touch: a missing or plain-JSON @@ -1698,38 +1698,38 @@ function loadOpencodeConfig(file: string): { // surgical top-level-key edits so comments and formatting elsewhere survive // byte-for-byte (#927). A no-op run (nothing touched) leaves the file alone. function writeOpencodeConfig( - file: string, - original: string, - data: Record, - touched: ReadonlySet, + file: string, + original: string, + data: Record, + touched: ReadonlySet, ): void { - if (touched.size === 0) return; - if (original === "") { - writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); - return; - } - let strict = false; - try { - JSON.parse(original); - strict = true; - } catch (error) { - // JSONC is expected here; preserve it with targeted edits instead. - void error; - } - if (strict) { - writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); - return; - } - let text = original; - for (const key of touched) { - text = applyEdits( - text, - jsoncModify(text, [key], data[key], { - formattingOptions: { tabSize: 2, insertSpaces: true }, - }), - ); - } - writeConfigText(file, text); + if (touched.size === 0) return; + if (original === "") { + writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); + return; + } + let strict = false; + try { + JSON.parse(original); + strict = true; + } catch (error) { + // JSONC is expected here; preserve it with targeted edits instead. + void error; + } + if (strict) { + writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); + return; + } + let text = original; + for (const key of touched) { + text = applyEdits( + text, + jsoncModify(text, [key], data[key], { + formattingOptions: { tabSize: 2, insertSpaces: true }, + }), + ); + } + writeConfigText(file, text); } // Legacy opencode-acp plugin entries — both config shapes v1 accepts: @@ -1740,68 +1740,68 @@ function writeOpencodeConfig( // #927: strip from BOTH key spellings — a 2.x host may carry acp entries under // `plugins`, an older v1 install under `plugin`. function isLegacyOpencodeAcpEntry(entry: string): boolean { - if (entry === "opencode-acp" || entry.startsWith("opencode-acp@")) - return true; - if (entry.startsWith("npm:")) { - const rest = entry.slice(4); - return rest === "opencode-acp" || rest.startsWith("opencode-acp@"); - } - const normalized = entry.replace(/\\/g, "/"); - const segments = normalized.split("/").filter((s) => s.length > 0); - // Any path segment naming the package identifies an acp install — covers - // dir specs, /index.js, and deeper entry paths like dist/index.js. - return segments.some( - (s) => s === "opencode-acp" || s.startsWith("opencode-acp@"), - ); + if (entry === "opencode-acp" || entry.startsWith("opencode-acp@")) + return true; + if (entry.startsWith("npm:")) { + const rest = entry.slice(4); + return rest === "opencode-acp" || rest.startsWith("opencode-acp@"); + } + const normalized = entry.replace(/\\/g, "/"); + const segments = normalized.split("/").filter((s) => s.length > 0); + // Any path segment naming the package identifies an acp install — covers + // dir specs, /index.js, and deeper entry paths like dist/index.js. + return segments.some( + (s) => s === "opencode-acp" || s.startsWith("opencode-acp@"), + ); } function stripLegacyOpencodeAcp( - data: Record, - notes: string[], - touched: Set, + data: Record, + notes: string[], + touched: Set, ): void { - const removed: string[] = []; - for (const key of PLUGIN_KEYS) { - const v = data[key]; - let dropped = 0; - if (Array.isArray(v)) { - const survivors: unknown[] = []; - for (const entry of v) { - if (typeof entry === "string" && isLegacyOpencodeAcpEntry(entry)) { - removed.push(entry); - dropped++; - continue; - } - survivors.push(entry); - } - if (dropped > 0) { - if (survivors.length === 0) delete data[key]; - else data[key] = survivors; - touched.add(key); - } - } else if (v !== null && typeof v === "object") { - const map = v as Record; - for (const k of Object.keys(map)) { - if (isLegacyOpencodeAcpEntry(k)) { - delete map[k]; - removed.push(k); - dropped++; - } - } - if (dropped > 0) { - if (Object.keys(map).length === 0) delete data[key]; - touched.add(key); - } - } - } - if (removed.length > 0) { - notes.push( - `replaced opencode-acp plugin entries (${removed.join(", ")}) — single compression owner; restore from the .bili-bak backup if that was intended`, - ); - notes.push( - "also check /.opencode/opencode.json — a LOCAL-scope opencode-acp install (opencode plugin opencode-acp) lives there, not in this global config", - ); - } + const removed: string[] = []; + for (const key of PLUGIN_KEYS) { + const v = data[key]; + let dropped = 0; + if (Array.isArray(v)) { + const survivors: unknown[] = []; + for (const entry of v) { + if (typeof entry === "string" && isLegacyOpencodeAcpEntry(entry)) { + removed.push(entry); + dropped++; + continue; + } + survivors.push(entry); + } + if (dropped > 0) { + if (survivors.length === 0) delete data[key]; + else data[key] = survivors; + touched.add(key); + } + } else if (v !== null && typeof v === "object") { + const map = v as Record; + for (const k of Object.keys(map)) { + if (isLegacyOpencodeAcpEntry(k)) { + delete map[k]; + removed.push(k); + dropped++; + } + } + if (dropped > 0) { + if (Object.keys(map).length === 0) delete data[key]; + touched.add(key); + } + } + } + if (removed.length > 0) { + notes.push( + `replaced opencode-acp plugin entries (${removed.join(", ")}) — single compression owner; restore from the .bili-bak backup if that was intended`, + ); + notes.push( + "also check /.opencode/opencode.json — a LOCAL-scope opencode-acp install (opencode plugin opencode-acp) lives there, not in this global config", + ); + } } // #925: how THIS bili was installed decides which plugin entry install can @@ -1811,13 +1811,13 @@ function stripLegacyOpencodeAcp( // Npm.add machinery (host-managed install + upgrade, portable config). Any // other form (git checkout / dev build) has no published entry — local shim dir. export function isNpmInstallForm(root: string): boolean { - return /(^|[/\\])node_modules[/\\]/.test(root); + return /(^|[/\\])node_modules[/\\]/.test(root); } export const OPENCODE_NPM_ENTRY = "billion-context"; const DEV_FORM_NOTE = - "dev form: machine-local shim, not portable across machines — an npm install writes the bare package name instead"; + "dev form: machine-local shim, not portable across machines — an npm install writes the bare package name instead"; // #925: pick + apply the plugin entry for this install form. Replaces any // existing entry of either form (single owner), returns note(s). #927: the @@ -1830,283 +1830,283 @@ const DEV_FORM_NOTE = // projection must never be written back, and "plugin present" must mean // the key was left untouched (no rewrite of the surrounding file either). export function applyOpencodePluginEntry(args: { - data: Record; - root: string; - shimDir: string; - agentJs: string; - key?: "plugin" | "plugins"; - touched?: Set; + data: Record; + root: string; + shimDir: string; + agentJs: string; + key?: "plugin" | "plugins"; + touched?: Set; }): string[] { - const { data, root, shimDir, agentJs } = args; - const key = args.key ?? "plugin"; - const touched = args.touched ?? new Set(); - const ours = [OPENCODE_NPM_ENTRY, shimDir]; - const npmForm = isNpmInstallForm(root); - const entry = npmForm ? OPENCODE_NPM_ENTRY : shimDir; - const isOurs = (x: unknown): boolean => - typeof x === "string" && ours.includes(x); - const raw = data[key]; - const oursIn = (): string[] => { - if (Array.isArray(raw)) return raw.filter((x): x is string => isOurs(x)); - if (raw !== null && typeof raw === "object") - return Object.keys(raw as Record).filter((k) => - isOurs(k), - ); - return []; - }; - const replaced = oursIn(); - if (npmForm && replaced.includes(shimDir)) - fs.rmSync(shimDir, { recursive: true, force: true }); - if (!npmForm) { - fs.mkdirSync(shimDir, { recursive: true }); - fs.writeFileSync( - path.join(shimDir, "index.js"), - `export { default } from ${JSON.stringify(agentJs)};\n`, - ); - } - // Exactly our one entry, already the right form — nothing to migrate: - // leave the key (and the file) untouched. - if (replaced.length === 1 && replaced[0] === entry) return [`${key} present`]; - if (Array.isArray(raw)) { - data[key] = [...raw.filter((x) => !isOurs(x)), entry]; - } else if (raw !== null && typeof raw === "object") { - const map = raw as Record; - for (const k of Object.keys(map)) if (isOurs(k)) delete map[k]; - map[entry] = true; - data[key] = map; - } else { - data[key] = [entry]; - } - touched.add(key); - if (npmForm) { - if (replaced.length === 0) return [`plugin -> ${OPENCODE_NPM_ENTRY}`]; - return [ - `plugin -> ${OPENCODE_NPM_ENTRY} (replaced ${replaced.join(", ")})`, - ]; - } - if (replaced.length === 0) return [`plugin -> ${shimDir}`, DEV_FORM_NOTE]; - return [ - `plugin -> ${shimDir} (replaced ${replaced.join(", ")})`, - DEV_FORM_NOTE, - ]; + const { data, root, shimDir, agentJs } = args; + const key = args.key ?? "plugin"; + const touched = args.touched ?? new Set(); + const ours = [OPENCODE_NPM_ENTRY, shimDir]; + const npmForm = isNpmInstallForm(root); + const entry = npmForm ? OPENCODE_NPM_ENTRY : shimDir; + const isOurs = (x: unknown): boolean => + typeof x === "string" && ours.includes(x); + const raw = data[key]; + const oursIn = (): string[] => { + if (Array.isArray(raw)) return raw.filter((x): x is string => isOurs(x)); + if (raw !== null && typeof raw === "object") + return Object.keys(raw as Record).filter((k) => + isOurs(k), + ); + return []; + }; + const replaced = oursIn(); + if (npmForm && replaced.includes(shimDir)) + fs.rmSync(shimDir, { recursive: true, force: true }); + if (!npmForm) { + fs.mkdirSync(shimDir, { recursive: true }); + fs.writeFileSync( + path.join(shimDir, "index.js"), + `export { default } from ${JSON.stringify(agentJs)};\n`, + ); + } + // Exactly our one entry, already the right form — nothing to migrate: + // leave the key (and the file) untouched. + if (replaced.length === 1 && replaced[0] === entry) return [`${key} present`]; + if (Array.isArray(raw)) { + data[key] = [...raw.filter((x) => !isOurs(x)), entry]; + } else if (raw !== null && typeof raw === "object") { + const map = raw as Record; + for (const k of Object.keys(map)) if (isOurs(k)) delete map[k]; + map[entry] = true; + data[key] = map; + } else { + data[key] = [entry]; + } + touched.add(key); + if (npmForm) { + if (replaced.length === 0) return [`plugin -> ${OPENCODE_NPM_ENTRY}`]; + return [ + `plugin -> ${OPENCODE_NPM_ENTRY} (replaced ${replaced.join(", ")})`, + ]; + } + if (replaced.length === 0) return [`plugin -> ${shimDir}`, DEV_FORM_NOTE]; + return [ + `plugin -> ${shimDir} (replaced ${replaced.join(", ")})`, + DEV_FORM_NOTE, + ]; } function opencodeInstall(withMcp = false): string { - const file = opencodeTargetFile(); - const { original, data } = loadOpencodeConfig(file); - const notes: string[] = []; - const touched = new Set(); - - // #926: the native plugin below registers the bili tools itself (auto - // session-bound), so opencode gets NO mcp.bili by default — a frozen - // BILI_MCP_PROXY there goes stale the moment the plugin's - // ephemeral-port proxy restarts. Default heals any entry an older - // install froze in. --with-mcp opts in; the entry then carries no origin - // pin (dist/mcp.js discovers the live proxy via the instance file at - // call time) unless BILI_MCP_PROXY is set for this install. - if (!withMcp) { - const rawMcp = data.mcp; - if (isPlainMcpObject(rawMcp) && "bili" in rawMcp) { - delete rawMcp.bili; - if (Object.keys(rawMcp).length === 0) delete data.mcp; - touched.add("mcp"); - notes.push( - "mcp.bili removed (stale second tool face — the native plugin provides the bili tools; install with --with-mcp to keep an MCP face)", - ); - } else { - notes.push( - "mcp.bili not written (the native plugin provides the bili tools; --with-mcp adds an MCP face)", - ); - } - } else { - try { - const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js"); - requireDistFile(mcpJs); - const rawMcp = data.mcp; - if (rawMcp != null && !isPlainMcpObject(rawMcp)) { - notes.push('mcp.bili skipped ("mcp" is not an object)'); - } else { - const mcp = (rawMcp as Record | undefined) ?? {}; - const explicit = process.env.BILI_MCP_PROXY?.trim(); - const bili = mcp.bili; - if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { - const env = (bili as Record).environment; - const envObj = - env !== null && typeof env === "object" && !Array.isArray(env) - ? (env as Record) - : undefined; - if (envObj?.BILI_MCP_PROXY !== undefined && explicit === undefined) { - delete envObj.BILI_MCP_PROXY; - if (Object.keys(envObj).length === 0) - delete (bili as Record).environment; - touched.add("mcp"); - notes.push( - "mcp.bili present (stale BILI_MCP_PROXY pin removed — live discovery takes over)", - ); - } else { - notes.push("mcp.bili present"); - } - } else { - const entry: Record = { - type: "local", - command: [process.execPath, mcpJs], - enabled: true, - }; - if (explicit !== undefined) - entry.environment = { BILI_MCP_PROXY: explicit }; - mcp.bili = entry; - data.mcp = mcp; - touched.add("mcp"); - notes.push( - explicit !== undefined - ? `mcp.bili written (BILI_MCP_PROXY=${explicit})` - : "mcp.bili written (no origin pin — live discovery via instance file)", - ); - } - } - } catch (err) { - notes.push( - `mcp.bili skipped (${err instanceof Error ? err.message : String(err)})`, - ); - } - } - - // Native plugin (#820/#925): self-spawned proxy + http.request URL rewrite. - // Entry form depends on how THIS bili was installed — npm → bare package - // name (exports["./server"], host-managed), checkout/dev → local shim dir. - const root = selfPackageRoot(); - const agentJs = path.join(root, "dist", "agent", "opencode-native.js"); - requireDistFile(agentJs); - // Single compression owner FIRST: drop any opencode-acp entry before - // adding ours, so both never load armed in one host (#918). The write - // below snapshots the original config to .bili-bak (first write only). - stripLegacyOpencodeAcp(data, notes, touched); - // #927 entry key for this host + #925 entry form for this install form. - notes.push( - ...applyOpencodePluginEntry({ - data, - root, - shimDir: opencodePluginDir(file), - agentJs, - key: pickPluginKey(detectOpencodeMajor()), - touched, - }), - ); - - // Single compression owner: with the native plugin installed, ACP owns - // compression — disable host auto-compaction (merge-preserving; the key is - // ignored on OpenCode 1.x). Restored from the pre-install backup on - // remove. #927: skip when the target already says auto:false — the user - // wrote it themselves, so one file carries the fact exactly once. - const curCompaction = data.compaction; - const curObj = - curCompaction !== null && - typeof curCompaction === "object" && - !Array.isArray(curCompaction) - ? (curCompaction as Record) - : undefined; - if (curObj?.auto === false) { - notes.push("compaction.auto already disabled"); - } else { - data.compaction = { ...(curObj ?? {}), auto: false }; - touched.add("compaction"); - notes.push("compaction.auto set to false"); - } - - writeOpencodeConfig(file, original, data, touched); - return `opencode: installed -> ${file} (${notes.join("; ")})`; + const file = opencodeTargetFile(); + const { original, data } = loadOpencodeConfig(file); + const notes: string[] = []; + const touched = new Set(); + + // #926: the native plugin below registers the bili tools itself (auto + // session-bound), so opencode gets NO mcp.bili by default — a frozen + // BILI_MCP_PROXY there goes stale the moment the plugin's + // ephemeral-port proxy restarts. Default heals any entry an older + // install froze in. --with-mcp opts in; the entry then carries no origin + // pin (dist/mcp.js discovers the live proxy via the instance file at + // call time) unless BILI_MCP_PROXY is set for this install. + if (!withMcp) { + const rawMcp = data.mcp; + if (isPlainMcpObject(rawMcp) && "bili" in rawMcp) { + delete rawMcp.bili; + if (Object.keys(rawMcp).length === 0) delete data.mcp; + touched.add("mcp"); + notes.push( + "mcp.bili removed (stale second tool face — the native plugin provides the bili tools; install with --with-mcp to keep an MCP face)", + ); + } else { + notes.push( + "mcp.bili not written (the native plugin provides the bili tools; --with-mcp adds an MCP face)", + ); + } + } else { + try { + const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js"); + requireDistFile(mcpJs); + const rawMcp = data.mcp; + if (rawMcp != null && !isPlainMcpObject(rawMcp)) { + notes.push('mcp.bili skipped ("mcp" is not an object)'); + } else { + const mcp = (rawMcp as Record | undefined) ?? {}; + const explicit = process.env.BILI_MCP_PROXY?.trim(); + const bili = mcp.bili; + if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { + const env = (bili as Record).environment; + const envObj = + env !== null && typeof env === "object" && !Array.isArray(env) + ? (env as Record) + : undefined; + if (envObj?.BILI_MCP_PROXY !== undefined && explicit === undefined) { + delete envObj.BILI_MCP_PROXY; + if (Object.keys(envObj).length === 0) + delete (bili as Record).environment; + touched.add("mcp"); + notes.push( + "mcp.bili present (stale BILI_MCP_PROXY pin removed — live discovery takes over)", + ); + } else { + notes.push("mcp.bili present"); + } + } else { + const entry: Record = { + type: "local", + command: [process.execPath, mcpJs], + enabled: true, + }; + if (explicit !== undefined) + entry.environment = { BILI_MCP_PROXY: explicit }; + mcp.bili = entry; + data.mcp = mcp; + touched.add("mcp"); + notes.push( + explicit !== undefined + ? `mcp.bili written (BILI_MCP_PROXY=${explicit})` + : "mcp.bili written (no origin pin — live discovery via instance file)", + ); + } + } + } catch (err) { + notes.push( + `mcp.bili skipped (${err instanceof Error ? err.message : String(err)})`, + ); + } + } + + // Native plugin (#820/#925): self-spawned proxy + http.request URL rewrite. + // Entry form depends on how THIS bili was installed — npm → bare package + // name (exports["./server"], host-managed), checkout/dev → local shim dir. + const root = selfPackageRoot(); + const agentJs = path.join(root, "dist", "agent", "opencode-native.js"); + requireDistFile(agentJs); + // Single compression owner FIRST: drop any opencode-acp entry before + // adding ours, so both never load armed in one host (#918). The write + // below snapshots the original config to .bili-bak (first write only). + stripLegacyOpencodeAcp(data, notes, touched); + // #927 entry key for this host + #925 entry form for this install form. + notes.push( + ...applyOpencodePluginEntry({ + data, + root, + shimDir: opencodePluginDir(file), + agentJs, + key: pickPluginKey(detectOpencodeMajor()), + touched, + }), + ); + + // Single compression owner: with the native plugin installed, ACP owns + // compression — disable host auto-compaction (merge-preserving; the key is + // ignored on OpenCode 1.x). Restored from the pre-install backup on + // remove. #927: skip when the target already says auto:false — the user + // wrote it themselves, so one file carries the fact exactly once. + const curCompaction = data.compaction; + const curObj = + curCompaction !== null && + typeof curCompaction === "object" && + !Array.isArray(curCompaction) + ? (curCompaction as Record) + : undefined; + if (curObj?.auto === false) { + notes.push("compaction.auto already disabled"); + } else { + data.compaction = { ...(curObj ?? {}), auto: false }; + touched.add("compaction"); + notes.push("compaction.auto set to false"); + } + + writeOpencodeConfig(file, original, data, touched); + return `opencode: installed -> ${file} (${notes.join("; ")})`; } function opencodeRemove(): string { - const file = opencodeTargetFile(); - const { original, data } = loadOpencodeConfig(file); - const notes: string[] = []; - const touched = new Set(); - - const mcp = data.mcp; - if (isPlainMcpObject(mcp) && "bili" in mcp) { - delete mcp.bili; - if (Object.keys(mcp).length === 0) delete data.mcp; - touched.add("mcp"); - notes.push("mcp.bili removed"); - } - - // #927: clean our entry out of whichever key spelling carries it; the - // entry may be either form (#925) — bare npm name or shim dir. #1002: - // the key dies only when NOTHING raw survives — foreign object entries - // and map-form options are preserved verbatim, never collapsed. - const dir = opencodePluginDir(file); - const removed: string[] = []; - for (const key of PLUGIN_KEYS) { - const v = data[key]; - const hit = (x: string): boolean => x === OPENCODE_NPM_ENTRY || x === dir; - if (Array.isArray(v)) { - const survivors = v.filter((x) => !(typeof x === "string" && hit(x))); - if (survivors.length === v.length) continue; - for (const x of v) if (typeof x === "string" && hit(x)) removed.push(x); - if (survivors.length === 0) delete data[key]; - else data[key] = survivors; - touched.add(key); - } else if (v !== null && typeof v === "object") { - const map = v as Record; - const hits = Object.keys(map).filter(hit); - if (hits.length === 0) continue; - for (const k of hits) { - delete map[k]; - removed.push(k); - } - if (Object.keys(map).length === 0) delete data[key]; - else data[key] = map; - touched.add(key); - } - } - if (removed.length > 0) { - if (removed.includes(dir)) fs.rmSync(dir, { recursive: true, force: true }); - notes.push(`plugin removed (${removed.join(", ")})`); - } - - if (notes.length > 0) { - const cur = data.compaction as Record | undefined; - if (cur && cur.auto === false) { - const bak = `${file}.bili-bak`; - if (fs.existsSync(bak)) { - try { - const bakData = loadOpencodeConfig(bak).data; - if (bakData.compaction === undefined) delete data.compaction; - else data.compaction = bakData.compaction; - touched.add("compaction"); - notes.push("compaction restored from backup"); - } catch { - // unreadable backup — leave current settings untouched - } - } else if (Object.keys(cur).length === 1) { - // no pre-install config existed, so our {auto:false} is the entire - // key — dropping it restores the pre-install state exactly; with - // extra keys present we can't tell user edits apart, so leave them - delete data.compaction; - touched.add("compaction"); - notes.push("compaction removed (no prior config)"); - } - } - } - - writeOpencodeConfig(file, original, data, touched); - return notes.length > 0 - ? `opencode: removed from ${file} (${notes.join("; ")})` - : `opencode: not installed (${file})`; + const file = opencodeTargetFile(); + const { original, data } = loadOpencodeConfig(file); + const notes: string[] = []; + const touched = new Set(); + + const mcp = data.mcp; + if (isPlainMcpObject(mcp) && "bili" in mcp) { + delete mcp.bili; + if (Object.keys(mcp).length === 0) delete data.mcp; + touched.add("mcp"); + notes.push("mcp.bili removed"); + } + + // #927: clean our entry out of whichever key spelling carries it; the + // entry may be either form (#925) — bare npm name or shim dir. #1002: + // the key dies only when NOTHING raw survives — foreign object entries + // and map-form options are preserved verbatim, never collapsed. + const dir = opencodePluginDir(file); + const removed: string[] = []; + for (const key of PLUGIN_KEYS) { + const v = data[key]; + const hit = (x: string): boolean => x === OPENCODE_NPM_ENTRY || x === dir; + if (Array.isArray(v)) { + const survivors = v.filter((x) => !(typeof x === "string" && hit(x))); + if (survivors.length === v.length) continue; + for (const x of v) if (typeof x === "string" && hit(x)) removed.push(x); + if (survivors.length === 0) delete data[key]; + else data[key] = survivors; + touched.add(key); + } else if (v !== null && typeof v === "object") { + const map = v as Record; + const hits = Object.keys(map).filter(hit); + if (hits.length === 0) continue; + for (const k of hits) { + delete map[k]; + removed.push(k); + } + if (Object.keys(map).length === 0) delete data[key]; + else data[key] = map; + touched.add(key); + } + } + if (removed.length > 0) { + if (removed.includes(dir)) fs.rmSync(dir, { recursive: true, force: true }); + notes.push(`plugin removed (${removed.join(", ")})`); + } + + if (notes.length > 0) { + const cur = data.compaction as Record | undefined; + if (cur && cur.auto === false) { + const bak = `${file}.bili-bak`; + if (fs.existsSync(bak)) { + try { + const bakData = loadOpencodeConfig(bak).data; + if (bakData.compaction === undefined) delete data.compaction; + else data.compaction = bakData.compaction; + touched.add("compaction"); + notes.push("compaction restored from backup"); + } catch { + // unreadable backup — leave current settings untouched + } + } else if (Object.keys(cur).length === 1) { + // no pre-install config existed, so our {auto:false} is the entire + // key — dropping it restores the pre-install state exactly; with + // extra keys present we can't tell user edits apart, so leave them + delete data.compaction; + touched.add("compaction"); + notes.push("compaction removed (no prior config)"); + } + } + } + + writeOpencodeConfig(file, original, data, touched); + return notes.length > 0 + ? `opencode: removed from ${file} (${notes.join("; ")})` + : `opencode: not installed (${file})`; } function opencodeStatus(): string { - const file = opencodeTargetFile(); - const { data } = loadOpencodeConfig(file); - const mcp = data.mcp; - const dir = opencodePluginDir(file); - const listed = PLUGIN_KEYS.some((k) => - pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY || p === dir), - ); - return (isPlainMcpObject(mcp) && "bili" in mcp) || listed - ? "installed" - : "not installed"; + const file = opencodeTargetFile(); + const { data } = loadOpencodeConfig(file); + const mcp = data.mcp; + const dir = opencodePluginDir(file); + const listed = PLUGIN_KEYS.some((k) => + pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY || p === dir), + ); + return (isPlainMcpObject(mcp) && "bili" in mcp) || listed + ? "installed" + : "not installed"; } // — dsh ———————————————————————————————————————————————————————————————— @@ -2122,54 +2122,54 @@ function opencodeStatus(): string { // checkout/dev → absolute path (pnpm link:, tracks the live source). function dshInstall(): string { - const root = selfPackageRoot(); - requireDistFile(path.join(root, "dist", "agent", "dsh-native.js")); - const dirs = dshProfileDirs(); - const notes: string[] = []; - for (const dir of dirs) { - if (stripLegacyManagedBlock(dir)) - notes.push(`${path.basename(dir)}: legacy managed block stripped`); - } - const spec = isNpmInstallForm(root) ? DSH_PACKAGE : path.resolve(root); - for (const dir of dirs) { - runDshPlugin(["plugin", "--profile", path.basename(dir), "add", spec]); - } - return `installed ${DSH_PACKAGE} into ${dirs.length} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} via 'dsh plugin --profile add ${spec}'${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — restart dsh to load it`; + const root = selfPackageRoot(); + requireDistFile(path.join(root, "dist", "agent", "dsh-native.js")); + const dirs = dshProfileDirs(); + const notes: string[] = []; + for (const dir of dirs) { + if (stripLegacyManagedBlock(dir)) + notes.push(`${path.basename(dir)}: legacy managed block stripped`); + } + const spec = isNpmInstallForm(root) ? DSH_PACKAGE : path.resolve(root); + for (const dir of dirs) { + runDshPlugin(["plugin", "--profile", path.basename(dir), "add", spec]); + } + return `installed ${DSH_PACKAGE} into ${dirs.length} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} via 'dsh plugin --profile add ${spec}'${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — restart dsh to load it`; } function dshRemove(): string { - const notes: string[] = []; - const touched = new Set(); - for (const dir of dshProfileDirs()) { - const name = path.basename(dir); - if (dshProfileDependsOnBili(dir)) { - runDshPlugin(["plugin", "--profile", name, "remove", DSH_PACKAGE]); - touched.add(name); - notes.push(`${name}: uninstalled via the dsh plugin channel`); - } - if (stripLegacyManagedBlock(dir)) { - touched.add(name); - notes.push(`${name}: legacy managed block stripped`); - } - } - if (touched.size === 0) - return "nothing to remove — no dsh profile carries billion-context"; - return `removed bili from ${touched.size} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} (${notes.join("; ")}) — restart dsh to finish`; + const notes: string[] = []; + const touched = new Set(); + for (const dir of dshProfileDirs()) { + const name = path.basename(dir); + if (dshProfileDependsOnBili(dir)) { + runDshPlugin(["plugin", "--profile", name, "remove", DSH_PACKAGE]); + touched.add(name); + notes.push(`${name}: uninstalled via the dsh plugin channel`); + } + if (stripLegacyManagedBlock(dir)) { + touched.add(name); + notes.push(`${name}: legacy managed block stripped`); + } + } + if (touched.size === 0) + return "nothing to remove — no dsh profile carries billion-context"; + return `removed bili from ${touched.size} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} (${notes.join("; ")}) — restart dsh to finish`; } function dshStatus(): string { - const dirs = dshProfileDirs(); - const bundle = dirs.filter((dir) => dshBundleInstalled(dir)); - const withBlock = dirs.filter((dir) => dshHasLegacyManagedBlock(dir)); - if (bundle.length === dirs.length && dirs.length > 0) - return `installed (dsh bundle in all ${dirs.length} profiles)`; - if (bundle.length > 0) - return `installed as a dsh bundle in ${bundle.length}/${dirs.length} profiles`; - if (withBlock.length === dirs.length && dirs.length > 0) - return "installed (legacy managed block — rerun 'bili plugin install dsh' to migrate to the dsh bundle channel)"; - if (withBlock.length > 0) - return `legacy managed block in ${withBlock.length}/${dirs.length} profiles — rerun 'bili plugin install dsh' to migrate`; - return "not installed"; + const dirs = dshProfileDirs(); + const bundle = dirs.filter((dir) => dshBundleInstalled(dir)); + const withBlock = dirs.filter((dir) => dshHasLegacyManagedBlock(dir)); + if (bundle.length === dirs.length && dirs.length > 0) + return `installed (dsh bundle in all ${dirs.length} profiles)`; + if (bundle.length > 0) + return `installed as a dsh bundle in ${bundle.length}/${dirs.length} profiles`; + if (withBlock.length === dirs.length && dirs.length > 0) + return "installed (legacy managed block — rerun 'bili plugin install dsh' to migrate to the dsh bundle channel)"; + if (withBlock.length > 0) + return `legacy managed block in ${withBlock.length}/${dirs.length} profiles — rerun 'bili plugin install dsh' to migrate`; + return "not installed"; } /** True when any profile carries the persistent native install — either the @@ -2179,17 +2179,17 @@ function dshStatus(): string { * `id: bili-native` insert would hard-fail dsh boot whenever the persistent * install is present. */ export function dshNativeInstalled( - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = process.env, ): boolean { - let dirs: string[]; - try { - dirs = dshProfileDirs(env); - } catch { - return false; - } - return dirs.some( - (dir) => dshBundleInstalled(dir) || dshHasLegacyManagedBlock(dir), - ); + let dirs: string[]; + try { + dirs = dshProfileDirs(env); + } catch { + return false; + } + return dirs.some( + (dir) => dshBundleInstalled(dir) || dshHasLegacyManagedBlock(dir), + ); } // — kimi ———————————————————————————————————————————————————————————————— @@ -2205,65 +2205,65 @@ export function dshNativeInstalled( const KIMI_PLUGIN_ID = "billion-context"; function kimiHome(): string { - return resolveKimiHome(process.env); + return resolveKimiHome(process.env); } function kimiManagedDir(): string { - return path.join(kimiHome(), "plugins", "managed", KIMI_PLUGIN_ID); + return path.join(kimiHome(), "plugins", "managed", KIMI_PLUGIN_ID); } function kimiRegistryFile(): string { - return path.join(kimiHome(), "plugins", "installed.json"); + return path.join(kimiHome(), "plugins", "installed.json"); } interface KimiInstalledRecord { - id: string; - root: string; - source: "local-path"; - enabled: boolean; - installedAt: string; - updatedAt?: string; + id: string; + root: string; + source: "local-path"; + enabled: boolean; + installedAt: string; + updatedAt?: string; } /** installed.json is machine-managed (kimi's own store writes it too) but is * not user-authored prose — a corrupt registry is surfaced loudly instead of * being silently re-created (§7.3). */ function readKimiInstalledRegistry(file: string): { - version: number; - plugins: KimiInstalledRecord[]; + version: number; + plugins: KimiInstalledRecord[]; } { - let text: string; - try { - text = fs.readFileSync(file, "utf8"); - } catch (err) { - if ((err as { code?: string }).code === "ENOENT") - return { version: 1, plugins: [] }; - throw err; - } - let parsed: { version?: unknown; plugins?: unknown }; - try { - parsed = JSON.parse(text) as { version?: unknown; plugins?: unknown }; - } catch (err) { - throw new Error( - `${file} is corrupt (invalid JSON) — fix or remove it, then retry`, - { cause: err }, - ); - } - if (!Array.isArray(parsed.plugins)) - throw new Error( - `${file} is corrupt (no plugins array) — fix or remove it, then retry`, - ); - return { - version: typeof parsed.version === "number" ? parsed.version : 1, - plugins: parsed.plugins as KimiInstalledRecord[], - }; + let text: string; + try { + text = fs.readFileSync(file, "utf8"); + } catch (err) { + if ((err as { code?: string }).code === "ENOENT") + return { version: 1, plugins: [] }; + throw err; + } + let parsed: { version?: unknown; plugins?: unknown }; + try { + parsed = JSON.parse(text) as { version?: unknown; plugins?: unknown }; + } catch (err) { + throw new Error( + `${file} is corrupt (invalid JSON) — fix or remove it, then retry`, + { cause: err }, + ); + } + if (!Array.isArray(parsed.plugins)) + throw new Error( + `${file} is corrupt (no plugins array) — fix or remove it, then retry`, + ); + return { + version: typeof parsed.version === "number" ? parsed.version : 1, + plugins: parsed.plugins as KimiInstalledRecord[], + }; } function writeJsonAtomic(file: string, data: unknown): void { - fs.mkdirSync(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; - fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`); - fs.renameSync(tmp, file); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}`; + fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`); + fs.renameSync(tmp, file); } /** Kimi Code v2 floor: the plugin system (managed plugins + hooks + stdio MCP @@ -2271,158 +2271,158 @@ function writeJsonAtomic(file: string, data: unknown): void { * an old one throws with launcher-mode guidance rather than writing a dead * manifest. */ function detectKimiVersion(env: NodeJS.ProcessEnv = process.env): string { - const candidates: Array<{ cmd: string; viaShell: boolean }> = - process.platform === "win32" - ? [{ cmd: "kimi --version", viaShell: true }] - : [ - { cmd: "kimi", viaShell: false }, - { - cmd: path.join(resolveKimiHome(env), "bin", "kimi"), - viaShell: false, - }, - ]; - let out: string | undefined; - for (const c of candidates) { - try { - out = c.viaShell - ? execFileSync(c.cmd, { - shell: true, - timeout: 5000, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }) - : execFileSync(c.cmd, ["--version"], { - timeout: 5000, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }); - break; - } catch {} - } - if (out === undefined) - throw new Error( - "kimi CLI not found on PATH or in $KIMI_CODE_HOME/bin — install Kimi Code first (`npm i -g @moonshot-ai/kimi-code`)", - ); - const m = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(out); - if (m && parseInt(m[1], 10) < 2) { - throw new Error( - `Kimi Code ${m[0]} is too old for native mode (needs >= 2.0.0) — upgrade with \`npm i -g @moonshot-ai/kimi-code@latest\` and retry; \`bili kimi\` launcher mode still works`, - ); - } - return m ? m[0] : out.trim(); + const candidates: Array<{ cmd: string; viaShell: boolean }> = + process.platform === "win32" + ? [{ cmd: "kimi --version", viaShell: true }] + : [ + { cmd: "kimi", viaShell: false }, + { + cmd: path.join(resolveKimiHome(env), "bin", "kimi"), + viaShell: false, + }, + ]; + let out: string | undefined; + for (const c of candidates) { + try { + out = c.viaShell + ? execFileSync(c.cmd, { + shell: true, + timeout: 5000, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }) + : execFileSync(c.cmd, ["--version"], { + timeout: 5000, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }); + break; + } catch {} + } + if (out === undefined) + throw new Error( + "kimi CLI not found on PATH or in $KIMI_CODE_HOME/bin — install Kimi Code first (`npm i -g @moonshot-ai/kimi-code`)", + ); + const m = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(out); + if (m && parseInt(m[1], 10) < 2) { + throw new Error( + `Kimi Code ${m[0]} is too old for native mode (needs >= 2.0.0) — upgrade with \`npm i -g @moonshot-ai/kimi-code@latest\` and retry; \`bili kimi\` launcher mode still works`, + ); + } + return m ? m[0] : out.trim(); } function selfVersion(): string { - try { - return ( - ( - JSON.parse( - fs.readFileSync(path.join(selfPackageRoot(), "package.json"), "utf8"), - ) as { version?: string } - ).version ?? "0.0.0" - ); - } catch { - return "0.0.0"; - } + try { + return ( + ( + JSON.parse( + fs.readFileSync(path.join(selfPackageRoot(), "package.json"), "utf8"), + ) as { version?: string } + ).version ?? "0.0.0" + ); + } catch { + return "0.0.0"; + } } function kimiPluginManifest(root: string): Record { - return { - name: KIMI_PLUGIN_ID, - version: selfVersion(), - description: "billion-context: ACP context-compression proxy (native mode)", - mcpServers: { - bili: { - command: "node", - args: [path.join(root, "dist", "kimi", "native-mcp.js")], - cwd: "./", - }, - }, - hooks: [ - { - event: "SessionStart", - command: portableHookCommand("node", [ - path.join(root, "dist", "kimi", "bootstrap-hook.js"), - ]), - timeout: 30, - }, - ], - }; + return { + name: KIMI_PLUGIN_ID, + version: selfVersion(), + description: "billion-context: ACP context-compression proxy (native mode)", + mcpServers: { + bili: { + command: "node", + args: [path.join(root, "dist", "kimi", "native-mcp.js")], + cwd: "./", + }, + }, + hooks: [ + { + event: "SessionStart", + command: portableHookCommand("node", [ + path.join(root, "dist", "kimi", "bootstrap-hook.js"), + ]), + timeout: 30, + }, + ], + }; } function kimiInstall(): string { - const root = selfPackageRoot(); - requireDistFile(path.join(root, "dist", "kimi", "native-mcp.js")); - requireDistFile(path.join(root, "dist", "kimi", "bootstrap-hook.js")); - const version = detectKimiVersion(); - const dir = kimiManagedDir(); - fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync( - path.join(dir, "kimi.plugin.json"), - `${JSON.stringify(kimiPluginManifest(root), null, 2)}\n`, - ); - const file = kimiRegistryFile(); - backupBeforeWrite(file); - const reg = readKimiInstalledRegistry(file); - const now = new Date().toISOString(); - const existing = reg.plugins.find((p) => p.id === KIMI_PLUGIN_ID); - const record: KimiInstalledRecord = { - id: KIMI_PLUGIN_ID, - root: dir, - source: "local-path", - enabled: true, - installedAt: existing?.installedAt ?? now, - updatedAt: now, - }; - reg.plugins = existing - ? reg.plugins.map((p) => (p.id === KIMI_PLUGIN_ID ? record : p)) - : [...reg.plugins, record]; - writeJsonAtomic(file, reg); - return `wrote the billion-context plugin into ${dir} (kimi ${version}) — start a new Kimi Code session to activate`; + const root = selfPackageRoot(); + requireDistFile(path.join(root, "dist", "kimi", "native-mcp.js")); + requireDistFile(path.join(root, "dist", "kimi", "bootstrap-hook.js")); + const version = detectKimiVersion(); + const dir = kimiManagedDir(); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, "kimi.plugin.json"), + `${JSON.stringify(kimiPluginManifest(root), null, 2)}\n`, + ); + const file = kimiRegistryFile(); + backupBeforeWrite(file); + const reg = readKimiInstalledRegistry(file); + const now = new Date().toISOString(); + const existing = reg.plugins.find((p) => p.id === KIMI_PLUGIN_ID); + const record: KimiInstalledRecord = { + id: KIMI_PLUGIN_ID, + root: dir, + source: "local-path", + enabled: true, + installedAt: existing?.installedAt ?? now, + updatedAt: now, + }; + reg.plugins = existing + ? reg.plugins.map((p) => (p.id === KIMI_PLUGIN_ID ? record : p)) + : [...reg.plugins, record]; + writeJsonAtomic(file, reg); + return `wrote the billion-context plugin into ${dir} (kimi ${version}) — start a new Kimi Code session to activate`; } function kimiRemove(): string { - const notes: string[] = []; - let removed = false; - const dir = kimiManagedDir(); - if (fs.existsSync(dir)) { - fs.rmSync(dir, { recursive: true, force: true }); - removed = true; - } - try { - const reg = readKimiInstalledRegistry(kimiRegistryFile()); - const rest = reg.plugins.filter((p) => p.id !== KIMI_PLUGIN_ID); - if (rest.length !== reg.plugins.length) - writeJsonAtomic(kimiRegistryFile(), { - version: reg.version, - plugins: rest, - }); - } catch {} - const restored = restoreKimiBackup({ log: (msg) => notes.push(msg) }); - if (restored.restored) - notes.push("restored config.toml from the pre-install snapshot"); - else unrouteKimi({ log: (msg) => notes.push(msg) }); - return removed - ? `removed the billion-context plugin${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new Kimi Code session to finish` - : "not installed"; + const notes: string[] = []; + let removed = false; + const dir = kimiManagedDir(); + if (fs.existsSync(dir)) { + fs.rmSync(dir, { recursive: true, force: true }); + removed = true; + } + try { + const reg = readKimiInstalledRegistry(kimiRegistryFile()); + const rest = reg.plugins.filter((p) => p.id !== KIMI_PLUGIN_ID); + if (rest.length !== reg.plugins.length) + writeJsonAtomic(kimiRegistryFile(), { + version: reg.version, + plugins: rest, + }); + } catch {} + const restored = restoreKimiBackup({ log: (msg) => notes.push(msg) }); + if (restored.restored) + notes.push("restored config.toml from the pre-install snapshot"); + else unrouteKimi({ log: (msg) => notes.push(msg) }); + return removed + ? `removed the billion-context plugin${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new Kimi Code session to finish` + : "not installed"; } function kimiStatus(): string { - const manifestOk = fs.existsSync( - path.join(kimiManagedDir(), "kimi.plugin.json"), - ); - let registered = false; - try { - registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some( - (p) => p.id === KIMI_PLUGIN_ID, - ); - } catch {} - if (manifestOk && registered) return "installed"; - if (manifestOk || registered) - return "partially installed — rerun 'bili plugin install kimi' to fix"; - return "not installed"; + const manifestOk = fs.existsSync( + path.join(kimiManagedDir(), "kimi.plugin.json"), + ); + let registered = false; + try { + registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some( + (p) => p.id === KIMI_PLUGIN_ID, + ); + } catch {} + if (manifestOk && registered) return "installed"; + if (manifestOk || registered) + return "partially installed — rerun 'bili plugin install kimi' to fix"; + return "not installed"; } // — hermes (#958) —————————————————————————————————————————————————————————————— @@ -2436,113 +2436,113 @@ const HERMES_PLUGIN_ID = "billion-context"; // cmd.exe's canonical "command missing" line (its exit code is not reliably // 9009 when spawned via CreateProcess — CI-verified). const CMD_NOT_FOUND_RE = - /is not recognized as an internal or external command/i; + /is not recognized as an internal or external command/i; function hermesPluginDir(): string { - return path.join(resolveHermesHome(process.env), "plugins", HERMES_PLUGIN_ID); + return path.join(resolveHermesHome(process.env), "plugins", HERMES_PLUGIN_ID); } interface HermesSidecar { - proxyScript: string; - nodePath: string; + proxyScript: string; + nodePath: string; } function runHermesCli( - args: string[], + args: string[], ): { ok: true } | { ok: false; reason: string } { - try { - // #679 spawn rules: on Windows a bare `hermes` name or a .cmd shim needs the - // comspec wrap — a plain execFileSync("hermes") ENOENTs there. planDshSpawn - // is the generic host-CLI planner (dsh-named for historical reasons). - const plan = planDshSpawn("hermes", args); - const res = spawnSync(plan.command, plan.args, { - timeout: 15_000, - encoding: "utf8", - stdio: ["ignore", "pipe", "pipe"], - windowsVerbatimArguments: plan.windowsVerbatimArguments, - windowsHide: true, - }); - if (res.error) - return { - ok: false, - reason: - (res.error as NodeJS.ErrnoException).code === "ENOENT" - ? "not-found" - : String(res.error), - }; - if (res.status === 0) return { ok: true }; - if ( - process.platform === "win32" && - (res.status === 9009 || CMD_NOT_FOUND_RE.test(res.stderr ?? "")) - ) - return { ok: false, reason: "not-found" }; - const detail = (res.stderr ?? "").trim(); - return { ok: false, reason: detail || `exit ${res.status}` }; - } catch (err) { - return { - ok: false, - reason: err instanceof Error ? err.message : String(err), - }; - } + try { + // #679 spawn rules: on Windows a bare `hermes` name or a .cmd shim needs the + // comspec wrap — a plain execFileSync("hermes") ENOENTs there. planDshSpawn + // is the generic host-CLI planner (dsh-named for historical reasons). + const plan = planDshSpawn("hermes", args); + const res = spawnSync(plan.command, plan.args, { + timeout: 15_000, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + windowsVerbatimArguments: plan.windowsVerbatimArguments, + windowsHide: true, + }); + if (res.error) + return { + ok: false, + reason: + (res.error as NodeJS.ErrnoException).code === "ENOENT" + ? "not-found" + : String(res.error), + }; + if (res.status === 0) return { ok: true }; + if ( + process.platform === "win32" && + (res.status === 9009 || CMD_NOT_FOUND_RE.test(res.stderr ?? "")) + ) + return { ok: false, reason: "not-found" }; + const detail = (res.stderr ?? "").trim(); + return { ok: false, reason: detail || `exit ${res.status}` }; + } catch (err) { + return { + ok: false, + reason: err instanceof Error ? err.message : String(err), + }; + } } function hermesInstallCore(): void { - const root = selfPackageRoot(); - const initSrc = fs.readFileSync( - path.join(root, "hermes-plugin", "__init__.py"), - "utf8", - ); - const yamlSrc = fs.readFileSync( - path.join(root, "hermes-plugin", "plugin.yaml"), - "utf8", - ); - requireDistFile(path.join(root, "dist", "index.js")); - const dir = hermesPluginDir(); - fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync(path.join(dir, "__init__.py"), initSrc); - fs.writeFileSync( - path.join(dir, "plugin.yaml"), - yamlSrc.replace(/^version:.*/m, `version: "${selfVersion()}"`), - ); - const sidecar: HermesSidecar = { - proxyScript: path.join(root, "dist", "index.js"), - nodePath: process.execPath, - }; - fs.writeFileSync( - path.join(dir, "bili.json"), - `${JSON.stringify(sidecar, null, 2)}\n`, - ); + const root = selfPackageRoot(); + const initSrc = fs.readFileSync( + path.join(root, "hermes-plugin", "__init__.py"), + "utf8", + ); + const yamlSrc = fs.readFileSync( + path.join(root, "hermes-plugin", "plugin.yaml"), + "utf8", + ); + requireDistFile(path.join(root, "dist", "index.js")); + const dir = hermesPluginDir(); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, "__init__.py"), initSrc); + fs.writeFileSync( + path.join(dir, "plugin.yaml"), + yamlSrc.replace(/^version:.*/m, `version: "${selfVersion()}"`), + ); + const sidecar: HermesSidecar = { + proxyScript: path.join(root, "dist", "index.js"), + nodePath: process.execPath, + }; + fs.writeFileSync( + path.join(dir, "bili.json"), + `${JSON.stringify(sidecar, null, 2)}\n`, + ); } function hermesInstall(): string { - hermesInstallCore(); - const dir = hermesPluginDir(); - const enable = runHermesCli(["plugins", "enable", HERMES_PLUGIN_ID]); - if (enable.ok) - return `wrote the billion-context plugin into ${dir} and enabled it — start a new hermes session to activate`; - const hint = - enable.reason === "not-found" - ? "the hermes CLI was not found on PATH — enable it manually: hermes plugins enable billion-context" - : `enabling via the hermes CLI failed (${enable.reason}) — enable it manually: hermes plugins enable billion-context`; - return `wrote the billion-context plugin into ${dir}; ${hint}`; + hermesInstallCore(); + const dir = hermesPluginDir(); + const enable = runHermesCli(["plugins", "enable", HERMES_PLUGIN_ID]); + if (enable.ok) + return `wrote the billion-context plugin into ${dir} and enabled it — start a new hermes session to activate`; + const hint = + enable.reason === "not-found" + ? "the hermes CLI was not found on PATH — enable it manually: hermes plugins enable billion-context" + : `enabling via the hermes CLI failed (${enable.reason}) — enable it manually: hermes plugins enable billion-context`; + return `wrote the billion-context plugin into ${dir}; ${hint}`; } function hermesRemove(): string { - const dir = hermesPluginDir(); - if (!fs.existsSync(dir)) return "not installed"; - fs.rmSync(dir, { recursive: true, force: true }); - const disable = runHermesCli(["plugins", "disable", HERMES_PLUGIN_ID]); - return disable.ok - ? `removed the billion-context plugin (${dir}) and disabled it — start a new hermes session to finish` - : `removed the billion-context plugin (${dir}); if hermes still lists it, disable it manually: hermes plugins disable billion-context`; + const dir = hermesPluginDir(); + if (!fs.existsSync(dir)) return "not installed"; + fs.rmSync(dir, { recursive: true, force: true }); + const disable = runHermesCli(["plugins", "disable", HERMES_PLUGIN_ID]); + return disable.ok + ? `removed the billion-context plugin (${dir}) and disabled it — start a new hermes session to finish` + : `removed the billion-context plugin (${dir}); if hermes still lists it, disable it manually: hermes plugins disable billion-context`; } function hermesStatus(): string { - const dir = hermesPluginDir(); - return fs.existsSync(path.join(dir, "__init__.py")) && - fs.existsSync(path.join(dir, "bili.json")) - ? "installed" - : "not installed"; + const dir = hermesPluginDir(); + return fs.existsSync(path.join(dir, "__init__.py")) && + fs.existsSync(path.join(dir, "bili.json")) + ? "installed" + : "not installed"; } // — dispatch ———————————————————————————————————————————————————————————— @@ -2556,34 +2556,34 @@ const ZCODE_HOOK_ENTRY_RE = /(?:^|[\\/])zcode[\\/]bootstrap-hook\.(?:js|ts)$/; const ZCODE_MCP_ENTRY_RE = /(?:^|[\\/])zcode[\\/]mcp-entry\.(?:js|ts)$/; function zcodeUserConfigFile(): string { - return path.join(os.homedir(), ".zcode", "cli", "config.json"); + return path.join(os.homedir(), ".zcode", "cli", "config.json"); } function zcodeAsPlain(value: unknown): Record | undefined { - return value !== null && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : undefined; + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; } function zcodeArgsMatch(args: unknown, re: RegExp): boolean { - return ( - Array.isArray(args) && args.some((a) => typeof a === "string" && re.test(a)) - ); + return ( + Array.isArray(args) && args.some((a) => typeof a === "string" && re.test(a)) + ); } function isOursZcodeHookEntry(entry: unknown): boolean { - const hooks = zcodeAsPlain(entry)?.hooks; - if (!Array.isArray(hooks)) return false; - return hooks.some((h) => - zcodeArgsMatch(zcodeAsPlain(h)?.args, ZCODE_HOOK_ENTRY_RE), - ); + const hooks = zcodeAsPlain(entry)?.hooks; + if (!Array.isArray(hooks)) return false; + return hooks.some((h) => + zcodeArgsMatch(zcodeAsPlain(h)?.args, ZCODE_HOOK_ENTRY_RE), + ); } function isOursZcodeMcpServer(server: unknown): boolean { - const s = zcodeAsPlain(server); - return ( - !!s && s.type === "stdio" && zcodeArgsMatch(s.args, ZCODE_MCP_ENTRY_RE) - ); + const s = zcodeAsPlain(server); + return ( + !!s && s.type === "stdio" && zcodeArgsMatch(s.args, ZCODE_MCP_ENTRY_RE) + ); } /** Managed-block apply for ~/.zcode/cli/config.json (#1145). Pure over the @@ -2591,156 +2591,156 @@ function isOursZcodeMcpServer(server: unknown): boolean { * mcp.servers.bili when it already points at our dist — a user's own "bili" * server throws instead of being clobbered (§7.3). */ function applyZcodeManagedConfig( - doc: Record, - opts: { hookEntry: string; mcpEntry: string }, + doc: Record, + opts: { hookEntry: string; mcpEntry: string }, ): { data: Record; notes: string[] } { - const data = structuredClone(doc); - const notes: string[] = []; - const hooks = zcodeAsPlain(data.hooks) ?? {}; - if (hooks.enabled !== true) { - hooks.enabled = true; - notes.push("enabled hooks (hooks.enabled was off)"); - } - const events = zcodeAsPlain(hooks.events) ?? {}; - const sessionStart = Array.isArray(events.SessionStart) - ? [...(events.SessionStart as unknown[])] - : []; - const kept = sessionStart.filter((e) => !isOursZcodeHookEntry(e)); - if (kept.length !== sessionStart.length) - notes.push("replaced a previous bili SessionStart entry"); - kept.push({ - hooks: [{ type: "process", command: "node", args: [opts.hookEntry] }], - }); - events.SessionStart = kept; - hooks.events = events; - data.hooks = hooks; - const mcp = zcodeAsPlain(data.mcp) ?? {}; - const servers = zcodeAsPlain(mcp.servers) ?? {}; - if (servers.bili !== undefined && !isOursZcodeMcpServer(servers.bili)) { - throw new Error( - `${zcodeUserConfigFile()} already defines mcp.servers.bili owned by something else — rename or remove it first; refusing to overwrite`, - ); - } - servers.bili = { type: "stdio", command: "node", args: [opts.mcpEntry] }; - mcp.servers = servers; - data.mcp = mcp; - return { data, notes }; + const data = structuredClone(doc); + const notes: string[] = []; + const hooks = zcodeAsPlain(data.hooks) ?? {}; + if (hooks.enabled !== true) { + hooks.enabled = true; + notes.push("enabled hooks (hooks.enabled was off)"); + } + const events = zcodeAsPlain(hooks.events) ?? {}; + const sessionStart = Array.isArray(events.SessionStart) + ? [...(events.SessionStart as unknown[])] + : []; + const kept = sessionStart.filter((e) => !isOursZcodeHookEntry(e)); + if (kept.length !== sessionStart.length) + notes.push("replaced a previous bili SessionStart entry"); + kept.push({ + hooks: [{ type: "process", command: "node", args: [opts.hookEntry] }], + }); + events.SessionStart = kept; + hooks.events = events; + data.hooks = hooks; + const mcp = zcodeAsPlain(data.mcp) ?? {}; + const servers = zcodeAsPlain(mcp.servers) ?? {}; + if (servers.bili !== undefined && !isOursZcodeMcpServer(servers.bili)) { + throw new Error( + `${zcodeUserConfigFile()} already defines mcp.servers.bili owned by something else — rename or remove it first; refusing to overwrite`, + ); + } + servers.bili = { type: "stdio", command: "node", args: [opts.mcpEntry] }; + mcp.servers = servers; + data.mcp = mcp; + return { data, notes }; } function stripZcodeManagedConfig(doc: Record): { - data: Record; - removed: string[]; + data: Record; + removed: string[]; } { - const data = structuredClone(doc); - const removed: string[] = []; - const hooks = zcodeAsPlain(data.hooks); - if (hooks) { - const events = zcodeAsPlain(hooks.events); - if (events && Array.isArray(events.SessionStart)) { - const kept = (events.SessionStart as unknown[]).filter( - (e) => !isOursZcodeHookEntry(e), - ); - if (kept.length !== (events.SessionStart as unknown[]).length) { - removed.push("hooks.events.SessionStart entry"); - if (kept.length > 0) events.SessionStart = kept; - else delete events.SessionStart; - if (Object.keys(events).length === 0) delete hooks.events; - if (Object.keys(hooks).length === 0) delete data.hooks; - } - } - } - const mcp = zcodeAsPlain(data.mcp); - if (mcp) { - const servers = zcodeAsPlain(mcp.servers); - if ( - servers && - servers.bili !== undefined && - isOursZcodeMcpServer(servers.bili) - ) { - removed.push("mcp.servers.bili"); - delete servers.bili; - if (Object.keys(servers).length === 0) delete mcp.servers; - if (Object.keys(mcp).length === 0) delete data.mcp; - } - } - return { data, removed }; + const data = structuredClone(doc); + const removed: string[] = []; + const hooks = zcodeAsPlain(data.hooks); + if (hooks) { + const events = zcodeAsPlain(hooks.events); + if (events && Array.isArray(events.SessionStart)) { + const kept = (events.SessionStart as unknown[]).filter( + (e) => !isOursZcodeHookEntry(e), + ); + if (kept.length !== (events.SessionStart as unknown[]).length) { + removed.push("hooks.events.SessionStart entry"); + if (kept.length > 0) events.SessionStart = kept; + else delete events.SessionStart; + if (Object.keys(events).length === 0) delete hooks.events; + if (Object.keys(hooks).length === 0) delete data.hooks; + } + } + } + const mcp = zcodeAsPlain(data.mcp); + if (mcp) { + const servers = zcodeAsPlain(mcp.servers); + if ( + servers && + servers.bili !== undefined && + isOursZcodeMcpServer(servers.bili) + ) { + removed.push("mcp.servers.bili"); + delete servers.bili; + if (Object.keys(servers).length === 0) delete mcp.servers; + if (Object.keys(mcp).length === 0) delete data.mcp; + } + } + return { data, removed }; } function zcodeInstall(): string { - const root = selfPackageRoot(); - const hookEntry = path.join(root, "dist", "zcode", "bootstrap-hook.js"); - const mcpEntry = path.join(root, "dist", "zcode", "mcp-entry.js"); - requireDistFile(hookEntry); - requireDistFile(mcpEntry); - const file = zcodeUserConfigFile(); - const { data, notes } = applyZcodeManagedConfig(readJson(file), { - hookEntry, - mcpEntry, - }); - writeJson(file, data); - return `wrote the billion-context hook+MCP into ${file}${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new ZCode session to activate`; + const root = selfPackageRoot(); + const hookEntry = path.join(root, "dist", "zcode", "bootstrap-hook.js"); + const mcpEntry = path.join(root, "dist", "zcode", "mcp-entry.js"); + requireDistFile(hookEntry); + requireDistFile(mcpEntry); + const file = zcodeUserConfigFile(); + const { data, notes } = applyZcodeManagedConfig(readJson(file), { + hookEntry, + mcpEntry, + }); + writeJson(file, data); + return `wrote the billion-context hook+MCP into ${file}${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new ZCode session to activate`; } function zcodeRemove(): string { - const file = zcodeUserConfigFile(); - const notes: string[] = []; - try { - const doc = readJson(file); - const { data, removed } = stripZcodeManagedConfig(doc); - if (removed.length > 0) { - // Revert hooks.enabled only when the pre-install snapshot shows we - // are the reason it is on (never drop a user-owned switch). - let bak: Record | undefined; - try { - bak = JSON.parse(fs.readFileSync(`${file}.bili-bak`, "utf8")) as Record< - string, - unknown - >; - } catch {} - const hooks = zcodeAsPlain(data.hooks); - if (hooks && Object.keys(hooks).length === 1 && hooks.enabled === true) { - const bakEnabled = zcodeAsPlain(bak?.hooks)?.enabled === true; - if (!bakEnabled) delete hooks.enabled; - if (Object.keys(hooks).length === 0) delete data.hooks; - } - writeJson(file, data); - } - for (const r of removed) notes.push(`removed ${r}`); - } catch {} - const restored = restoreZcodeBackup({ log: (msg) => notes.push(msg) }); - if (!restored.restored) unrouteZcode({ log: () => {} }); - return notes.length > 0 - ? `removed the billion-context zcode lane (${notes.join("; ")}) — start a new ZCode session to finish` - : "not installed"; + const file = zcodeUserConfigFile(); + const notes: string[] = []; + try { + const doc = readJson(file); + const { data, removed } = stripZcodeManagedConfig(doc); + if (removed.length > 0) { + // Revert hooks.enabled only when the pre-install snapshot shows we + // are the reason it is on (never drop a user-owned switch). + let bak: Record | undefined; + try { + bak = JSON.parse(fs.readFileSync(`${file}.bili-bak`, "utf8")) as Record< + string, + unknown + >; + } catch {} + const hooks = zcodeAsPlain(data.hooks); + if (hooks && Object.keys(hooks).length === 1 && hooks.enabled === true) { + const bakEnabled = zcodeAsPlain(bak?.hooks)?.enabled === true; + if (!bakEnabled) delete hooks.enabled; + if (Object.keys(hooks).length === 0) delete data.hooks; + } + writeJson(file, data); + } + for (const r of removed) notes.push(`removed ${r}`); + } catch {} + const restored = restoreZcodeBackup({ log: (msg) => notes.push(msg) }); + if (!restored.restored) unrouteZcode({ log: () => {} }); + return notes.length > 0 + ? `removed the billion-context zcode lane (${notes.join("; ")}) — start a new ZCode session to finish` + : "not installed"; } function zcodeStatus(): string { - let hasHook = false; - let hasMcp = false; - try { - const doc = readJson(zcodeUserConfigFile()); - const sessionStart = zcodeAsPlain( - zcodeAsPlain(doc.hooks)?.events, - )?.SessionStart; - hasHook = - Array.isArray(sessionStart) && - (sessionStart as unknown[]).some(isOursZcodeHookEntry); - hasMcp = isOursZcodeMcpServer( - zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili, - ); - } catch {} - let status = - hasHook && hasMcp - ? "installed" - : hasHook || hasMcp - ? "partially installed — rerun 'bili plugin install zcode' to fix" - : "not installed"; - try { - const routed = inspectZcodeRouting(resolveZcodeDataDir(process.env)); - if (routed && routed.wrapped.length > 0) - status += ` (routing ${routed.kind} store: ${routed.wrapped.map((w) => w.id).join(", ")})`; - } catch {} - return status; + let hasHook = false; + let hasMcp = false; + try { + const doc = readJson(zcodeUserConfigFile()); + const sessionStart = zcodeAsPlain( + zcodeAsPlain(doc.hooks)?.events, + )?.SessionStart; + hasHook = + Array.isArray(sessionStart) && + (sessionStart as unknown[]).some(isOursZcodeHookEntry); + hasMcp = isOursZcodeMcpServer( + zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili, + ); + } catch {} + let status = + hasHook && hasMcp + ? "installed" + : hasHook || hasMcp + ? "partially installed — rerun 'bili plugin install zcode' to fix" + : "not installed"; + try { + const routed = inspectZcodeRouting(resolveZcodeDataDir(process.env)); + if (routed && routed.wrapped.length > 0) + status += ` (routing ${routed.kind} store: ${routed.wrapped.map((w) => w.id).join(", ")})`; + } catch {} + return status; } // — doctor (#1235) ————————————————————————————————————————————————————— @@ -2751,40 +2751,40 @@ function zcodeStatus(): string { * malformed config; single-source probes (pi/opencode/zcode) propagate the * parse error so doctor reports a broken probe instead of a false "absent". */ interface LanePresence { - installed: boolean; - pointers: string[]; - targets: string[]; - form: "npm" | "local-path" | "managed-block" | "none"; - copyVersion?: string; - profiles?: Array<{ - name: string; - spec?: string; - pinned: boolean; - bundleInstalled: boolean; - copyVersion?: string; - }>; + installed: boolean; + pointers: string[]; + targets: string[]; + form: "npm" | "local-path" | "managed-block" | "none"; + copyVersion?: string; + profiles?: Array<{ + name: string; + spec?: string; + pinned: boolean; + bundleInstalled: boolean; + copyVersion?: string; + }>; } function laneAbsent(): LanePresence { - return { installed: false, pointers: [], targets: [], form: "none" }; + return { installed: false, pointers: [], targets: [], form: "none" }; } function pkgVersionAt(rootDir: string): string | undefined { - try { - const v = ( - JSON.parse( - fs.readFileSync(path.join(rootDir, "package.json"), "utf8"), - ) as { version?: unknown } - ).version; - return typeof v === "string" ? v : undefined; - } catch { - return undefined; - } + try { + const v = ( + JSON.parse( + fs.readFileSync(path.join(rootDir, "package.json"), "utf8"), + ) as { version?: unknown } + ).version; + return typeof v === "string" ? v : undefined; + } catch { + return undefined; + } } /** Package root three levels above a /dist//.js entry. */ function rootFromDistFile(file: string): string { - return path.dirname(path.dirname(path.dirname(file))); + return path.dirname(path.dirname(path.dirname(file))); } // #2260(F): cache spec slots are `billion-context@`; for registry @@ -2793,30 +2793,30 @@ function rootFromDistFile(file: string): string { // segment; anything non-numeric ("latest", file: specs) falls back to plain // string order — same relative position as before. function compareSpecSlots(a: string, b: string): number { - const SPEC_PREFIX = "billion-context@"; - const av = a.startsWith(SPEC_PREFIX) ? a.slice(SPEC_PREFIX.length) : a; - const bv = b.startsWith(SPEC_PREFIX) ? b.slice(SPEC_PREFIX.length) : b; - const segments = (s: string): number[] | null => { - const parts = s.split("."); - if (parts.length === 0) return null; - const out: number[] = []; - for (const p of parts) { - if (!/^\d+$/.test(p)) return null; - out.push(Number(p)); - } - return out; - }; - const an = segments(av); - const bn = segments(bv); - if (an !== null && bn !== null) { - const len = Math.max(an.length, bn.length); - for (let i = 0; i < len; i++) { - const d = (an[i] ?? 0) - (bn[i] ?? 0); - if (d !== 0) return d; - } - return 0; - } - return av.localeCompare(bv); + const SPEC_PREFIX = "billion-context@"; + const av = a.startsWith(SPEC_PREFIX) ? a.slice(SPEC_PREFIX.length) : a; + const bv = b.startsWith(SPEC_PREFIX) ? b.slice(SPEC_PREFIX.length) : b; + const segments = (s: string): number[] | null => { + const parts = s.split("."); + if (parts.length === 0) return null; + const out: number[] = []; + for (const p of parts) { + if (!/^\d+$/.test(p)) return null; + out.push(Number(p)); + } + return out; + }; + const an = segments(av); + const bn = segments(bv); + if (an !== null && bn !== null) { + const len = Math.max(an.length, bn.length); + for (let i = 0; i < len; i++) { + const d = (an[i] ?? 0) - (bn[i] ?? 0); + if (d !== 0) return d; + } + return 0; + } + return av.localeCompare(bv); } /** #1234/#2199: on-disk root of the OpenCode v2 cache copy of billion-context — @@ -2828,437 +2828,437 @@ function compareSpecSlots(a: string, b: string): number { * package.json/package-lock.json nor deletes its cache, so drift between the * outer lockfile and the inner package version is expected and left alone. */ export function opencodeCacheCopyRoot( - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = process.env, ): string | undefined { - const xdgCache = - env.XDG_CACHE_HOME && env.XDG_CACHE_HOME.trim().length > 0 - ? env.XDG_CACHE_HOME - : path.join(os.homedir(), ".cache"); - const npm = path.join(xdgCache, "opencode", "npm"); - let slots: string[]; - try { - slots = fs.readdirSync(npm); - } catch { - return undefined; - } - for (const slot of slots - .filter((s) => s.startsWith("billion-context@")) - .sort(compareSpecSlots) - .reverse()) { - let stamps: string[]; - try { - stamps = fs.readdirSync(path.join(npm, slot)); - } catch { - continue; - } - for (const stamp of stamps.sort().reverse()) { - const root = path.join(npm, slot, stamp, "node_modules", DSH_PACKAGE); - try { - fs.accessSync(root); - return root; - } catch {} - } - } - return undefined; + const xdgCache = + env.XDG_CACHE_HOME && env.XDG_CACHE_HOME.trim().length > 0 + ? env.XDG_CACHE_HOME + : path.join(os.homedir(), ".cache"); + const npm = path.join(xdgCache, "opencode", "npm"); + let slots: string[]; + try { + slots = fs.readdirSync(npm); + } catch { + return undefined; + } + for (const slot of slots + .filter((s) => s.startsWith("billion-context@")) + .sort(compareSpecSlots) + .reverse()) { + let stamps: string[]; + try { + stamps = fs.readdirSync(path.join(npm, slot)); + } catch { + continue; + } + for (const stamp of stamps.sort().reverse()) { + const root = path.join(npm, slot, stamp, "node_modules", DSH_PACKAGE); + try { + fs.accessSync(root); + return root; + } catch {} + } + } + return undefined; } export function inspectLanePresence(agent: PluginAgent): LanePresence { - if (agent === "pi") { - const root = selfPackageRoot(); - const packages = readJson(piSettingsFile()).packages; - const list = Array.isArray(packages) - ? (packages as unknown[]).map(String) - : []; - const entries = list.filter( - (p) => isBiliPiEntry(p, root) || p === piEntryFor(root), - ); - if (entries.length === 0) return laneAbsent(); - // #2850: every npm spec form (plain / @pinned / @latest) resolves to - // the SAME pi-managed copy directory — the spec suffix never changes - // the folder name — so match the form, not just the exact unpinned - // string, and probe the real materialization path (piNpmCopyRoot). - if (entries.some((p) => /^npm:billion-context(@|$)/.test(p))) { - const store = piNpmCopyRoot(process.env); - return { - installed: true, - pointers: entries, - targets: fs.existsSync(store) ? [store] : [], - form: "npm", - copyVersion: pkgVersionAt(store), - }; - } - const abs = entries.find((p) => path.isAbsolute(p)); - return { - installed: true, - pointers: entries, - targets: abs !== undefined ? [abs] : [], - form: "local-path", - copyVersion: abs !== undefined ? pkgVersionAt(abs) : undefined, - }; - } - if (agent === "omp") { - let text: string; - try { - text = fs.readFileSync(ompConfigFile(), "utf8"); - } catch { - return laneAbsent(); - } - const lines = text.split("\n"); - const values = ompExtensionItemLines(text) - .map((i) => ompEntryValue(lines[i]!)) - .filter((v) => OMP_ENTRY_RE.test(v)); - if (values.length === 0) return laneAbsent(); - const targets = values.filter((v) => path.isAbsolute(v)); - const first = targets[0]; - return { - installed: true, - pointers: values, - targets, - form: "local-path", - copyVersion: - first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, - }; - } - if (agent === "claude") { - const out = laneAbsent(); - try { - const data = readJson(claudeSettingsFile()); - const baseUrl = (data.env as Record | undefined) - ?.ANTHROPIC_BASE_URL; - if (typeof baseUrl === "string" && isBiliClaudeBaseUrl(baseUrl)) { - out.installed = true; - out.pointers.push(`env.ANTHROPIC_BASE_URL=${baseUrl}`); - } - } catch {} - try { - const mcpData = readJson(claudeMcpJson()) as { - mcpServers?: Record; - }; - const bili = mcpData.mcpServers?.bili; - if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { - const s = bili as Record; - out.installed = true; - const args = Array.isArray(s.args) - ? (s.args as unknown[]).map(String) - : []; - out.pointers.push( - [s.command, ...args] - .filter((x) => typeof x === "string" && x.length > 0) - .join(" "), - ); - const script = args[0]; - if (script !== undefined && path.isAbsolute(script)) { - out.targets.push(script); - out.copyVersion = - out.copyVersion ?? pkgVersionAt(rootFromDistFile(script)); - } - } - } catch {} - if (out.installed) out.form = "managed-block"; - return out; - } - if (agent === "codex") { - let text: string; - try { - text = fs.readFileSync(codexToml(), "utf8"); - } catch { - return laneAbsent(); - } - if (!/^\[mcp_servers\.bili\]\s*$/m.test(text)) return laneAbsent(); - const start = text.indexOf("[mcp_servers.bili]"); - const rest = text.slice(start); - const nextSection = /^\[[^\]\n]+\]/m.exec(rest.slice(1)); - const block = - nextSection !== null ? rest.slice(0, 1 + nextSection.index) : rest; - const unquote = (raw: string): string => { - try { - const parsed: unknown = JSON.parse(raw); - return typeof parsed === "string" - ? parsed - : raw.replace(/^["']|["']$/g, ""); - } catch { - return raw.replace(/^["']|["']$/g, ""); - } - }; - const cmdMatch = /^command\s*=\s*(.+?)\s*$/m.exec(block); - const command = cmdMatch?.[1] ? unquote(cmdMatch[1]) : ""; - const argsMatch = /^args\s*=\s*\[(.*)\]\s*$/m.exec(block); - let args: string[] = []; - if (argsMatch?.[1]) { - try { - args = (JSON.parse(`[${argsMatch[1]}]`) as unknown[]).filter( - (x): x is string => typeof x === "string", - ); - } catch { - args = [...argsMatch[1].matchAll(/["']([^"']*)["']/g)].map( - (m) => m[1]!, - ); - } - } - const targets = args.filter((a) => path.isAbsolute(a) && /\.js$/.test(a)); - const first = targets[0]; - const out: LanePresence = { - installed: true, - pointers: [ - `[mcp_servers.bili] command=${command || "?"} args=[${args.join(", ")}]`, - ], - targets, - form: "managed-block", - copyVersion: - first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, - }; - // Ticket 08 faces, reported next to (never instead of) the MCP block: a - // session hook and the ACP skill are separate integration surfaces, so a - // lane missing only one of them must not read as fully installed. - const hookCommand = findBiliCodexHook(text); - if (hookCommand !== undefined) { - out.pointers.push(`hooks.SessionStart: ${hookCommand}`); - const hookDisabled = codexHooksEnabledNote(text); - if (hookDisabled !== "") - out.pointers.push(`hooks disabled — ${hookDisabled}`); - } else { - out.pointers.push("hooks.SessionStart: not installed"); - } - const skillState = codexSkillStatus(process.env); - out.pointers.push( - skillState === "installed" - ? `skill: ${codexSkillFile(process.env)}` - : skillState === "outdated" - ? "skill: outdated (rerun install)" - : skillState === "foreign" - ? "skill: not owned by bili (left untouched)" - : "skill: not installed", - ); - return out; - } - if (agent === "opencode") { - const file = opencodeTargetFile(); - const { data } = loadOpencodeConfig(file); - const dir = opencodePluginDir(file); - const listed = PLUGIN_KEYS.flatMap((k) => pluginEntries(data, k)).filter( - (p) => p === OPENCODE_NPM_ENTRY || p === dir, - ); - const hasMcp = isPlainMcpObject(data.mcp) && "bili" in data.mcp; - if (listed.length === 0 && !hasMcp) return laneAbsent(); - const out: LanePresence = { - installed: true, - pointers: [...listed], - targets: [], - form: "none", - }; - if (hasMcp) out.pointers.push("mcp.bili"); - if (listed.includes(OPENCODE_NPM_ENTRY)) { - out.form = "npm"; - // #1234/#2199: the bare npm entry is materialized into opencode's - // cache — surface the actual copy root + disk version so doctor can - // report staleness honestly instead of "version not resolvable". - const cacheRoot = opencodeCacheCopyRoot(); - if (cacheRoot !== undefined) { - out.targets.push(cacheRoot); - out.copyVersion = pkgVersionAt(cacheRoot); - } - } else if (listed.includes(dir)) { - out.form = "local-path"; - out.targets.push(path.join(dir, "index.js")); - out.copyVersion = pkgVersionAt(dir); - } - return out; - } - if (agent === "dsh") { - let dirs: string[]; - try { - dirs = dshProfileDirs(); - } catch { - return laneAbsent(); - } - const profiles = dirs.flatMap((dir) => { - const spec = dshProfileDepSpec(dir); - const bundled = dshBundleInstalled(dir); - if (spec === undefined && !bundled) return []; - return [ - { - name: path.basename(dir), - spec, - pinned: spec !== undefined && !isRegistryDepSpec(spec), - bundleInstalled: bundled, - copyVersion: bundled - ? pkgVersionAt(path.join(dir, "node_modules", DSH_PACKAGE)) - : undefined, - }, - ]; - }); - if (profiles.length === 0) return laneAbsent(); - return { - installed: true, - pointers: profiles.map((p) => `${p.name}: ${p.spec ?? "(no dep)"}`), - targets: [], - form: profiles.some((p) => p.pinned) ? "local-path" : "npm", - profiles, - }; - } - if (agent === "kimi") { - const manifestFile = path.join(kimiManagedDir(), "kimi.plugin.json"); - const manifestOk = fs.existsSync(manifestFile); - let registered = false; - try { - registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some( - (p) => p.id === KIMI_PLUGIN_ID, - ); - } catch {} - if (!manifestOk && !registered) return laneAbsent(); - const out: LanePresence = { - installed: manifestOk && registered, - pointers: [], - targets: [], - form: "local-path", - }; - if (!out.installed) - out.pointers.push( - manifestOk - ? "manifest present but registry record missing" - : "registry record present but manifest missing", - ); - try { - const man = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as Record< - string, - unknown - >; - if (typeof man.version === "string") out.copyVersion = man.version; - const mcpArgs = zcodeAsPlain(zcodeAsPlain(man.mcpServers)?.bili)?.args; - for (const a of Array.isArray(mcpArgs) - ? (mcpArgs as unknown[]).map(String) - : []) { - if (path.isAbsolute(a)) out.targets.push(a); - } - const hookCmd = Array.isArray(man.hooks) - ? (man.hooks as unknown[]) - .map((h) => zcodeAsPlain(h)?.command) - .find((c): c is string => typeof c === "string") - : undefined; - if (hookCmd !== undefined) { - const script = hookCmd.trim().split(/\s+/).pop(); - if (script !== undefined && path.isAbsolute(script)) - out.targets.push(script); - } - } catch {} - return out; - } - if (agent === "hermes") { - const dir = hermesPluginDir(); - if (!fs.existsSync(path.join(dir, "__init__.py"))) return laneAbsent(); - const out: LanePresence = { - installed: true, - pointers: [dir], - targets: [], - form: "local-path", - }; - try { - const sidecar = JSON.parse( - fs.readFileSync(path.join(dir, "bili.json"), "utf8"), - ) as HermesSidecar; - if ( - typeof sidecar.proxyScript === "string" && - sidecar.proxyScript.length > 0 - ) - out.targets.push(sidecar.proxyScript); - } catch {} - try { - const yaml = fs.readFileSync(path.join(dir, "plugin.yaml"), "utf8"); - const m = /^version:\s*["']?([^"'\r\n]+?)["']?\s*$/m.exec(yaml); - if (m?.[1]) out.copyVersion = m[1]; - } catch {} - return out; - } - // zcode - const doc = readJson(zcodeUserConfigFile()); - const sessionStart = zcodeAsPlain( - zcodeAsPlain(doc.hooks)?.events, - )?.SessionStart; - const hasHook = - Array.isArray(sessionStart) && - (sessionStart as unknown[]).some(isOursZcodeHookEntry); - const mcpBili = zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili; - const hasMcp = isOursZcodeMcpServer(mcpBili); - if (!hasHook && !hasMcp) return laneAbsent(); - const out: LanePresence = { - installed: hasHook && hasMcp, - pointers: [], - targets: [], - form: "managed-block", - }; - if (!out.installed) - out.pointers.push( - hasHook - ? "hook present, MCP face missing" - : "MCP face present, hook missing", - ); - const collectArgs = (args: unknown): void => { - for (const a of Array.isArray(args) - ? (args as unknown[]).map(String) - : []) { - if (path.isAbsolute(a) && /\.(js|ts)$/.test(a)) out.targets.push(a); - } - }; - if (Array.isArray(sessionStart)) { - for (const e of sessionStart as unknown[]) { - if (!isOursZcodeHookEntry(e)) continue; - const hooks = zcodeAsPlain(e)?.hooks; - if (Array.isArray(hooks)) - for (const h of hooks as unknown[]) collectArgs(zcodeAsPlain(h)?.args); - } - } - if (hasMcp) collectArgs(zcodeAsPlain(mcpBili)?.args); - const first = out.targets[0]; - if (first !== undefined) - out.copyVersion = pkgVersionAt(rootFromDistFile(first)); - return out; + if (agent === "pi") { + const root = selfPackageRoot(); + const packages = readJson(piSettingsFile()).packages; + const list = Array.isArray(packages) + ? (packages as unknown[]).map(String) + : []; + const entries = list.filter( + (p) => isBiliPiEntry(p, root) || p === piEntryFor(root), + ); + if (entries.length === 0) return laneAbsent(); + // #2850: every npm spec form (plain / @pinned / @latest) resolves to + // the SAME pi-managed copy directory — the spec suffix never changes + // the folder name — so match the form, not just the exact unpinned + // string, and probe the real materialization path (piNpmCopyRoot). + if (entries.some((p) => /^npm:billion-context(@|$)/.test(p))) { + const store = piNpmCopyRoot(process.env); + return { + installed: true, + pointers: entries, + targets: fs.existsSync(store) ? [store] : [], + form: "npm", + copyVersion: pkgVersionAt(store), + }; + } + const abs = entries.find((p) => path.isAbsolute(p)); + return { + installed: true, + pointers: entries, + targets: abs !== undefined ? [abs] : [], + form: "local-path", + copyVersion: abs !== undefined ? pkgVersionAt(abs) : undefined, + }; + } + if (agent === "omp") { + let text: string; + try { + text = fs.readFileSync(ompConfigFile(), "utf8"); + } catch { + return laneAbsent(); + } + const lines = text.split("\n"); + const values = ompExtensionItemLines(text) + .map((i) => ompEntryValue(lines[i]!)) + .filter((v) => OMP_ENTRY_RE.test(v)); + if (values.length === 0) return laneAbsent(); + const targets = values.filter((v) => path.isAbsolute(v)); + const first = targets[0]; + return { + installed: true, + pointers: values, + targets, + form: "local-path", + copyVersion: + first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, + }; + } + if (agent === "claude") { + const out = laneAbsent(); + try { + const data = readJson(claudeSettingsFile()); + const baseUrl = (data.env as Record | undefined) + ?.ANTHROPIC_BASE_URL; + if (typeof baseUrl === "string" && isBiliClaudeBaseUrl(baseUrl)) { + out.installed = true; + out.pointers.push(`env.ANTHROPIC_BASE_URL=${baseUrl}`); + } + } catch {} + try { + const mcpData = readJson(claudeMcpJson()) as { + mcpServers?: Record; + }; + const bili = mcpData.mcpServers?.bili; + if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { + const s = bili as Record; + out.installed = true; + const args = Array.isArray(s.args) + ? (s.args as unknown[]).map(String) + : []; + out.pointers.push( + [s.command, ...args] + .filter((x) => typeof x === "string" && x.length > 0) + .join(" "), + ); + const script = args[0]; + if (script !== undefined && path.isAbsolute(script)) { + out.targets.push(script); + out.copyVersion = + out.copyVersion ?? pkgVersionAt(rootFromDistFile(script)); + } + } + } catch {} + if (out.installed) out.form = "managed-block"; + return out; + } + if (agent === "codex") { + let text: string; + try { + text = fs.readFileSync(codexToml(), "utf8"); + } catch { + return laneAbsent(); + } + if (!/^\[mcp_servers\.bili\]\s*$/m.test(text)) return laneAbsent(); + const start = text.indexOf("[mcp_servers.bili]"); + const rest = text.slice(start); + const nextSection = /^\[[^\]\n]+\]/m.exec(rest.slice(1)); + const block = + nextSection !== null ? rest.slice(0, 1 + nextSection.index) : rest; + const unquote = (raw: string): string => { + try { + const parsed: unknown = JSON.parse(raw); + return typeof parsed === "string" + ? parsed + : raw.replace(/^["']|["']$/g, ""); + } catch { + return raw.replace(/^["']|["']$/g, ""); + } + }; + const cmdMatch = /^command\s*=\s*(.+?)\s*$/m.exec(block); + const command = cmdMatch?.[1] ? unquote(cmdMatch[1]) : ""; + const argsMatch = /^args\s*=\s*\[(.*)\]\s*$/m.exec(block); + let args: string[] = []; + if (argsMatch?.[1]) { + try { + args = (JSON.parse(`[${argsMatch[1]}]`) as unknown[]).filter( + (x): x is string => typeof x === "string", + ); + } catch { + args = [...argsMatch[1].matchAll(/["']([^"']*)["']/g)].map( + (m) => m[1]!, + ); + } + } + const targets = args.filter((a) => path.isAbsolute(a) && /\.js$/.test(a)); + const first = targets[0]; + const out: LanePresence = { + installed: true, + pointers: [ + `[mcp_servers.bili] command=${command || "?"} args=[${args.join(", ")}]`, + ], + targets, + form: "managed-block", + copyVersion: + first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, + }; + // Ticket 08 faces, reported next to (never instead of) the MCP block: a + // session hook and the ACP skill are separate integration surfaces, so a + // lane missing only one of them must not read as fully installed. + const hookCommand = findBiliCodexHook(text); + if (hookCommand !== undefined) { + out.pointers.push(`hooks.SessionStart: ${hookCommand}`); + const hookDisabled = codexHooksEnabledNote(text); + if (hookDisabled !== "") + out.pointers.push(`hooks disabled — ${hookDisabled}`); + } else { + out.pointers.push("hooks.SessionStart: not installed"); + } + const skillState = codexSkillStatus(process.env); + out.pointers.push( + skillState === "installed" + ? `skill: ${codexSkillFile(process.env)}` + : skillState === "outdated" + ? "skill: outdated (rerun install)" + : skillState === "foreign" + ? "skill: not owned by bili (left untouched)" + : "skill: not installed", + ); + return out; + } + if (agent === "opencode") { + const file = opencodeTargetFile(); + const { data } = loadOpencodeConfig(file); + const dir = opencodePluginDir(file); + const listed = PLUGIN_KEYS.flatMap((k) => pluginEntries(data, k)).filter( + (p) => p === OPENCODE_NPM_ENTRY || p === dir, + ); + const hasMcp = isPlainMcpObject(data.mcp) && "bili" in data.mcp; + if (listed.length === 0 && !hasMcp) return laneAbsent(); + const out: LanePresence = { + installed: true, + pointers: [...listed], + targets: [], + form: "none", + }; + if (hasMcp) out.pointers.push("mcp.bili"); + if (listed.includes(OPENCODE_NPM_ENTRY)) { + out.form = "npm"; + // #1234/#2199: the bare npm entry is materialized into opencode's + // cache — surface the actual copy root + disk version so doctor can + // report staleness honestly instead of "version not resolvable". + const cacheRoot = opencodeCacheCopyRoot(); + if (cacheRoot !== undefined) { + out.targets.push(cacheRoot); + out.copyVersion = pkgVersionAt(cacheRoot); + } + } else if (listed.includes(dir)) { + out.form = "local-path"; + out.targets.push(path.join(dir, "index.js")); + out.copyVersion = pkgVersionAt(dir); + } + return out; + } + if (agent === "dsh") { + let dirs: string[]; + try { + dirs = dshProfileDirs(); + } catch { + return laneAbsent(); + } + const profiles = dirs.flatMap((dir) => { + const spec = dshProfileDepSpec(dir); + const bundled = dshBundleInstalled(dir); + if (spec === undefined && !bundled) return []; + return [ + { + name: path.basename(dir), + spec, + pinned: spec !== undefined && !isRegistryDepSpec(spec), + bundleInstalled: bundled, + copyVersion: bundled + ? pkgVersionAt(path.join(dir, "node_modules", DSH_PACKAGE)) + : undefined, + }, + ]; + }); + if (profiles.length === 0) return laneAbsent(); + return { + installed: true, + pointers: profiles.map((p) => `${p.name}: ${p.spec ?? "(no dep)"}`), + targets: [], + form: profiles.some((p) => p.pinned) ? "local-path" : "npm", + profiles, + }; + } + if (agent === "kimi") { + const manifestFile = path.join(kimiManagedDir(), "kimi.plugin.json"); + const manifestOk = fs.existsSync(manifestFile); + let registered = false; + try { + registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some( + (p) => p.id === KIMI_PLUGIN_ID, + ); + } catch {} + if (!manifestOk && !registered) return laneAbsent(); + const out: LanePresence = { + installed: manifestOk && registered, + pointers: [], + targets: [], + form: "local-path", + }; + if (!out.installed) + out.pointers.push( + manifestOk + ? "manifest present but registry record missing" + : "registry record present but manifest missing", + ); + try { + const man = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as Record< + string, + unknown + >; + if (typeof man.version === "string") out.copyVersion = man.version; + const mcpArgs = zcodeAsPlain(zcodeAsPlain(man.mcpServers)?.bili)?.args; + for (const a of Array.isArray(mcpArgs) + ? (mcpArgs as unknown[]).map(String) + : []) { + if (path.isAbsolute(a)) out.targets.push(a); + } + const hookCmd = Array.isArray(man.hooks) + ? (man.hooks as unknown[]) + .map((h) => zcodeAsPlain(h)?.command) + .find((c): c is string => typeof c === "string") + : undefined; + if (hookCmd !== undefined) { + const script = hookCmd.trim().split(/\s+/).pop(); + if (script !== undefined && path.isAbsolute(script)) + out.targets.push(script); + } + } catch {} + return out; + } + if (agent === "hermes") { + const dir = hermesPluginDir(); + if (!fs.existsSync(path.join(dir, "__init__.py"))) return laneAbsent(); + const out: LanePresence = { + installed: true, + pointers: [dir], + targets: [], + form: "local-path", + }; + try { + const sidecar = JSON.parse( + fs.readFileSync(path.join(dir, "bili.json"), "utf8"), + ) as HermesSidecar; + if ( + typeof sidecar.proxyScript === "string" && + sidecar.proxyScript.length > 0 + ) + out.targets.push(sidecar.proxyScript); + } catch {} + try { + const yaml = fs.readFileSync(path.join(dir, "plugin.yaml"), "utf8"); + const m = /^version:\s*["']?([^"'\r\n]+?)["']?\s*$/m.exec(yaml); + if (m?.[1]) out.copyVersion = m[1]; + } catch {} + return out; + } + // zcode + const doc = readJson(zcodeUserConfigFile()); + const sessionStart = zcodeAsPlain( + zcodeAsPlain(doc.hooks)?.events, + )?.SessionStart; + const hasHook = + Array.isArray(sessionStart) && + (sessionStart as unknown[]).some(isOursZcodeHookEntry); + const mcpBili = zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili; + const hasMcp = isOursZcodeMcpServer(mcpBili); + if (!hasHook && !hasMcp) return laneAbsent(); + const out: LanePresence = { + installed: hasHook && hasMcp, + pointers: [], + targets: [], + form: "managed-block", + }; + if (!out.installed) + out.pointers.push( + hasHook + ? "hook present, MCP face missing" + : "MCP face present, hook missing", + ); + const collectArgs = (args: unknown): void => { + for (const a of Array.isArray(args) + ? (args as unknown[]).map(String) + : []) { + if (path.isAbsolute(a) && /\.(js|ts)$/.test(a)) out.targets.push(a); + } + }; + if (Array.isArray(sessionStart)) { + for (const e of sessionStart as unknown[]) { + if (!isOursZcodeHookEntry(e)) continue; + const hooks = zcodeAsPlain(e)?.hooks; + if (Array.isArray(hooks)) + for (const h of hooks as unknown[]) collectArgs(zcodeAsPlain(h)?.args); + } + } + if (hasMcp) collectArgs(zcodeAsPlain(mcpBili)?.args); + const first = out.targets[0]; + if (first !== undefined) + out.copyVersion = pkgVersionAt(rootFromDistFile(first)); + return out; } export function isPluginAgent(value: string): value is PluginAgent { - return (PLUGIN_AGENTS as readonly string[]).includes(value); + return (PLUGIN_AGENTS as readonly string[]).includes(value); } export function pluginInstall( - agent: PluginAgent, - opts: { withMcp?: boolean } = {}, + agent: PluginAgent, + opts: { withMcp?: boolean } = {}, ): string { - return agent === "pi" - ? piInstall() - : agent === "omp" - ? ompInstall() - : agent === "claude" - ? claudeInstall() - : agent === "codex" - ? codexInstall() - : agent === "dsh" - ? dshInstall() - : agent === "kimi" - ? kimiInstall() - : agent === "hermes" - ? hermesInstall() - : agent === "zcode" - ? zcodeInstall() - : opencodeInstall(opts.withMcp === true); + return agent === "pi" + ? piInstall() + : agent === "omp" + ? ompInstall() + : agent === "claude" + ? claudeInstall() + : agent === "codex" + ? codexInstall() + : agent === "dsh" + ? dshInstall() + : agent === "kimi" + ? kimiInstall() + : agent === "hermes" + ? hermesInstall() + : agent === "zcode" + ? zcodeInstall() + : opencodeInstall(opts.withMcp === true); } export function pluginRemove(agent: PluginAgent): string { - return agent === "pi" - ? piRemove() - : agent === "omp" - ? ompRemove() - : agent === "claude" - ? claudeRemove() - : agent === "codex" - ? codexRemove() - : agent === "dsh" - ? dshRemove() - : agent === "kimi" - ? kimiRemove() - : agent === "hermes" - ? hermesRemove() - : agent === "zcode" - ? zcodeRemove() - : opencodeRemove(); + return agent === "pi" + ? piRemove() + : agent === "omp" + ? ompRemove() + : agent === "claude" + ? claudeRemove() + : agent === "codex" + ? codexRemove() + : agent === "dsh" + ? dshRemove() + : agent === "kimi" + ? kimiRemove() + : agent === "hermes" + ? hermesRemove() + : agent === "zcode" + ? zcodeRemove() + : opencodeRemove(); } /** #2155 uninstall guardrail (advisory half): `bili plugin remove ` @@ -3268,47 +3268,47 @@ export function pluginRemove(agent: PluginAgent): string { * (degrade to proxy mode); this note closes the loop for the human. Best-effort: * any failure (no proxy, endpoint down, odd shape) stays silent. */ export async function warnActivePluginSessions( - agent: PluginAgent, + agent: PluginAgent, ): Promise { - try { - const inst = readProxyInstanceFile(); - if (inst === undefined) return ""; - const res = await fetch( - inst.origin.replace(/\/$/, "") + "/__bili/sessions", - { - signal: AbortSignal.timeout(2500), - headers: { accept: "application/json" }, - }, - ); - if (!res.ok) return ""; - const data = (await res.json()) as { - sessions?: Array>; - }; - const sessions = Array.isArray(data.sessions) ? data.sessions : []; - const cutoff = Date.now() - 10 * 60 * 1000; - let live = 0; - for (const s of sessions) { - const hint = typeof s["clientHint"] === "string" ? s["clientHint"] : ""; - const seen = - typeof s["lastSeen"] === "string" - ? Date.parse(s["lastSeen"]) - : Number.NaN; - if (hint === agent && Number.isFinite(seen) && seen >= cutoff) live += 1; - } - if (live === 0) return ""; - return `note: ${live} active ${agent} session(s) seen in the last 10 minutes — already-open client windows keep running; their plugin lane is gone and the proxy self-heals them to proxy mode (#2155). Reload/restart the client to fully detach.`; - } catch { - return ""; - } + try { + const inst = readProxyInstanceFile(); + if (inst === undefined) return ""; + const res = await fetch( + inst.origin.replace(/\/$/, "") + "/__bili/sessions", + { + signal: AbortSignal.timeout(2500), + headers: { accept: "application/json" }, + }, + ); + if (!res.ok) return ""; + const data = (await res.json()) as { + sessions?: Array>; + }; + const sessions = Array.isArray(data.sessions) ? data.sessions : []; + const cutoff = Date.now() - 10 * 60 * 1000; + let live = 0; + for (const s of sessions) { + const hint = typeof s["clientHint"] === "string" ? s["clientHint"] : ""; + const seen = + typeof s["lastSeen"] === "string" + ? Date.parse(s["lastSeen"]) + : Number.NaN; + if (hint === agent && Number.isFinite(seen) && seen >= cutoff) live += 1; + } + if (live === 0) return ""; + return `note: ${live} active ${agent} session(s) seen in the last 10 minutes — already-open client windows keep running; their plugin lane is gone and the proxy self-heals them to proxy mode (#2155). Reload/restart the client to fully detach.`; + } catch { + return ""; + } } export interface PluginStatusRow { - agent: string; - status: string; - channel: string; - /** On-disk version of the billion-context copy this lane loads (#2325); - * undefined when not resolvable from disk. */ - copyVersion?: string; + agent: string; + status: string; + channel: string; + /** On-disk version of the billion-context copy this lane loads (#2325); + * undefined when not resolvable from disk. */ + copyVersion?: string; } /** The billion-context version(s) a lane's on-disk copy actually loads @@ -3316,55 +3316,55 @@ export interface PluginStatusRow { * → the distinct per-profile versions joined with "," so cross-profile drift * stays visible. undefined when nothing is resolvable. */ function laneCopyVersion(presence: LanePresence): string | undefined { - if (!presence.installed) return undefined; - if (presence.profiles !== undefined) { - const set = [ - ...new Set( - presence.profiles - .map((p) => p.copyVersion) - .filter((v): v is string => v !== undefined), - ), - ]; - return set.length > 0 ? set.join(",") : undefined; - } - return presence.copyVersion; + if (!presence.installed) return undefined; + if (presence.profiles !== undefined) { + const set = [ + ...new Set( + presence.profiles + .map((p) => p.copyVersion) + .filter((v): v is string => v !== undefined), + ), + ]; + return set.length > 0 ? set.join(",") : undefined; + } + return presence.copyVersion; } export function pluginStatusAll(): PluginStatusRow[] { - const checks: Array<[PluginAgent, () => string]> = [ - ["pi", piStatus], - ["omp", ompStatus], - ["claude", claudeStatus], - ["codex", codexStatus], - ["opencode", opencodeStatus], - ["dsh", dshStatus], - ["kimi", kimiStatus], - ["hermes", hermesStatus], - ["zcode", zcodeStatus], - ]; - return checks.map(([agent, check]) => { - let copyVersion: string | undefined; - try { - copyVersion = laneCopyVersion(inspectLanePresence(agent)); - } catch { - copyVersion = undefined; - } - try { - return { - agent, - status: check(), - channel: UPDATE_CHANNEL[agent], - copyVersion, - }; - } catch (err) { - return { - agent, - status: `error: ${err instanceof Error ? err.message : String(err)}`, - channel: UPDATE_CHANNEL[agent], - copyVersion, - }; - } - }); + const checks: Array<[PluginAgent, () => string]> = [ + ["pi", piStatus], + ["omp", ompStatus], + ["claude", claudeStatus], + ["codex", codexStatus], + ["opencode", opencodeStatus], + ["dsh", dshStatus], + ["kimi", kimiStatus], + ["hermes", hermesStatus], + ["zcode", zcodeStatus], + ]; + return checks.map(([agent, check]) => { + let copyVersion: string | undefined; + try { + copyVersion = laneCopyVersion(inspectLanePresence(agent)); + } catch { + copyVersion = undefined; + } + try { + return { + agent, + status: check(), + channel: UPDATE_CHANNEL[agent], + copyVersion, + }; + } catch (err) { + return { + agent, + status: `error: ${err instanceof Error ? err.message : String(err)}`, + channel: UPDATE_CHANNEL[agent], + copyVersion, + }; + } + }); } // #991 single-writer: every lane's update path, user-facing. Host-managed @@ -3376,17 +3376,17 @@ export function pluginStatusAll(): PluginStatusRow[] { // bili install itself — hermes additionally re-copies its Python files via // `bili plugin update hermes`. export const UPDATE_CHANNEL: Record = { - pi: "pi update --extension npm:billion-context (pi owns the npm copy; its proxy self-drives the refresh every check cycle, #1196)", - omp: "the global bili install (entry points at it)", - claude: "the global bili install (hook/MCP point at it)", - codex: "the global bili install (the mcp launcher shells out to it)", - opencode: - "the cache copy self-updates in place via its own proxy (#1234); OpenCode v2 'plugin update' is an extra manual channel — reload/restart OpenCode after a disk update to activate", - dsh: "the global bili self-update (profile bundles track it)", - kimi: "the global bili install (plugin points at its dist)", - hermes: - "the global bili install (sidecar points at its dist); `bili plugin update hermes` re-copies the plugin", - zcode: "the global bili install (hook/MCP point at its dist)", + pi: "pi update --extension npm:billion-context (pi owns the npm copy; its proxy self-drives the refresh every check cycle, #1196)", + omp: "the global bili install (entry points at it)", + claude: "the global bili install (hook/MCP point at it)", + codex: "the global bili install (the mcp launcher shells out to it)", + opencode: + "the cache copy self-updates in place via its own proxy (#1234); OpenCode v2 'plugin update' is an extra manual channel — reload/restart OpenCode after a disk update to activate", + dsh: "the global bili self-update (profile bundles track it)", + kimi: "the global bili install (plugin points at its dist)", + hermes: + "the global bili install (sidecar points at its dist); `bili plugin update hermes` re-copies the plugin", + zcode: "the global bili install (hook/MCP point at its dist)", }; /** Render `bili plugin list` as an aligned table with a version column (#2325). @@ -3395,53 +3395,53 @@ export const UPDATE_CHANNEL: Record = { * the resolved version. It NEVER falls back to the running CLI version; the * on-disk copy may lag a still-running session until reload/restart. */ export function renderPluginList(rows: PluginStatusRow[]): string { - const cells = rows.map((r) => { - const hidden = r.status === "not installed" || r.status.startsWith("error"); - return { - agent: r.agent, - status: r.status, - version: hidden ? "—" : (r.copyVersion ?? "unknown"), - channel: hidden ? "" : r.channel, - }; - }); - const wAgent = Math.max("agent".length, ...cells.map((c) => c.agent.length)); - const wVersion = Math.max( - "version".length, - ...cells.map((c) => c.version.length), - ); - // Status is unbounded free text (multi-profile summaries, probe errors that - // carry file paths) — cap the padded width so one long row cannot stretch - // every other row out; an over-long status simply overflows its own row - // rather than being truncated. - const STATUS_CAP = 52; - const wStatus = Math.min( - STATUS_CAP, - Math.max("status".length, ...cells.map((c) => c.status.length)), - ); - const padTo = (s: string, w: number): string => s.padEnd(w); - const lines: string[] = []; - lines.push( - `${padTo("agent", wAgent)} ${padTo("status", wStatus)} ${padTo("version", wVersion)} updates via`, - ); - for (const c of cells) { - const statusCell = - c.status.length > wStatus ? c.status : padTo(c.status, wStatus); - const body = `${padTo(c.agent, wAgent)} ${statusCell} ${padTo(c.version, wVersion)}`; - lines.push( - (c.channel === "" ? body : `${body} ${c.channel}`).replace(/\s+$/, ""), - ); - } - return `${lines.join("\n")}\n`; + const cells = rows.map((r) => { + const hidden = r.status === "not installed" || r.status.startsWith("error"); + return { + agent: r.agent, + status: r.status, + version: hidden ? "—" : (r.copyVersion ?? "unknown"), + channel: hidden ? "" : r.channel, + }; + }); + const wAgent = Math.max("agent".length, ...cells.map((c) => c.agent.length)); + const wVersion = Math.max( + "version".length, + ...cells.map((c) => c.version.length), + ); + // Status is unbounded free text (multi-profile summaries, probe errors that + // carry file paths) — cap the padded width so one long row cannot stretch + // every other row out; an over-long status simply overflows its own row + // rather than being truncated. + const STATUS_CAP = 52; + const wStatus = Math.min( + STATUS_CAP, + Math.max("status".length, ...cells.map((c) => c.status.length)), + ); + const padTo = (s: string, w: number): string => s.padEnd(w); + const lines: string[] = []; + lines.push( + `${padTo("agent", wAgent)} ${padTo("status", wStatus)} ${padTo("version", wVersion)} updates via`, + ); + for (const c of cells) { + const statusCell = + c.status.length > wStatus ? c.status : padTo(c.status, wStatus); + const body = `${padTo(c.agent, wAgent)} ${statusCell} ${padTo(c.version, wVersion)}`; + lines.push( + (c.channel === "" ? body : `${body} ${c.channel}`).replace(/\s+$/, ""), + ); + } + return `${lines.join("\n")}\n`; } interface PluginUpdateOpts { - packageName: string; - resolveProxy?: (url: string) => string | undefined; - updateTag?: string; - /** Runs the global self-update check before per-lane reports. The CLI - * wires this to checkForUpdate(force); tests omit it to stay offline. */ - globalCheck?: () => Promise; - log?: (level: "info" | "warn", msg: string) => void; + packageName: string; + resolveProxy?: (url: string) => string | undefined; + updateTag?: string; + /** Runs the global self-update check before per-lane reports. The CLI + * wires this to checkForUpdate(force); tests omit it to stay offline. */ + globalCheck?: () => Promise; + log?: (level: "info" | "warn", msg: string) => void; } /** `bili plugin update [agent]` — bring every lane's bili presence up to @@ -3460,117 +3460,117 @@ interface PluginUpdateOpts { * Returns user-facing lines. Network is only touched when a dsh profile * actually depends on bili (version lookup) or globalCheck is provided. */ export async function pluginUpdate( - agents: readonly PluginAgent[] | undefined, - opts: PluginUpdateOpts, + agents: readonly PluginAgent[] | undefined, + opts: PluginUpdateOpts, ): Promise { - const log = opts.log ?? (() => {}); - const lines: string[] = []; - if (opts.globalCheck) { - await opts.globalCheck(); - lines.push( - "global bili copy: update check ran (see log above; it skips copies owned by a host)", - ); - } - for (const agent of agents ?? PLUGIN_AGENTS) { - try { - lines.push(...(await updateLane(agent as PluginAgent, opts, log))); - } catch (err) { - lines.push( - `${agent}: update failed — ${err instanceof Error ? err.message : String(err)}`, - ); - } - } - return lines; + const log = opts.log ?? (() => {}); + const lines: string[] = []; + if (opts.globalCheck) { + await opts.globalCheck(); + lines.push( + "global bili copy: update check ran (see log above; it skips copies owned by a host)", + ); + } + for (const agent of agents ?? PLUGIN_AGENTS) { + try { + lines.push(...(await updateLane(agent as PluginAgent, opts, log))); + } catch (err) { + lines.push( + `${agent}: update failed — ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + return lines; } async function updateLane( - agent: PluginAgent, - opts: PluginUpdateOpts, - log: (level: "info" | "warn", msg: string) => void, + agent: PluginAgent, + opts: PluginUpdateOpts, + log: (level: "info" | "warn", msg: string) => void, ): Promise { - if (agent === "pi") { - const packages = readJson(piSettingsFile()).packages; - const list = Array.isArray(packages) - ? (packages as unknown[]).map(String) - : []; - const root = selfPackageRoot(); - // #2850: versioned npm specs (@pinned/@latest) are the same pi-managed - // copy, not a checkout pointer — route them to the same message. - if (list.some((p) => /^npm:billion-context(@|$)/.test(p))) { - return [ - "pi: the plugin copy is pi-managed (npm:billion-context) — `pi update` upgrades it; bili never overwrites it (#991)", - ]; - } - if (list.some((p) => isPiEntry(p, root))) { - return [ - "pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes", - ]; - } - return ["pi: not installed"]; - } - if (agent === "opencode") { - const file = opencodeTargetFile(); - const { data } = loadOpencodeConfig(file); - const dir = opencodePluginDir(file); - if ( - PLUGIN_KEYS.some((k) => - pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY), - ) - ) { - const root = opencodeCacheCopyRoot(); - const ver = root !== undefined ? pkgVersionAt(root) : undefined; - const where = root !== undefined ? ` (${root})` : ""; - const v = ver !== undefined ? ` v${ver}` : ""; - return [ - `opencode: the cache copy is bili-owned and self-updates in place through its own proxy${where}${v} (#1234) — this command does NOT run opencode's upgrade; OpenCode v2 'plugin update' is an extra manual channel, and reload/restart OpenCode after a disk update to activate it`, - ]; - } - if ( - PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir)) - ) { - return [ - "opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes", - ]; - } - return ["opencode: not installed"]; - } - if (agent === "dsh") { - let dirs: string[]; - try { - dirs = dshProfileDirs(); - } catch { - return ["dsh: never initialized on this machine — nothing to update"]; - } - const targets = dirs.filter((dir) => dshProfileDependsOnBili(dir)); - if (targets.length === 0) - return ["dsh: no profile depends on billion-context — nothing to update"]; - const latest = await fetchRegistryVersion(opts, opts.packageName); - if (!latest) - return [ - "dsh: could not resolve the latest version from npm — leaving profile bundles alone", - ]; - const before = targets.length; - const { refreshed, failed } = await refreshDshProfileBundles(latest, log); - if (failed === 0) { - // #2192: a clean manual run is evidence the lane works — disarm - // its cooldown immediately instead of letting the automatic channel - // wait out the window (up to 6 h). - await clearOwnerLaneBackoff("dsh-profile", latest); - } - return [ - `dsh: ${refreshed}/${before} profile bundle(s) refreshed to ${latest} through dsh's plugin channel${failed > 0 ? ` (${failed} failed)` : ""} (see log for per-profile results)`, - ]; - } - if (agent === "hermes") { - if (hermesStatus() !== "installed") - return ["hermes: not installed — nothing to update"]; - hermesInstallCore(); - return [ - `hermes: re-copied the plugin into ${hermesPluginDir()} (bili ${selfVersion()}) — restart hermes to pick it up`, - ]; - } - const via = UPDATE_CHANNEL[agent]; - return [ - `${agent}: the plugin entry follows the global bili install — it updates together with it (${via})`, - ]; + if (agent === "pi") { + const packages = readJson(piSettingsFile()).packages; + const list = Array.isArray(packages) + ? (packages as unknown[]).map(String) + : []; + const root = selfPackageRoot(); + // #2850: versioned npm specs (@pinned/@latest) are the same pi-managed + // copy, not a checkout pointer — route them to the same message. + if (list.some((p) => /^npm:billion-context(@|$)/.test(p))) { + return [ + "pi: the plugin copy is pi-managed (npm:billion-context) — `pi update` upgrades it; bili never overwrites it (#991)", + ]; + } + if (list.some((p) => isPiEntry(p, root))) { + return [ + "pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes", + ]; + } + return ["pi: not installed"]; + } + if (agent === "opencode") { + const file = opencodeTargetFile(); + const { data } = loadOpencodeConfig(file); + const dir = opencodePluginDir(file); + if ( + PLUGIN_KEYS.some((k) => + pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY), + ) + ) { + const root = opencodeCacheCopyRoot(); + const ver = root !== undefined ? pkgVersionAt(root) : undefined; + const where = root !== undefined ? ` (${root})` : ""; + const v = ver !== undefined ? ` v${ver}` : ""; + return [ + `opencode: the cache copy is bili-owned and self-updates in place through its own proxy${where}${v} (#1234) — this command does NOT run opencode's upgrade; OpenCode v2 'plugin update' is an extra manual channel, and reload/restart OpenCode after a disk update to activate it`, + ]; + } + if ( + PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir)) + ) { + return [ + "opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes", + ]; + } + return ["opencode: not installed"]; + } + if (agent === "dsh") { + let dirs: string[]; + try { + dirs = dshProfileDirs(); + } catch { + return ["dsh: never initialized on this machine — nothing to update"]; + } + const targets = dirs.filter((dir) => dshProfileDependsOnBili(dir)); + if (targets.length === 0) + return ["dsh: no profile depends on billion-context — nothing to update"]; + const latest = await fetchRegistryVersion(opts, opts.packageName); + if (!latest) + return [ + "dsh: could not resolve the latest version from npm — leaving profile bundles alone", + ]; + const before = targets.length; + const { refreshed, failed } = await refreshDshProfileBundles(latest, log); + if (failed === 0) { + // #2192: a clean manual run is evidence the lane works — disarm + // its cooldown immediately instead of letting the automatic channel + // wait out the window (up to 6 h). + await clearOwnerLaneBackoff("dsh-profile", latest); + } + return [ + `dsh: ${refreshed}/${before} profile bundle(s) refreshed to ${latest} through dsh's plugin channel${failed > 0 ? ` (${failed} failed)` : ""} (see log for per-profile results)`, + ]; + } + if (agent === "hermes") { + if (hermesStatus() !== "installed") + return ["hermes: not installed — nothing to update"]; + hermesInstallCore(); + return [ + `hermes: re-copied the plugin into ${hermesPluginDir()} (bili ${selfVersion()}) — restart hermes to pick it up`, + ]; + } + const via = UPDATE_CHANNEL[agent]; + return [ + `${agent}: the plugin entry follows the global bili install — it updates together with it (${via})`, + ]; } diff --git a/src/proxy-service/index.ts b/src/proxy-service/index.ts index 08e89369c0..a38fcc6eac 100644 --- a/src/proxy-service/index.ts +++ b/src/proxy-service/index.ts @@ -1,25 +1,25 @@ export { - BILI_TASK_NAME, - planTaskDelete, - planTaskDisable, - planTaskEnable, - planTaskEnd, - planTaskQuery, - planTaskRegister, - planTaskRun, - type ProxyTaskOptions, - type TaskCommand, - type TaskRunner, - type TaskRunnerResult, + BILI_TASK_NAME, + planTaskDelete, + planTaskDisable, + planTaskEnable, + planTaskEnd, + planTaskQuery, + planTaskRegister, + planTaskRun, + type ProxyTaskOptions, + type TaskCommand, + type TaskRunner, + type TaskRunnerResult, } from "./task-scheduler.js"; export { - disableProxyService, - enableProxyService, - installProxyService, - proxyServiceStatus, - removeProxyService, - restartProxyService, - type ProxyServiceConfig, - type ProxyServiceRecord, - type ProxyServiceResult, + disableProxyService, + enableProxyService, + installProxyService, + proxyServiceStatus, + removeProxyService, + restartProxyService, + type ProxyServiceConfig, + type ProxyServiceRecord, + type ProxyServiceResult, } from "./service.js"; diff --git a/src/proxy-service/service.ts b/src/proxy-service/service.ts index 0936c1c5a6..647adbdfc8 100644 --- a/src/proxy-service/service.ts +++ b/src/proxy-service/service.ts @@ -3,83 +3,83 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { - isPidAlive, - isProxyInstanceFile, - lanePreferredPort, - readProxyInstanceFile, + isPidAlive, + isProxyInstanceFile, + lanePreferredPort, + readProxyInstanceFile, } from "../instance.js"; import { stateDir } from "../paths.js"; import { - BILI_TASK_NAME, - planTaskDelete, - planTaskDisable, - planTaskEnable, - planTaskEnd, - planTaskQuery, - planTaskRegisterXml, - planTaskRun, - renderTaskLauncherVbs, - renderTaskXml, - type TaskCommand, - type TaskRunner, - type TaskRunnerResult, + BILI_TASK_NAME, + planTaskDelete, + planTaskDisable, + planTaskEnable, + planTaskEnd, + planTaskQuery, + planTaskRegisterXml, + planTaskRun, + renderTaskLauncherVbs, + renderTaskXml, + type TaskCommand, + type TaskRunner, + type TaskRunnerResult, } from "./task-scheduler.js"; import { - BILI_SYSTEMD_UNIT, - planDaemonReload, - planSystemdDisable, - planSystemdEnableNow, - planSystemdIsActive, - planSystemdIsEnabled, - planSystemdStart, - planSystemdStop, - renderSystemdUnit, - systemdUnitActive, - systemdUnitEnabled, - systemdUnitMissing, - systemdUserBusUnavailable, + BILI_SYSTEMD_UNIT, + planDaemonReload, + planSystemdDisable, + planSystemdEnableNow, + planSystemdIsActive, + planSystemdIsEnabled, + planSystemdStart, + planSystemdStop, + renderSystemdUnit, + systemdUnitActive, + systemdUnitEnabled, + systemdUnitMissing, + systemdUserBusUnavailable, } from "./systemd.js"; const SERVICE_STATE_FILE = "proxy-service.json"; export interface ProxyServiceConfig { - taskName?: string; - nodePath?: string; - entryPath?: string; - port?: number; - host?: string; - platform?: NodeJS.Platform; - runner?: TaskRunner; - stateDirectory?: string; - /** Absolute path of the systemd user unit (Linux backend). Defaults to - * $XDG_CONFIG_HOME/systemd/user/. */ - unitPath?: string; + taskName?: string; + nodePath?: string; + entryPath?: string; + port?: number; + host?: string; + platform?: NodeJS.Platform; + runner?: TaskRunner; + stateDirectory?: string; + /** Absolute path of the systemd user unit (Linux backend). Defaults to + * $XDG_CONFIG_HOME/systemd/user/. */ + unitPath?: string; } export interface ProxyServiceResult { - ok: boolean; - action: - | "installed" - | "already-installed" - | "removed" - | "already-absent" - | "enabled" - | "disabled" - | "restarted" - | "status" - | "unsupported" - | "error"; - message: string; - state?: "ready" | "disabled" | "missing" | "unknown"; - output?: string; + ok: boolean; + action: + | "installed" + | "already-installed" + | "removed" + | "already-absent" + | "enabled" + | "disabled" + | "restarted" + | "status" + | "unsupported" + | "error"; + message: string; + state?: "ready" | "disabled" | "missing" | "unknown"; + output?: string; } export interface ProxyServiceRecord { - taskName: string; - port: number; - host: string; - entryPath: string; - installedAt: string; + taskName: string; + port: number; + host: string; + entryPath: string; + installedAt: string; } /** Which backend owns the registration on this machine. Recorded so a status @@ -88,15 +88,15 @@ export interface ProxyServiceRecord { type ServiceBackend = "schtasks" | "systemd"; interface ServiceRecord extends ProxyServiceRecord { - backend: ServiceBackend; - /** systemd only: absolute unit path written by install. */ - unitPath?: string; - /** Shape version of the registration this record describes. Bump whenever - * the GENERATED artifact changes in a way a pre-existing registration must - * adopt (e.g. adding to the Task Scheduler document). Without it - * the path-based idempotency check below would treat a task registered by an - * older bili as "already installed" and never apply the new shape. */ - registrationVersion?: number; + backend: ServiceBackend; + /** systemd only: absolute unit path written by install. */ + unitPath?: string; + /** Shape version of the registration this record describes. Bump whenever + * the GENERATED artifact changes in a way a pre-existing registration must + * adopt (e.g. adding to the Task Scheduler document). Without it + * the path-based idempotency check below would treat a task registered by an + * older bili as "already installed" and never apply the new shape. */ + registrationVersion?: number; } /** Current registration shape. Bump this whenever renderTaskXml / the task @@ -111,387 +111,387 @@ const REGISTRATION_VERSION = 4; /** Task names are user-visible but not filename-safe; the generated companion * files (hidden launcher, temporary XML transport) derive their names from it. */ function safeTaskFileName(taskName: string): string { - return taskName.replace(/[^A-Za-z0-9._-]+/g, "-"); + return taskName.replace(/[^A-Za-z0-9._-]+/g, "-"); } /** Path of the persistent hidden-mode launcher the task invokes through * wscript.exe. Lives in the state directory because the task references it at * every logon and it must outlive the install command. */ function taskLauncherPath(c: ResolvedConfig): string { - return path.join( - c.stateDirectory, - `${safeTaskFileName(c.taskName)}.launch.vbs`, - ); + return path.join( + c.stateDirectory, + `${safeTaskFileName(c.taskName)}.launch.vbs`, + ); } /** Legacy records (written before the Linux backend existed) carry no * `backend`; they are by definition Task Scheduler registrations. */ function recordBackend(record: ServiceRecord): ServiceBackend { - return record.backend === "systemd" ? "systemd" : "schtasks"; + return record.backend === "systemd" ? "systemd" : "schtasks"; } function defaultRunner(command: TaskCommand): Promise { - return new Promise((resolve, reject) => { - import("node:child_process").then(({ spawn }) => { - const child = spawn(command.file, command.args, { - windowsHide: true, - stdio: ["ignore", "pipe", "pipe"], - }); - const stdout: Buffer[] = []; - const stderr: Buffer[] = []; - child.stdout?.on("data", (chunk: Buffer) => stdout.push(chunk)); - child.stderr?.on("data", (chunk: Buffer) => stderr.push(chunk)); - child.once("error", reject); - child.once("close", (code) => { - const decode = (chunks: Buffer[]): string => - new TextDecoder("gbk").decode(Buffer.concat(chunks)); - resolve({ - exitCode: code ?? 1, - stdout: decode(stdout), - stderr: decode(stderr), - }); - }); - }); - }); + return new Promise((resolve, reject) => { + import("node:child_process").then(({ spawn }) => { + const child = spawn(command.file, command.args, { + windowsHide: true, + stdio: ["ignore", "pipe", "pipe"], + }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + child.stdout?.on("data", (chunk: Buffer) => stdout.push(chunk)); + child.stderr?.on("data", (chunk: Buffer) => stderr.push(chunk)); + child.once("error", reject); + child.once("close", (code) => { + const decode = (chunks: Buffer[]): string => + new TextDecoder("gbk").decode(Buffer.concat(chunks)); + resolve({ + exitCode: code ?? 1, + stdout: decode(stdout), + stderr: decode(stderr), + }); + }); + }); + }); } function serviceRecordPath(directory = stateDir()): string { - return path.join(directory, SERVICE_STATE_FILE); + return path.join(directory, SERVICE_STATE_FILE); } function readRecord(file: string): ServiceRecord | undefined { - try { - const value: unknown = JSON.parse(fs.readFileSync(file, "utf8")); - if (value === null || typeof value !== "object" || Array.isArray(value)) - return undefined; - const row = value as Record; - if ( - typeof row.taskName !== "string" || - typeof row.entryPath !== "string" || - typeof row.host !== "string" || - typeof row.port !== "number" || - typeof row.installedAt !== "string" - ) - return undefined; - return { - taskName: row.taskName, - entryPath: row.entryPath, - host: row.host, - port: row.port, - installedAt: row.installedAt, - backend: row.backend === "systemd" ? "systemd" : "schtasks", - ...(typeof row.unitPath === "string" ? { unitPath: row.unitPath } : {}), - ...(typeof row.registrationVersion === "number" - ? { registrationVersion: row.registrationVersion } - : {}), - }; - } catch { - return undefined; - } + try { + const value: unknown = JSON.parse(fs.readFileSync(file, "utf8")); + if (value === null || typeof value !== "object" || Array.isArray(value)) + return undefined; + const row = value as Record; + if ( + typeof row.taskName !== "string" || + typeof row.entryPath !== "string" || + typeof row.host !== "string" || + typeof row.port !== "number" || + typeof row.installedAt !== "string" + ) + return undefined; + return { + taskName: row.taskName, + entryPath: row.entryPath, + host: row.host, + port: row.port, + installedAt: row.installedAt, + backend: row.backend === "systemd" ? "systemd" : "schtasks", + ...(typeof row.unitPath === "string" ? { unitPath: row.unitPath } : {}), + ...(typeof row.registrationVersion === "number" + ? { registrationVersion: row.registrationVersion } + : {}), + }; + } catch { + return undefined; + } } function writeRecord(file: string, record: ServiceRecord): void { - fs.mkdirSync(path.dirname(file), { recursive: true }); - const temporary = `${file}.${process.pid}.tmp`; - fs.writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { - mode: 0o600, - }); - fs.renameSync(temporary, file); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const temporary = `${file}.${process.pid}.tmp`; + fs.writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { + mode: 0o600, + }); + fs.renameSync(temporary, file); } function removeRecord(file: string): void { - try { - fs.unlinkSync(file); - } catch (error) { - if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) - throw error; - } + try { + fs.unlinkSync(file); + } catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) + throw error; + } } function resolveConfig(config: ProxyServiceConfig) { - const taskName = config.taskName ?? BILI_TASK_NAME; - const entryPath = - config.entryPath ?? - process.argv[1] ?? - fileURLToPath(new URL("../index.js", import.meta.url)); - return { - taskName, - nodePath: config.nodePath ?? process.execPath, - entryPath, - port: config.port ?? lanePreferredPort("codex"), - host: config.host ?? "127.0.0.1", - platform: config.platform ?? process.platform, - runner: config.runner ?? defaultRunner, - stateDirectory: config.stateDirectory ?? stateDir(), - unitPath: config.unitPath ?? defaultUnitPath(), - }; + const taskName = config.taskName ?? BILI_TASK_NAME; + const entryPath = + config.entryPath ?? + process.argv[1] ?? + fileURLToPath(new URL("../index.js", import.meta.url)); + return { + taskName, + nodePath: config.nodePath ?? process.execPath, + entryPath, + port: config.port ?? lanePreferredPort("codex"), + host: config.host ?? "127.0.0.1", + platform: config.platform ?? process.platform, + runner: config.runner ?? defaultRunner, + stateDirectory: config.stateDirectory ?? stateDir(), + unitPath: config.unitPath ?? defaultUnitPath(), + }; } /** $XDG_CONFIG_HOME/systemd/user/, defaulting under ~/.config. Mirrors * paths.ts's XDG handling without importing its billion-context leaf dirs * (the unit belongs to systemd's namespace, not ours). */ function defaultUnitPath(): string { - const base = process.env["XDG_CONFIG_HOME"]?.trim(); - const root = - base !== undefined && base.length > 0 - ? path.resolve(base) - : path.join(os.homedir(), ".config"); - return path.join(root, "systemd", "user", BILI_SYSTEMD_UNIT); + const base = process.env["XDG_CONFIG_HOME"]?.trim(); + const root = + base !== undefined && base.length > 0 + ? path.resolve(base) + : path.join(os.homedir(), ".config"); + return path.join(root, "systemd", "user", BILI_SYSTEMD_UNIT); } async function invoke( - runner: TaskRunner, - command: TaskCommand, + runner: TaskRunner, + command: TaskCommand, ): Promise { - try { - return await runner(command); - } catch (error) { - return { - exitCode: 1, - stdout: "", - stderr: error instanceof Error ? error.message : String(error), - }; - } + try { + return await runner(command); + } catch (error) { + return { + exitCode: 1, + stdout: "", + stderr: error instanceof Error ? error.message : String(error), + }; + } } function taskExists(result: TaskRunnerResult): boolean { - return result.exitCode === 0 && /)/i.test(result.stdout); + return result.exitCode === 0 && /)/i.test(result.stdout); } function taskDisabled(result: TaskRunnerResult): boolean { - return /false<\/Enabled>/i.test(result.stdout); + return /false<\/Enabled>/i.test(result.stdout); } function taskMissing(result: TaskRunnerResult): boolean { - return ( - result.exitCode !== 0 && - /cannot find|does not exist|not found|ERROR: The system cannot find|系统找不到|找不到指定的文件|不存在/i.test( - `${result.stdout}\n${result.stderr}`, - ) - ); + return ( + result.exitCode !== 0 && + /cannot find|does not exist|not found|ERROR: The system cannot find|系统找不到|找不到指定的文件|不存在/i.test( + `${result.stdout}\n${result.stderr}`, + ) + ); } function hasOwnedTask(file: string, taskName: string): boolean { - const record = readRecord(file); - return ( - record !== undefined && - record.taskName === taskName && - recordBackend(record) === "schtasks" - ); + const record = readRecord(file); + return ( + record !== undefined && + record.taskName === taskName && + recordBackend(record) === "schtasks" + ); } /** systemd twin of hasOwnedTask: the unit this machine's record claims, and * only when the record says the systemd backend wrote it. */ function hasOwnedUnit(file: string, unitPath: string): boolean { - const record = readRecord(file); - return ( - record !== undefined && - recordBackend(record) === "systemd" && - record.unitPath === unitPath - ); + const record = readRecord(file); + return ( + record !== undefined && + recordBackend(record) === "systemd" && + record.unitPath === unitPath + ); } /** A record written by the OTHER backend. Presenting it as ours would let * `remove` delete a registration the running copy did not create. */ function hasForeignBackendRecord( - file: string, - backend: ServiceBackend, + file: string, + backend: ServiceBackend, ): boolean { - const record = readRecord(file); - return record !== undefined && recordBackend(record) !== backend; + const record = readRecord(file); + return record !== undefined && recordBackend(record) !== backend; } function unsupportedPlatform(platform: NodeJS.Platform): ProxyServiceResult { - return { - ok: false, - action: "unsupported", - state: "unknown", - message: `persistent proxy service is not supported on ${platform} (Windows Task Scheduler and Linux systemd user units are)`, - }; + return { + ok: false, + action: "unsupported", + state: "unknown", + message: `persistent proxy service is not supported on ${platform} (Windows Task Scheduler and Linux systemd user units are)`, + }; } function describeFailure( - action: string, - result: TaskRunnerResult, + action: string, + result: TaskRunnerResult, ): ProxyServiceResult { - const detail = ( - result.stderr || - result.stdout || - `exit code ${result.exitCode}` - ).trim(); - return { ok: false, action: "error", message: `${action} failed: ${detail}` }; + const detail = ( + result.stderr || + result.stdout || + `exit code ${result.exitCode}` + ).trim(); + return { ok: false, action: "error", message: `${action} failed: ${detail}` }; } export async function proxyServiceStatus( - config: ProxyServiceConfig = {}, + config: ProxyServiceConfig = {}, ): Promise { - const c = resolveConfig(config); - if (c.platform === "linux") return statusSystemd(c); - if (c.platform !== "win32") return unsupportedPlatform(c.platform); - const result = await invoke(c.runner, planTaskQuery(c.taskName)); - if (taskMissing(result)) - return { - ok: true, - action: "status", - state: "missing", - message: "scheduled task is not registered", - }; - if (result.exitCode !== 0) - return describeFailure("query scheduled task", result); - if (!taskExists(result)) - return { - ok: false, - action: "error", - state: "unknown", - message: "scheduled task query returned unrecognized XML", - }; - if (!hasOwnedTask(serviceRecordPath(c.stateDirectory), c.taskName)) { - return { - ok: true, - action: "status", - state: "unknown", - message: "scheduled task name is occupied by an unowned task", - }; - } - return { - ok: true, - action: "status", - state: taskDisabled(result) ? "disabled" : "ready", - message: taskDisabled(result) - ? "scheduled task is registered but disabled" - : "scheduled task is registered", - output: result.stdout, - }; + const c = resolveConfig(config); + if (c.platform === "linux") return statusSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const result = await invoke(c.runner, planTaskQuery(c.taskName)); + if (taskMissing(result)) + return { + ok: true, + action: "status", + state: "missing", + message: "scheduled task is not registered", + }; + if (result.exitCode !== 0) + return describeFailure("query scheduled task", result); + if (!taskExists(result)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML", + }; + if (!hasOwnedTask(serviceRecordPath(c.stateDirectory), c.taskName)) { + return { + ok: true, + action: "status", + state: "unknown", + message: "scheduled task name is occupied by an unowned task", + }; + } + return { + ok: true, + action: "status", + state: taskDisabled(result) ? "disabled" : "ready", + message: taskDisabled(result) + ? "scheduled task is registered but disabled" + : "scheduled task is registered", + output: result.stdout, + }; } export async function installProxyService( - config: ProxyServiceConfig = {}, + config: ProxyServiceConfig = {}, ): Promise { - const c = resolveConfig(config); - if (c.platform === "linux") return installSystemd(c); - if (c.platform !== "win32") return unsupportedPlatform(c.platform); - const file = serviceRecordPath(c.stateDirectory); - const query = await invoke(c.runner, planTaskQuery(c.taskName)); - if (query.exitCode !== 0 && !taskMissing(query)) - return describeFailure("query scheduled task", query); - if (query.exitCode === 0 && !taskExists(query)) { - return { - ok: false, - action: "error", - state: "unknown", - message: "scheduled task query returned unrecognized XML; left untouched", - }; - } - if (query.exitCode === 0 && taskExists(query)) { - const existing = readRecord(file); - if (existing?.taskName !== c.taskName) { - return { - ok: false, - action: "error", - state: "unknown", - message: - "scheduled task name is occupied by an unowned task; left untouched", - }; - } - if ( - existing.entryPath === c.entryPath && - existing.port === c.port && - existing.host === c.host && - existing.registrationVersion === REGISTRATION_VERSION - ) { - return { - ok: true, - action: "already-installed", - state: taskDisabled(query) ? "disabled" : "ready", - message: - "scheduled task is already registered with the current bili entry", - }; - } - } - const xmlPath = path.join( - c.stateDirectory, - `${safeTaskFileName(c.taskName)}.task.xml`, - ); - // The task action is a .vbs run through wscript.exe, not node.exe directly: - // a console-subsystem binary started by the scheduler in the interactive - // session allocates a conhost window that cannot suppress. The - // launcher PERSISTS (the task references it at every logon) — only the XML - // transport file is temporary. - const launcherPath = taskLauncherPath(c); - let result: TaskRunnerResult; - try { - fs.mkdirSync(c.stateDirectory, { recursive: true }); - fs.writeFileSync( - launcherPath, - Buffer.from(`\ufeff${renderTaskLauncherVbs(c)}`, "utf16le"), - ); - // Task Scheduler requires a UTF-16 document to carry the FF FE byte-order - // mark; Node's "utf16le" encoder writes none, and without it schtasks - // fails with "任务 XML 格式错误 (1,2)::错误: 一个根元素". - const xml = Buffer.from( - `\ufeff${renderTaskXml({ ...c, launcherPath })}`, - "utf16le", - ); - fs.writeFileSync(xmlPath, xml); - result = await invoke(c.runner, planTaskRegisterXml(xmlPath, c.taskName)); - } catch (err) { - return { - ok: false, - action: "error", - state: "unknown", - message: `could not register the scheduled task from its hidden XML document: ${err instanceof Error ? err.message : String(err)}`, - }; - } finally { - fs.rmSync(xmlPath, { force: true }); - } - if (result.exitCode !== 0) - return describeFailure("register scheduled task", result); - writeRecord(file, { - taskName: c.taskName, - entryPath: c.entryPath, - port: c.port, - host: c.host, - installedAt: new Date().toISOString(), - backend: "schtasks", - registrationVersion: REGISTRATION_VERSION, - }); - const verified = await invoke(c.runner, planTaskQuery(c.taskName)); - if (verified.exitCode !== 0 || !taskExists(verified)) { - await invoke(c.runner, planTaskDelete(c.taskName)); - removeRecord(file); - return { - ok: false, - action: "error", - state: "unknown", - message: - "registration command succeeded but scheduled task could not be verified; registration was rolled back", - }; - } - const started = await invoke(c.runner, planTaskRun(c.taskName)); - if (started.exitCode !== 0) { - await invoke(c.runner, planTaskDelete(c.taskName)); - removeRecord(file); - return { - ok: false, - action: "error", - state: "unknown", - message: `scheduled task registered but immediate start failed; registration was rolled back: ${(started.stderr || started.stdout || `exit code ${started.exitCode}`).trim()}`, - }; - } - return { - ok: true, - action: "installed", - state: taskDisabled(verified) ? "disabled" : "ready", - message: - "registered per-user at-logon Task Scheduler task and requested an immediate start", - }; + const c = resolveConfig(config); + if (c.platform === "linux") return installSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const file = serviceRecordPath(c.stateDirectory); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (query.exitCode !== 0 && !taskMissing(query)) + return describeFailure("query scheduled task", query); + if (query.exitCode === 0 && !taskExists(query)) { + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + } + if (query.exitCode === 0 && taskExists(query)) { + const existing = readRecord(file); + if (existing?.taskName !== c.taskName) { + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + } + if ( + existing.entryPath === c.entryPath && + existing.port === c.port && + existing.host === c.host && + existing.registrationVersion === REGISTRATION_VERSION + ) { + return { + ok: true, + action: "already-installed", + state: taskDisabled(query) ? "disabled" : "ready", + message: + "scheduled task is already registered with the current bili entry", + }; + } + } + const xmlPath = path.join( + c.stateDirectory, + `${safeTaskFileName(c.taskName)}.task.xml`, + ); + // The task action is a .vbs run through wscript.exe, not node.exe directly: + // a console-subsystem binary started by the scheduler in the interactive + // session allocates a conhost window that cannot suppress. The + // launcher PERSISTS (the task references it at every logon) — only the XML + // transport file is temporary. + const launcherPath = taskLauncherPath(c); + let result: TaskRunnerResult; + try { + fs.mkdirSync(c.stateDirectory, { recursive: true }); + fs.writeFileSync( + launcherPath, + Buffer.from(`\ufeff${renderTaskLauncherVbs(c)}`, "utf16le"), + ); + // Task Scheduler requires a UTF-16 document to carry the FF FE byte-order + // mark; Node's "utf16le" encoder writes none, and without it schtasks + // fails with "任务 XML 格式错误 (1,2)::错误: 一个根元素". + const xml = Buffer.from( + `\ufeff${renderTaskXml({ ...c, launcherPath })}`, + "utf16le", + ); + fs.writeFileSync(xmlPath, xml); + result = await invoke(c.runner, planTaskRegisterXml(xmlPath, c.taskName)); + } catch (err) { + return { + ok: false, + action: "error", + state: "unknown", + message: `could not register the scheduled task from its hidden XML document: ${err instanceof Error ? err.message : String(err)}`, + }; + } finally { + fs.rmSync(xmlPath, { force: true }); + } + if (result.exitCode !== 0) + return describeFailure("register scheduled task", result); + writeRecord(file, { + taskName: c.taskName, + entryPath: c.entryPath, + port: c.port, + host: c.host, + installedAt: new Date().toISOString(), + backend: "schtasks", + registrationVersion: REGISTRATION_VERSION, + }); + const verified = await invoke(c.runner, planTaskQuery(c.taskName)); + if (verified.exitCode !== 0 || !taskExists(verified)) { + await invoke(c.runner, planTaskDelete(c.taskName)); + removeRecord(file); + return { + ok: false, + action: "error", + state: "unknown", + message: + "registration command succeeded but scheduled task could not be verified; registration was rolled back", + }; + } + const started = await invoke(c.runner, planTaskRun(c.taskName)); + if (started.exitCode !== 0) { + await invoke(c.runner, planTaskDelete(c.taskName)); + removeRecord(file); + return { + ok: false, + action: "error", + state: "unknown", + message: `scheduled task registered but immediate start failed; registration was rolled back: ${(started.stderr || started.stdout || `exit code ${started.exitCode}`).trim()}`, + }; + } + return { + ok: true, + action: "installed", + state: taskDisabled(verified) ? "disabled" : "ready", + message: + "registered per-user at-logon Task Scheduler task and requested an immediate start", + }; } function readProxyPidOnPort(port: number): number | undefined { - const info = readProxyInstanceFile(); - if (!isProxyInstanceFile(info)) return undefined; - if (info.port !== port || info.pid <= 0) return undefined; - return isPidAlive(info.pid) ? info.pid : undefined; + const info = readProxyInstanceFile(); + if (!isProxyInstanceFile(info)) return undefined; + if (info.port !== port || info.pid <= 0) return undefined; + return isPidAlive(info.pid) ? info.pid : undefined; } /** Best-effort stop of a proxy that the scheduler can no longer reach. @@ -504,216 +504,216 @@ function readProxyPidOnPort(port: number): number | undefined { * one owning the port we registered. Never throws: a failure here must not turn * a successful uninstall into an error. */ function reapOrphanProxy(port: number): boolean { - let killed = false; - const pid = readProxyPidOnPort(port); - if (pid !== undefined) { - try { - process.kill(pid); - killed = true; - } catch { - // The process exited between the liveness check and the signal, or we - // lack permission; either way removal proceeds without it. - } - } - return killed; + let killed = false; + const pid = readProxyPidOnPort(port); + if (pid !== undefined) { + try { + process.kill(pid); + killed = true; + } catch { + // The process exited between the liveness check and the signal, or we + // lack permission; either way removal proceeds without it. + } + } + return killed; } export async function removeProxyService( - config: ProxyServiceConfig = {}, + config: ProxyServiceConfig = {}, ): Promise { - const c = resolveConfig(config); - if (c.platform === "linux") return removeSystemd(c); - if (c.platform !== "win32") return unsupportedPlatform(c.platform); - const file = serviceRecordPath(c.stateDirectory); - const query = await invoke(c.runner, planTaskQuery(c.taskName)); - if (query.exitCode !== 0 && !taskMissing(query)) - return describeFailure("query scheduled task", query); - if (query.exitCode === 0 && !taskExists(query)) - return { - ok: false, - action: "error", - state: "unknown", - message: "scheduled task query returned unrecognized XML; left untouched", - }; - if ( - query.exitCode === 0 && - taskExists(query) && - !hasOwnedTask(file, c.taskName) - ) { - return { - ok: false, - action: "error", - state: "unknown", - message: - "scheduled task name is occupied by an unowned task; left untouched", - }; - } - // Stop the live instance BEFORE deleting the task: the task is the only - // handle on that process, so removing it first would orphan a running proxy - // that keeps listening (and keeps compressing traffic) with no way to stop it - // except by hand. A "not running" answer is the normal already-stopped case. - const end = await invoke(c.runner, planTaskEnd(c.taskName)); - if ( - end.exitCode !== 0 && - !/not running|not currently running/i.test(`${end.stdout}\n${end.stderr}`) - ) - return describeFailure("stop scheduled task instance", end); - const result = await invoke(c.runner, planTaskDelete(c.taskName)); - if (result.exitCode !== 0 && !taskMissing(result)) - return describeFailure("remove scheduled task", result); - // /End killed our launcher but the node it spawned may have survived as an - // orphan still holding the port; reap it so "removed" means removed. - reapOrphanProxy(c.port); - // The hidden launcher is only referenced by the task we just deleted; a - // leftover .vbs would otherwise survive uninstall and keep pointing at a - // dist/ tree the user may have removed. - fs.rmSync(taskLauncherPath(c), { force: true }); - removeRecord(file); - return { - ok: true, - action: result.exitCode === 0 ? "removed" : "already-absent", - state: "missing", - message: - result.exitCode === 0 - ? "scheduled task removed" - : "scheduled task was already absent", - }; + const c = resolveConfig(config); + if (c.platform === "linux") return removeSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const file = serviceRecordPath(c.stateDirectory); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (query.exitCode !== 0 && !taskMissing(query)) + return describeFailure("query scheduled task", query); + if (query.exitCode === 0 && !taskExists(query)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + if ( + query.exitCode === 0 && + taskExists(query) && + !hasOwnedTask(file, c.taskName) + ) { + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + } + // Stop the live instance BEFORE deleting the task: the task is the only + // handle on that process, so removing it first would orphan a running proxy + // that keeps listening (and keeps compressing traffic) with no way to stop it + // except by hand. A "not running" answer is the normal already-stopped case. + const end = await invoke(c.runner, planTaskEnd(c.taskName)); + if ( + end.exitCode !== 0 && + !/not running|not currently running/i.test(`${end.stdout}\n${end.stderr}`) + ) + return describeFailure("stop scheduled task instance", end); + const result = await invoke(c.runner, planTaskDelete(c.taskName)); + if (result.exitCode !== 0 && !taskMissing(result)) + return describeFailure("remove scheduled task", result); + // /End killed our launcher but the node it spawned may have survived as an + // orphan still holding the port; reap it so "removed" means removed. + reapOrphanProxy(c.port); + // The hidden launcher is only referenced by the task we just deleted; a + // leftover .vbs would otherwise survive uninstall and keep pointing at a + // dist/ tree the user may have removed. + fs.rmSync(taskLauncherPath(c), { force: true }); + removeRecord(file); + return { + ok: true, + action: result.exitCode === 0 ? "removed" : "already-absent", + state: "missing", + message: + result.exitCode === 0 + ? "scheduled task removed" + : "scheduled task was already absent", + }; } export async function disableProxyService( - config: ProxyServiceConfig = {}, + config: ProxyServiceConfig = {}, ): Promise { - const c = resolveConfig(config); - if (c.platform === "linux") return disableSystemd(c); - if (c.platform !== "win32") return unsupportedPlatform(c.platform); - const file = serviceRecordPath(c.stateDirectory); - const query = await invoke(c.runner, planTaskQuery(c.taskName)); - if (taskMissing(query)) - return { - ok: false, - action: "error", - state: "missing", - message: "scheduled task is not registered; install it first", - }; - if (query.exitCode !== 0) - return describeFailure("query scheduled task", query); - if (!taskExists(query)) - return { - ok: false, - action: "error", - state: "unknown", - message: "scheduled task query returned unrecognized XML; left untouched", - }; - if (!hasOwnedTask(file, c.taskName)) - return { - ok: false, - action: "error", - state: "unknown", - message: - "scheduled task name is occupied by an unowned task; left untouched", - }; - const result = await invoke(c.runner, planTaskDisable(c.taskName)); - if ( - result.exitCode !== 0 && - !/already disabled/i.test(`${result.stdout}\n${result.stderr}`) - ) - return describeFailure("disable scheduled task", result); - return { - ok: true, - action: "disabled", - state: "disabled", - message: "scheduled task disabled", - }; + const c = resolveConfig(config); + if (c.platform === "linux") return disableSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const file = serviceRecordPath(c.stateDirectory); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (taskMissing(query)) + return { + ok: false, + action: "error", + state: "missing", + message: "scheduled task is not registered; install it first", + }; + if (query.exitCode !== 0) + return describeFailure("query scheduled task", query); + if (!taskExists(query)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + if (!hasOwnedTask(file, c.taskName)) + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + const result = await invoke(c.runner, planTaskDisable(c.taskName)); + if ( + result.exitCode !== 0 && + !/already disabled/i.test(`${result.stdout}\n${result.stderr}`) + ) + return describeFailure("disable scheduled task", result); + return { + ok: true, + action: "disabled", + state: "disabled", + message: "scheduled task disabled", + }; } export async function restartProxyService( - config: ProxyServiceConfig = {}, + config: ProxyServiceConfig = {}, ): Promise { - const c = resolveConfig(config); - if (c.platform === "linux") return restartSystemd(c); - if (c.platform !== "win32") return unsupportedPlatform(c.platform); - const query = await invoke(c.runner, planTaskQuery(c.taskName)); - if (taskMissing(query)) - return { - ok: false, - action: "error", - state: "missing", - message: "scheduled task is not registered; install it first", - }; - if (query.exitCode !== 0) - return describeFailure("query scheduled task", query); - if (!taskExists(query)) - return { - ok: false, - action: "error", - state: "unknown", - message: "scheduled task query returned unrecognized XML; left untouched", - }; - if (!hasOwnedTask(serviceRecordPath(c.stateDirectory), c.taskName)) - return { - ok: false, - action: "error", - state: "unknown", - message: - "scheduled task name is occupied by an unowned task; left untouched", - }; - const end = await invoke(c.runner, planTaskEnd(c.taskName)); - if ( - end.exitCode !== 0 && - !/not running|not currently running/i.test(`${end.stdout}\n${end.stderr}`) - ) - return describeFailure("stop scheduled task instance", end); - const run = await invoke(c.runner, planTaskRun(c.taskName)); - if (run.exitCode !== 0) return describeFailure("start scheduled task", run); - return { - ok: true, - action: "restarted", - state: "ready", - message: "scheduled task restart requested", - }; + const c = resolveConfig(config); + if (c.platform === "linux") return restartSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (taskMissing(query)) + return { + ok: false, + action: "error", + state: "missing", + message: "scheduled task is not registered; install it first", + }; + if (query.exitCode !== 0) + return describeFailure("query scheduled task", query); + if (!taskExists(query)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + if (!hasOwnedTask(serviceRecordPath(c.stateDirectory), c.taskName)) + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + const end = await invoke(c.runner, planTaskEnd(c.taskName)); + if ( + end.exitCode !== 0 && + !/not running|not currently running/i.test(`${end.stdout}\n${end.stderr}`) + ) + return describeFailure("stop scheduled task instance", end); + const run = await invoke(c.runner, planTaskRun(c.taskName)); + if (run.exitCode !== 0) return describeFailure("start scheduled task", run); + return { + ok: true, + action: "restarted", + state: "ready", + message: "scheduled task restart requested", + }; } export async function enableProxyService( - config: ProxyServiceConfig = {}, + config: ProxyServiceConfig = {}, ): Promise { - const c = resolveConfig(config); - if (c.platform === "linux") return enableSystemd(c); - if (c.platform !== "win32") return unsupportedPlatform(c.platform); - const file = serviceRecordPath(c.stateDirectory); - const query = await invoke(c.runner, planTaskQuery(c.taskName)); - if (taskMissing(query)) - return { - ok: false, - action: "error", - state: "missing", - message: "scheduled task is not registered; install it first", - }; - if (query.exitCode !== 0) - return describeFailure("query scheduled task", query); - if (!taskExists(query)) - return { - ok: false, - action: "error", - state: "unknown", - message: "scheduled task query returned unrecognized XML; left untouched", - }; - if (!hasOwnedTask(file, c.taskName)) - return { - ok: false, - action: "error", - state: "unknown", - message: - "scheduled task name is occupied by an unowned task; left untouched", - }; - const result = await invoke(c.runner, planTaskEnable(c.taskName)); - if (result.exitCode !== 0) - return describeFailure("enable scheduled task", result); - return { - ok: true, - action: "enabled", - state: "ready", - message: "scheduled task enabled", - }; + const c = resolveConfig(config); + if (c.platform === "linux") return enableSystemd(c); + if (c.platform !== "win32") return unsupportedPlatform(c.platform); + const file = serviceRecordPath(c.stateDirectory); + const query = await invoke(c.runner, planTaskQuery(c.taskName)); + if (taskMissing(query)) + return { + ok: false, + action: "error", + state: "missing", + message: "scheduled task is not registered; install it first", + }; + if (query.exitCode !== 0) + return describeFailure("query scheduled task", query); + if (!taskExists(query)) + return { + ok: false, + action: "error", + state: "unknown", + message: "scheduled task query returned unrecognized XML; left untouched", + }; + if (!hasOwnedTask(file, c.taskName)) + return { + ok: false, + action: "error", + state: "unknown", + message: + "scheduled task name is occupied by an unowned task; left untouched", + }; + const result = await invoke(c.runner, planTaskEnable(c.taskName)); + if (result.exitCode !== 0) + return describeFailure("enable scheduled task", result); + return { + ok: true, + action: "enabled", + state: "ready", + message: "scheduled task enabled", + }; } // --------------------------------------------------------------------------- @@ -726,10 +726,10 @@ export async function enableProxyService( type ResolvedConfig = ReturnType; function systemdResult( - result: TaskRunnerResult, - action: string, + result: TaskRunnerResult, + action: string, ): ProxyServiceResult { - return describeFailure(action, result); + return describeFailure(action, result); } /** Bus reachability preflight shared by every mutating systemd path. Returns a @@ -737,120 +737,120 @@ function systemdResult( * undefined. Writing a unit into a machine whose user manager will never load * it is the failure mode this prevents. */ async function requireSystemdBus( - c: ResolvedConfig, + c: ResolvedConfig, ): Promise { - const probe = await invoke( - c.runner, - planSystemdIsEnabled({ unitName: c.taskName, unitPath: c.unitPath }), - ); - if (systemdUserBusUnavailable(probe)) - return { - ok: false, - action: "error", - state: "unknown", - message: - "systemctl --user cannot reach a user manager (no systemd user bus in this session) — run `loginctl enable-linger $USER` on a systemd host, or start the proxy with `bili start` instead", - }; - return undefined; + const probe = await invoke( + c.runner, + planSystemdIsEnabled({ unitName: c.taskName, unitPath: c.unitPath }), + ); + if (systemdUserBusUnavailable(probe)) + return { + ok: false, + action: "error", + state: "unknown", + message: + "systemctl --user cannot reach a user manager (no systemd user bus in this session) — run `loginctl enable-linger $USER` on a systemd host, or start the proxy with `bili start` instead", + }; + return undefined; } async function statusSystemd(c: ResolvedConfig): Promise { - const probe = await invoke( - c.runner, - planSystemdIsEnabled({ unitName: c.taskName }), - ); - if (systemdUserBusUnavailable(probe)) - return { - ok: false, - action: "unsupported", - state: "unknown", - message: - "systemctl --user cannot reach a user manager (no systemd user bus in this session)", - }; - const unitName = c.taskName; - const enabled = await querySystemdEnabled(c); - if (enabled === undefined) - return { - ok: true, - action: "status", - state: "missing", - message: "systemd user unit is not registered", - }; - if (!hasOwnedUnit(serviceRecordPath(c.stateDirectory), c.unitPath)) - return { - ok: true, - action: "status", - state: "unknown", - message: "systemd user unit is not owned by this bili copy", - }; - const active = await invoke(c.runner, planSystemdIsActive({ unitName })); - return { - ok: true, - action: "status", - state: enabled - ? systemdUnitActive(active) - ? "ready" - : "disabled" - : "disabled", - message: enabled - ? systemdUnitActive(active) - ? "systemd user unit is enabled and active" - : "systemd user unit is enabled but not running" - : "systemd user unit is registered but disabled", - output: active.stdout, - }; + const probe = await invoke( + c.runner, + planSystemdIsEnabled({ unitName: c.taskName }), + ); + if (systemdUserBusUnavailable(probe)) + return { + ok: false, + action: "unsupported", + state: "unknown", + message: + "systemctl --user cannot reach a user manager (no systemd user bus in this session)", + }; + const unitName = c.taskName; + const enabled = await querySystemdEnabled(c); + if (enabled === undefined) + return { + ok: true, + action: "status", + state: "missing", + message: "systemd user unit is not registered", + }; + if (!hasOwnedUnit(serviceRecordPath(c.stateDirectory), c.unitPath)) + return { + ok: true, + action: "status", + state: "unknown", + message: "systemd user unit is not owned by this bili copy", + }; + const active = await invoke(c.runner, planSystemdIsActive({ unitName })); + return { + ok: true, + action: "status", + state: enabled + ? systemdUnitActive(active) + ? "ready" + : "disabled" + : "disabled", + message: enabled + ? systemdUnitActive(active) + ? "systemd user unit is enabled and active" + : "systemd user unit is enabled but not running" + : "systemd user unit is registered but disabled", + output: active.stdout, + }; } /** Renders the unit, wires it into systemd and starts it immediately. */ async function installSystemd(c: ResolvedConfig): Promise { - const bus = await requireSystemdBus(c); - if (bus !== undefined) return bus; - const file = serviceRecordPath(c.stateDirectory); - if (hasForeignBackendRecord(file, "systemd")) - return { - ok: false, - action: "error", - state: "unknown", - message: - "a Task Scheduler registration is recorded for this copy; remove it with `bili service remove` before installing the systemd unit", - }; - const existing = await querySystemdEnabled(c); - // Ownership is decided against what systemd ACTUALLY knows, not against the - // record alone: a unit file left behind by another copy (or by a hand edit) - // while our record is missing must still be seen as foreign, or install - // would silently overwrite someone else's unit. - const unitOnDisk = fs.existsSync(c.unitPath); - if ( - (existing !== undefined || unitOnDisk) && - !hasOwnedUnit(file, c.unitPath) - ) { - return { - ok: false, - action: "error", - state: "unknown", - message: `systemd user unit ${c.taskName} already exists and is not owned by this bili copy; left untouched`, - }; - } - const previous = readRecord(file); - const record = readRecord(file); - if ( - existing !== undefined && - record !== undefined && - recordBackend(record) === "systemd" && - record.entryPath === c.entryPath && - record.port === c.port && - record.host === c.host && - record.registrationVersion === REGISTRATION_VERSION - ) { - return { - ok: true, - action: "already-installed", - state: "ready", - message: - "systemd user unit is already registered with the current bili entry", - }; - } - return writeAndEnableSystemd(c, file, previous); + const bus = await requireSystemdBus(c); + if (bus !== undefined) return bus; + const file = serviceRecordPath(c.stateDirectory); + if (hasForeignBackendRecord(file, "systemd")) + return { + ok: false, + action: "error", + state: "unknown", + message: + "a Task Scheduler registration is recorded for this copy; remove it with `bili service remove` before installing the systemd unit", + }; + const existing = await querySystemdEnabled(c); + // Ownership is decided against what systemd ACTUALLY knows, not against the + // record alone: a unit file left behind by another copy (or by a hand edit) + // while our record is missing must still be seen as foreign, or install + // would silently overwrite someone else's unit. + const unitOnDisk = fs.existsSync(c.unitPath); + if ( + (existing !== undefined || unitOnDisk) && + !hasOwnedUnit(file, c.unitPath) + ) { + return { + ok: false, + action: "error", + state: "unknown", + message: `systemd user unit ${c.taskName} already exists and is not owned by this bili copy; left untouched`, + }; + } + const previous = readRecord(file); + const record = readRecord(file); + if ( + existing !== undefined && + record !== undefined && + recordBackend(record) === "systemd" && + record.entryPath === c.entryPath && + record.port === c.port && + record.host === c.host && + record.registrationVersion === REGISTRATION_VERSION + ) { + return { + ok: true, + action: "already-installed", + state: "ready", + message: + "systemd user unit is already registered with the current bili entry", + }; + } + return writeAndEnableSystemd(c, file, previous); } /** Write the unit, reload systemd, enable-and-start it, then verify it is @@ -858,245 +858,245 @@ async function installSystemd(c: ResolvedConfig): Promise { * deletes the file we created) and the previous record, so an install that * reports an error leaves the machine exactly as it found it. */ async function writeAndEnableSystemd( - c: ResolvedConfig, - file: string, - previous: ServiceRecord | undefined, + c: ResolvedConfig, + file: string, + previous: ServiceRecord | undefined, ): Promise { - let priorText: string | undefined; - try { - priorText = fs.readFileSync(c.unitPath, "utf8"); - } catch {} - try { - fs.mkdirSync(path.dirname(c.unitPath), { recursive: true }); - fs.writeFileSync( - c.unitPath, - renderSystemdUnit({ - nodePath: c.nodePath, - entryPath: c.entryPath, - port: c.port, - host: c.host, - unitPath: c.unitPath, - }), - ); - } catch (error) { - return { - ok: false, - action: "error", - state: "unknown", - message: `could not write ${c.unitPath}: ${error instanceof Error ? error.message : String(error)}`, - }; - } - const reload = await invoke(c.runner, planDaemonReload()); - if (reload.exitCode !== 0) { - restoreUnit(c.unitPath, priorText); - return systemdResult(reload, "reload systemd user manager"); - } - const enable = await invoke( - c.runner, - planSystemdEnableNow({ unitName: c.taskName }), - ); - if (enable.exitCode !== 0) { - restoreUnit(c.unitPath, priorText); - await invoke(c.runner, planDaemonReload()); - return systemdResult(enable, "enable systemd user unit"); - } - writeRecord(file, { - taskName: c.taskName, - entryPath: c.entryPath, - port: c.port, - host: c.host, - installedAt: new Date().toISOString(), - backend: "systemd", - unitPath: c.unitPath, - registrationVersion: REGISTRATION_VERSION, - }); - const verifiedActive = await invoke( - c.runner, - planSystemdIsActive({ unitName: c.taskName }), - ); - if (!systemdUnitActive(verifiedActive)) { - await invoke(c.runner, planSystemdDisable({ unitName: c.taskName })); - restoreUnit(c.unitPath, priorText); - await invoke(c.runner, planDaemonReload()); - if (previous !== undefined) writeRecord(file, previous); - else removeRecord(file); - return { - ok: false, - action: "error", - state: "unknown", - message: `systemd user unit enabled but did not become active; registration was rolled back (${(verifiedActive.stderr || verifiedActive.stdout || `exit code ${verifiedActive.exitCode}`).trim()})`, - }; - } - return { - ok: true, - action: "installed", - state: "ready", - message: - "wrote per-user systemd unit, enabled it at logon and started it immediately", - }; + let priorText: string | undefined; + try { + priorText = fs.readFileSync(c.unitPath, "utf8"); + } catch {} + try { + fs.mkdirSync(path.dirname(c.unitPath), { recursive: true }); + fs.writeFileSync( + c.unitPath, + renderSystemdUnit({ + nodePath: c.nodePath, + entryPath: c.entryPath, + port: c.port, + host: c.host, + unitPath: c.unitPath, + }), + ); + } catch (error) { + return { + ok: false, + action: "error", + state: "unknown", + message: `could not write ${c.unitPath}: ${error instanceof Error ? error.message : String(error)}`, + }; + } + const reload = await invoke(c.runner, planDaemonReload()); + if (reload.exitCode !== 0) { + restoreUnit(c.unitPath, priorText); + return systemdResult(reload, "reload systemd user manager"); + } + const enable = await invoke( + c.runner, + planSystemdEnableNow({ unitName: c.taskName }), + ); + if (enable.exitCode !== 0) { + restoreUnit(c.unitPath, priorText); + await invoke(c.runner, planDaemonReload()); + return systemdResult(enable, "enable systemd user unit"); + } + writeRecord(file, { + taskName: c.taskName, + entryPath: c.entryPath, + port: c.port, + host: c.host, + installedAt: new Date().toISOString(), + backend: "systemd", + unitPath: c.unitPath, + registrationVersion: REGISTRATION_VERSION, + }); + const verifiedActive = await invoke( + c.runner, + planSystemdIsActive({ unitName: c.taskName }), + ); + if (!systemdUnitActive(verifiedActive)) { + await invoke(c.runner, planSystemdDisable({ unitName: c.taskName })); + restoreUnit(c.unitPath, priorText); + await invoke(c.runner, planDaemonReload()); + if (previous !== undefined) writeRecord(file, previous); + else removeRecord(file); + return { + ok: false, + action: "error", + state: "unknown", + message: `systemd user unit enabled but did not become active; registration was rolled back (${(verifiedActive.stderr || verifiedActive.stdout || `exit code ${verifiedActive.exitCode}`).trim()})`, + }; + } + return { + ok: true, + action: "installed", + state: "ready", + message: + "wrote per-user systemd unit, enabled it at logon and started it immediately", + }; } /** Put back what was on disk before us, or remove the file we created. */ function restoreUnit(unitPath: string, priorText: string | undefined): void { - try { - if (priorText === undefined) fs.unlinkSync(unitPath); - else fs.writeFileSync(unitPath, priorText); - } catch {} + try { + if (priorText === undefined) fs.unlinkSync(unitPath); + else fs.writeFileSync(unitPath, priorText); + } catch {} } /** Ask systemd whether the unit is enabled. `undefined` means systemd does not * know this unit at all — distinct from "known but disabled", so callers can * tell "nothing installed" from "installed, turned off". */ async function querySystemdEnabled( - c: ResolvedConfig, + c: ResolvedConfig, ): Promise { - const result = await invoke( - c.runner, - planSystemdIsEnabled({ unitName: c.taskName }), - ); - if (systemdUnitMissing(result)) return undefined; - return systemdUnitEnabled(result); + const result = await invoke( + c.runner, + planSystemdIsEnabled({ unitName: c.taskName }), + ); + if (systemdUnitMissing(result)) return undefined; + return systemdUnitEnabled(result); } async function removeSystemd(c: ResolvedConfig): Promise { - const file = serviceRecordPath(c.stateDirectory); - if (hasForeignBackendRecord(file, "systemd")) - return { - ok: false, - action: "error", - state: "unknown", - message: - "a Task Scheduler registration is recorded for this copy, not a systemd unit; left untouched", - }; - if (!hasOwnedUnit(file, c.unitPath)) { - return { - ok: true, - action: "already-absent", - state: "missing", - message: "no systemd user unit is registered for this bili copy", - }; - } - const disable = await invoke( - c.runner, - planSystemdDisable({ unitName: c.taskName }), - ); - if (disable.exitCode !== 0 && !systemdUnitMissing(disable)) - return systemdResult(disable, "disable systemd user unit"); - const stop = await invoke( - c.runner, - planSystemdStop({ unitName: c.taskName }), - ); - if (stop.exitCode !== 0 && !systemdUnitMissing(stop)) - return systemdResult(stop, "stop systemd user unit"); - try { - fs.unlinkSync(c.unitPath); - } catch (error) { - if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) - return { - ok: false, - action: "error", - state: "unknown", - message: `could not delete ${c.unitPath}: ${error instanceof Error ? error.message : String(error)}`, - }; - } - await invoke(c.runner, planDaemonReload()); - removeRecord(file); - return { - ok: true, - action: "removed", - state: "missing", - message: "systemd user unit disabled, stopped and deleted", - }; + const file = serviceRecordPath(c.stateDirectory); + if (hasForeignBackendRecord(file, "systemd")) + return { + ok: false, + action: "error", + state: "unknown", + message: + "a Task Scheduler registration is recorded for this copy, not a systemd unit; left untouched", + }; + if (!hasOwnedUnit(file, c.unitPath)) { + return { + ok: true, + action: "already-absent", + state: "missing", + message: "no systemd user unit is registered for this bili copy", + }; + } + const disable = await invoke( + c.runner, + planSystemdDisable({ unitName: c.taskName }), + ); + if (disable.exitCode !== 0 && !systemdUnitMissing(disable)) + return systemdResult(disable, "disable systemd user unit"); + const stop = await invoke( + c.runner, + planSystemdStop({ unitName: c.taskName }), + ); + if (stop.exitCode !== 0 && !systemdUnitMissing(stop)) + return systemdResult(stop, "stop systemd user unit"); + try { + fs.unlinkSync(c.unitPath); + } catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) + return { + ok: false, + action: "error", + state: "unknown", + message: `could not delete ${c.unitPath}: ${error instanceof Error ? error.message : String(error)}`, + }; + } + await invoke(c.runner, planDaemonReload()); + removeRecord(file); + return { + ok: true, + action: "removed", + state: "missing", + message: "systemd user unit disabled, stopped and deleted", + }; } async function disableSystemd(c: ResolvedConfig): Promise { - if ((await querySystemdEnabled(c)) === undefined) - return { - ok: false, - action: "error", - state: "missing", - message: - "no systemd user unit is registered for this bili copy; install it first", - }; - const result = await invoke( - c.runner, - planSystemdDisable({ unitName: c.taskName }), - ); - if ( - result.exitCode !== 0 && - !/not enabled|already disabled/i.test(`${result.stdout}\n${result.stderr}`) - ) - return systemdResult(result, "disable systemd user unit"); - const stop = await invoke( - c.runner, - planSystemdStop({ unitName: c.taskName }), - ); - if ( - stop.exitCode !== 0 && - !systemdUnitMissing(stop) && - !/not running/i.test(`${stop.stdout}\n${stop.stderr}`) - ) - return systemdResult(stop, "stop systemd user unit"); - return { - ok: true, - action: "disabled", - state: "disabled", - message: "systemd user unit disabled and stopped", - }; + if ((await querySystemdEnabled(c)) === undefined) + return { + ok: false, + action: "error", + state: "missing", + message: + "no systemd user unit is registered for this bili copy; install it first", + }; + const result = await invoke( + c.runner, + planSystemdDisable({ unitName: c.taskName }), + ); + if ( + result.exitCode !== 0 && + !/not enabled|already disabled/i.test(`${result.stdout}\n${result.stderr}`) + ) + return systemdResult(result, "disable systemd user unit"); + const stop = await invoke( + c.runner, + planSystemdStop({ unitName: c.taskName }), + ); + if ( + stop.exitCode !== 0 && + !systemdUnitMissing(stop) && + !/not running/i.test(`${stop.stdout}\n${stop.stderr}`) + ) + return systemdResult(stop, "stop systemd user unit"); + return { + ok: true, + action: "disabled", + state: "disabled", + message: "systemd user unit disabled and stopped", + }; } async function enableSystemd(c: ResolvedConfig): Promise { - if ((await querySystemdEnabled(c)) === undefined) - return { - ok: false, - action: "error", - state: "missing", - message: - "no systemd user unit is registered for this bili copy; install it first", - }; - const result = await invoke( - c.runner, - planSystemdEnableNow({ unitName: c.taskName }), - ); - if (result.exitCode !== 0) - return systemdResult(result, "enable systemd user unit"); - return { - ok: true, - action: "enabled", - state: "ready", - message: "systemd user unit enabled and started", - }; + if ((await querySystemdEnabled(c)) === undefined) + return { + ok: false, + action: "error", + state: "missing", + message: + "no systemd user unit is registered for this bili copy; install it first", + }; + const result = await invoke( + c.runner, + planSystemdEnableNow({ unitName: c.taskName }), + ); + if (result.exitCode !== 0) + return systemdResult(result, "enable systemd user unit"); + return { + ok: true, + action: "enabled", + state: "ready", + message: "systemd user unit enabled and started", + }; } async function restartSystemd(c: ResolvedConfig): Promise { - if ((await querySystemdEnabled(c)) === undefined) - return { - ok: false, - action: "error", - state: "missing", - message: - "no systemd user unit is registered for this bili copy; install it first", - }; - const stop = await invoke( - c.runner, - planSystemdStop({ unitName: c.taskName }), - ); - if ( - stop.exitCode !== 0 && - !/not running/i.test(`${stop.stdout}\n${stop.stderr}`) && - !systemdUnitMissing(stop) - ) - return systemdResult(stop, "stop systemd user unit"); - const start = await invoke( - c.runner, - planSystemdStart({ unitName: c.taskName }), - ); - if (start.exitCode !== 0) - return systemdResult(start, "start systemd user unit"); - return { - ok: true, - action: "restarted", - state: "ready", - message: "systemd user unit restart requested", - }; + if ((await querySystemdEnabled(c)) === undefined) + return { + ok: false, + action: "error", + state: "missing", + message: + "no systemd user unit is registered for this bili copy; install it first", + }; + const stop = await invoke( + c.runner, + planSystemdStop({ unitName: c.taskName }), + ); + if ( + stop.exitCode !== 0 && + !/not running/i.test(`${stop.stdout}\n${stop.stderr}`) && + !systemdUnitMissing(stop) + ) + return systemdResult(stop, "stop systemd user unit"); + const start = await invoke( + c.runner, + planSystemdStart({ unitName: c.taskName }), + ); + if (start.exitCode !== 0) + return systemdResult(start, "start systemd user unit"); + return { + ok: true, + action: "restarted", + state: "ready", + message: "systemd user unit restart requested", + }; } diff --git a/src/proxy-service/systemd.ts b/src/proxy-service/systemd.ts index 908c815b3d..fe50e48fff 100644 --- a/src/proxy-service/systemd.ts +++ b/src/proxy-service/systemd.ts @@ -17,155 +17,155 @@ import path from "node:path"; export const BILI_SYSTEMD_UNIT = "bili-proxy.service"; export interface SystemdUnitOptions { - nodePath: string; - entryPath: string; - port: number; - host?: string; - /** Absolute path of the unit file. */ - unitPath: string; + nodePath: string; + entryPath: string; + port: number; + host?: string; + /** Absolute path of the unit file. */ + unitPath: string; } function checkedOptions( - options: SystemdUnitOptions, + options: SystemdUnitOptions, ): Required { - if ( - !Number.isInteger(options.port) || - options.port < 1 || - options.port > 65535 - ) { - throw new RangeError( - "proxy service port must be an integer from 1 to 65535", - ); - } - if ( - !path.isAbsolute(options.nodePath) || - !path.isAbsolute(options.entryPath) || - !path.isAbsolute(options.unitPath) - ) { - throw new TypeError( - "proxy service executable, entry and unit paths must be absolute", - ); - } - return { - nodePath: options.nodePath, - entryPath: options.entryPath, - port: options.port, - host: options.host ?? "127.0.0.1", - unitPath: options.unitPath, - }; + if ( + !Number.isInteger(options.port) || + options.port < 1 || + options.port > 65535 + ) { + throw new RangeError( + "proxy service port must be an integer from 1 to 65535", + ); + } + if ( + !path.isAbsolute(options.nodePath) || + !path.isAbsolute(options.entryPath) || + !path.isAbsolute(options.unitPath) + ) { + throw new TypeError( + "proxy service executable, entry and unit paths must be absolute", + ); + } + return { + nodePath: options.nodePath, + entryPath: options.entryPath, + port: options.port, + host: options.host ?? "127.0.0.1", + unitPath: options.unitPath, + }; } /** systemd ExecStart quoting: each argv element is quoted, with `"` and `\` * backslash-escaped (systemd.syntax(7): double quotes keep a value as ONE * argument; the shell only sees the unquoted result). */ function quoteArg(value: string): string { - return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; + return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; } /** The unit file bili owns. Restart=on-failure keeps the proxy alive across a * crash without a supervisor of its own; --no-auto-update matches the Windows * task (an auto-updating service would restart itself under systemd's feet). */ export function renderSystemdUnit(options: SystemdUnitOptions): string { - const o = checkedOptions(options); - const exec = [ - quoteArg(o.nodePath), - quoteArg(o.entryPath), - "start", - "--host", - quoteArg(o.host), - "--port", - String(o.port), - "--no-auto-update", - ].join(" "); - return [ - "[Unit]", - "Description=Billion Context proxy (bili)", - "Documentation=https://github.com/ranxianglei/billion-context", - "After=network-online.target", - "", - "[Service]", - "Type=simple", - `ExecStart=${exec}`, - "Restart=on-failure", - "RestartSec=5", - "", - "[Install]", - "WantedBy=default.target", - "", - ].join("\n"); + const o = checkedOptions(options); + const exec = [ + quoteArg(o.nodePath), + quoteArg(o.entryPath), + "start", + "--host", + quoteArg(o.host), + "--port", + String(o.port), + "--no-auto-update", + ].join(" "); + return [ + "[Unit]", + "Description=Billion Context proxy (bili)", + "Documentation=https://github.com/ranxianglei/billion-context", + "After=network-online.target", + "", + "[Service]", + "Type=simple", + `ExecStart=${exec}`, + "Restart=on-failure", + "RestartSec=5", + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"); } export interface SystemdCommand { - file: string; - args: string[]; + file: string; + args: string[]; } export interface SystemdQueryOptions { - unitName?: string; - unitPath?: string; + unitName?: string; + unitPath?: string; } function unitNameOf(options: SystemdQueryOptions): string { - return options.unitName ?? BILI_SYSTEMD_UNIT; + return options.unitName ?? BILI_SYSTEMD_UNIT; } export function planSystemctl( - args: string[], - options: SystemdQueryOptions = {}, + args: string[], + options: SystemdQueryOptions = {}, ): SystemdCommand { - return { - file: "systemctl", - args: ["--user", ...args, unitNameOf(options)], - }; + return { + file: "systemctl", + args: ["--user", ...args, unitNameOf(options)], + }; } export function planDaemonReload(): SystemdCommand { - return { file: "systemctl", args: ["--user", "daemon-reload"] }; + return { file: "systemctl", args: ["--user", "daemon-reload"] }; } export function planSystemdEnable( - options: SystemdQueryOptions = {}, + options: SystemdQueryOptions = {}, ): SystemdCommand { - return planSystemctl(["enable"], options); + return planSystemctl(["enable"], options); } export function planSystemdStart( - options: SystemdQueryOptions = {}, + options: SystemdQueryOptions = {}, ): SystemdCommand { - return planSystemctl(["start"], options); + return planSystemctl(["start"], options); } export function planSystemdStop( - options: SystemdQueryOptions = {}, + options: SystemdQueryOptions = {}, ): SystemdCommand { - return planSystemctl(["stop"], options); + return planSystemctl(["stop"], options); } export function planSystemdDisable( - options: SystemdQueryOptions = {}, + options: SystemdQueryOptions = {}, ): SystemdCommand { - return planSystemctl(["disable"], options); + return planSystemctl(["disable"], options); } export function planSystemdEnableNow( - options: SystemdQueryOptions = {}, + options: SystemdQueryOptions = {}, ): SystemdCommand { - return planSystemctl(["enable", "--now"], options); + return planSystemctl(["enable", "--now"], options); } /** `systemctl --user is-enabled `: exit 0 with "enabled"/"enabled-runtime" * ... on stdout when the [Install] section is wired up. */ export function planSystemdIsEnabled( - options: SystemdQueryOptions = {}, + options: SystemdQueryOptions = {}, ): SystemdCommand { - return planSystemctl(["is-enabled"], options); + return planSystemctl(["is-enabled"], options); } /** `systemctl --user is-active `: exit 0 with "active" when running. */ export function planSystemdIsActive( - options: SystemdQueryOptions = {}, + options: SystemdQueryOptions = {}, ): SystemdCommand { - return planSystemctl(["is-active"], options); + return planSystemctl(["is-active"], options); } /** True when `systemctl --user` can actually reach a user bus. A bare SSH @@ -174,45 +174,45 @@ export function planSystemdIsActive( * "Failed to connect to bus"; the caller degrades to a clear message instead * of writing a unit nothing will ever load. */ export function systemdUserBusUnavailable(result: { - exitCode: number; - stdout: string; - stderr: string; + exitCode: number; + stdout: string; + stderr: string; }): boolean { - if (result.exitCode === 0) return false; - return /failed to connect to bus|no medium found|systemd.*not been booted|connection refused/i.test( - `${result.stdout}\n${result.stderr}`, - ); + if (result.exitCode === 0) return false; + return /failed to connect to bus|no medium found|systemd.*not been booted|connection refused/i.test( + `${result.stdout}\n${result.stderr}`, + ); } /** `systemctl is-enabled` verdicts that mean the unit is NOT wired to start. */ export function systemdUnitEnabled(result: { - exitCode: number; - stdout: string; - stderr: string; + exitCode: number; + stdout: string; + stderr: string; }): boolean { - if (result.exitCode !== 0) return false; - return /^\s*enabled(-runtime)?\s*$/m.test(result.stdout); + if (result.exitCode !== 0) return false; + return /^\s*enabled(-runtime)?\s*$/m.test(result.stdout); } export function systemdUnitActive(result: { - exitCode: number; - stdout: string; - stderr: string; + exitCode: number; + stdout: string; + stderr: string; }): boolean { - if (result.exitCode !== 0) return false; - return /^\s*active\s*$/m.test(result.stdout); + if (result.exitCode !== 0) return false; + return /^\s*active\s*$/m.test(result.stdout); } /** Exit-code/liveness text from `systemctl` that means "no such unit" — the * Linux twin of task-scheduler's taskMissing. */ export function systemdUnitMissing(result: { - exitCode: number; - stdout: string; - stderr: string; + exitCode: number; + stdout: string; + stderr: string; }): boolean { - const text = `${result.stdout}\n${result.stderr}`; - if (/^\s*(inactive|unknown|not-found)\s*$/m.test(result.stdout)) return true; - return /could not be found|not loaded|no such unit|does not exist/i.test( - text, - ); + const text = `${result.stdout}\n${result.stderr}`; + if (/^\s*(inactive|unknown|not-found)\s*$/m.test(result.stdout)) return true; + return /could not be found|not loaded|no such unit|does not exist/i.test( + text, + ); } diff --git a/tests/codex-cc-switch.test.ts b/tests/codex-cc-switch.test.ts index 5841fd4b46..39aef7be55 100644 --- a/tests/codex-cc-switch.test.ts +++ b/tests/codex-cc-switch.test.ts @@ -1,44 +1,44 @@ import assert from "node:assert/strict"; import test from "node:test"; import { - detectCcSwitchFromText, - isProxyManagedCredential, + detectCcSwitchFromText, + isProxyManagedCredential, } from "../src/codex-integration/cc-switch.ts"; import { credentialFingerprint } from "../src/cache-ledger.ts"; test("CC Switch Direct and Routing fixtures are detected without claiming compatibility", () => { - const direct = detectCcSwitchFromText('{"codex":{"mode":"direct"}}'); - assert.equal(direct.discovered, true); - assert.equal(direct.mode, "direct"); - assert.equal(direct.compatibility, "config-route-only"); - assert.match(direct.detail, /provider-database synchronization is not integrated/); - const routing = detectCcSwitchFromText(undefined, '{"proxyMode":"routing"}'); - assert.equal(routing.mode, "routing"); - assert.equal(routing.compatibility, "unsupported"); - const unknown = detectCcSwitchFromText("{}", undefined); - assert.equal(unknown.discovered, true); - assert.equal(unknown.mode, "unknown"); - assert.equal(detectCcSwitchFromText().discovered, false); + const direct = detectCcSwitchFromText('{"codex":{"mode":"direct"}}'); + assert.equal(direct.discovered, true); + assert.equal(direct.mode, "direct"); + assert.equal(direct.compatibility, "config-route-only"); + assert.match(direct.detail, /provider-database synchronization is not integrated/); + const routing = detectCcSwitchFromText(undefined, '{"proxyMode":"routing"}'); + assert.equal(routing.mode, "routing"); + assert.equal(routing.compatibility, "unsupported"); + const unknown = detectCcSwitchFromText("{}", undefined); + assert.equal(unknown.discovered, true); + assert.equal(unknown.mode, "unknown"); + assert.equal(detectCcSwitchFromText().discovered, false); }); test("CC Switch live-state apps.codex.mode schema is recognized", () => { - const result = detectCcSwitchFromText(undefined, '{"version":1,"apps":{"codex":{"mode":"direct"}}}'); - assert.equal(result.discovered, true); - assert.equal(result.mode, "direct"); - assert.equal(result.compatibility, "config-route-only"); + const result = detectCcSwitchFromText(undefined, '{"version":1,"apps":{"codex":{"mode":"direct"}}}'); + assert.equal(result.discovered, true); + assert.equal(result.mode, "direct"); + assert.equal(result.compatibility, "config-route-only"); }); test("PROXY_MANAGED is not persisted as a credential fingerprint", () => { - assert.equal(isProxyManagedCredential("Bearer PROXY_MANAGED"), true); - assert.equal( - credentialFingerprint({ authorization: "Bearer PROXY_MANAGED" }), - undefined, - ); - assert.equal( - credentialFingerprint({ - authorization: "Bearer sk-live-example", - })?.startsWith("sha256:"), - true, - ); + assert.equal(isProxyManagedCredential("Bearer PROXY_MANAGED"), true); + assert.equal( + credentialFingerprint({ authorization: "Bearer PROXY_MANAGED" }), + undefined, + ); + assert.equal( + credentialFingerprint({ + authorization: "Bearer sk-live-example", + })?.startsWith("sha256:"), + true, + ); }); diff --git a/tests/codex-chatgpt-capability.test.ts b/tests/codex-chatgpt-capability.test.ts index afa3fa36de..b48859d15a 100644 --- a/tests/codex-chatgpt-capability.test.ts +++ b/tests/codex-chatgpt-capability.test.ts @@ -4,15 +4,15 @@ import test from "node:test"; import { chatGptDesktopCapability } from "../src/codex-integration/chatgpt-capability.ts"; test("ChatGPT subscription and Desktop remain explicitly unsupported without credential access", () => { - assert.deepEqual(chatGptDesktopCapability, { - state: "待完成/可实现", - credentials: "not-read-not-persisted", - officialLoginChannels: "preserved", - desktopMcp: "separate-from-model-routing", - }); - const source = fs.readFileSync( - new URL("../src/codex-integration/chatgpt-capability.ts", import.meta.url), - "utf8", - ); - assert.doesNotMatch(source, /readFileSync|writeFileSync/); + assert.deepEqual(chatGptDesktopCapability, { + state: "待完成/可实现", + credentials: "not-read-not-persisted", + officialLoginChannels: "preserved", + desktopMcp: "separate-from-model-routing", + }); + const source = fs.readFileSync( + new URL("../src/codex-integration/chatgpt-capability.ts", import.meta.url), + "utf8", + ); + assert.doesNotMatch(source, /readFileSync|writeFileSync/); }); diff --git a/tests/codex-hooks-skill.test.ts b/tests/codex-hooks-skill.test.ts index 3970202591..c0b26b75dc 100644 --- a/tests/codex-hooks-skill.test.ts +++ b/tests/codex-hooks-skill.test.ts @@ -4,375 +4,375 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { - assertCodexConfigLoads, - codexHookTable, - codexHooksEnabledNote, - codexHooksFeature, - findBiliCodexHook, - isBiliCodexHookCommand, - planCodexHook, - readCodexHookCommands, - stripCodexHook, + assertCodexConfigLoads, + codexHookTable, + codexHooksEnabledNote, + codexHooksFeature, + findBiliCodexHook, + isBiliCodexHookCommand, + planCodexHook, + readCodexHookCommands, + stripCodexHook, } from "../src/codex-integration/hooks.ts"; import { - CODEX_SKILL_MARKDOWN, - codexSkillDir, - codexSkillFile, - codexSkillStatus, - installCodexSkill, - readSkillName, - removeCodexSkill, + CODEX_SKILL_MARKDOWN, + codexSkillDir, + codexSkillFile, + codexSkillStatus, + installCodexSkill, + readSkillName, + removeCodexSkill, } from "../src/codex-integration/skill.ts"; import { - insertTableRaw, - tableRegions, + insertTableRaw, + tableRegions, } from "../src/codex-integration/toml-field.ts"; const hookCommand = 'node "C:/bili/dist/codex/bootstrap-hook.js"'; function tempHome(): { env: NodeJS.ProcessEnv; dir: string } { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-skill-")); - return { env: { ...process.env, CODEX_HOME: dir }, dir }; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-skill-")); + return { env: { ...process.env, CODEX_HOME: dir }, dir }; } test("hook command matching recognizes our script across install roots", () => { - assert.equal(isBiliCodexHookCommand(hookCommand), true); - assert.equal( - isBiliCodexHookCommand( - 'node "C:/Users/x/AppData/Roaming/npm/node_modules/billion-context/dist/codex/bootstrap-hook.js"', - ), - true, - ); - assert.equal( - isBiliCodexHookCommand("lean-ctx.exe hook codex-session-start"), - false, - ); - assert.equal( - isBiliCodexHookCommand('node "C:/other/dist/claude-native-bootstrap.js"'), - false, - ); + assert.equal(isBiliCodexHookCommand(hookCommand), true); + assert.equal( + isBiliCodexHookCommand( + 'node "C:/Users/x/AppData/Roaming/npm/node_modules/billion-context/dist/codex/bootstrap-hook.js"', + ), + true, + ); + assert.equal( + isBiliCodexHookCommand("lean-ctx.exe hook codex-session-start"), + false, + ); + assert.equal( + isBiliCodexHookCommand('node "C:/other/dist/claude-native-bootstrap.js"'), + false, + ); }); test("hook install keeps user tables byte-for-byte and is idempotent", () => { - const original = 'model = "gpt-5"\n\n[features]\nhooks = true\n'; - const first = planCodexHook(original, hookCommand); - assert.equal(first.action, "install"); - assert.match(first.text, /\[\[hooks\.SessionStart\]\]/); - assert.match(first.text, /\[features\]\nhooks = true/); - assert.equal(findBiliCodexHook(first.text), hookCommand); - assert.equal(codexHooksEnabledNote(first.text), ""); - - const again = planCodexHook(first.text, hookCommand); - assert.equal(again.action, "keep"); - assert.equal(again.text, first.text); - - const moved = planCodexHook( - first.text, - 'node "D:/new/dist/codex/bootstrap-hook.js"', - ); - assert.equal(moved.action, "refresh"); - assert.equal( - findBiliCodexHook(moved.text), - 'node "D:/new/dist/codex/bootstrap-hook.js"', - ); + const original = 'model = "gpt-5"\n\n[features]\nhooks = true\n'; + const first = planCodexHook(original, hookCommand); + assert.equal(first.action, "install"); + assert.match(first.text, /\[\[hooks\.SessionStart\]\]/); + assert.match(first.text, /\[features\]\nhooks = true/); + assert.equal(findBiliCodexHook(first.text), hookCommand); + assert.equal(codexHooksEnabledNote(first.text), ""); + + const again = planCodexHook(first.text, hookCommand); + assert.equal(again.action, "keep"); + assert.equal(again.text, first.text); + + const moved = planCodexHook( + first.text, + 'node "D:/new/dist/codex/bootstrap-hook.js"', + ); + assert.equal(moved.action, "refresh"); + assert.equal( + findBiliCodexHook(moved.text), + 'node "D:/new/dist/codex/bootstrap-hook.js"', + ); }); test("a foreign SessionStart entry is preserved and ours is appended", () => { - // `[[hooks.SessionStart]]` is an array: a foreign entry is a SIBLING, so - // bili adds its own instead of giving up. This is the real-machine case - // (lean-ctx already owns a SessionStart entry). - const foreign = `model = "gpt-5"\n\n[[hooks.SessionStart]]\nmatcher = "startup|resume|clear"\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\n`; - const plan = planCodexHook(foreign, hookCommand); - assert.equal(plan.action, "install"); - assert.match(plan.text, /lean-ctx\.exe hook codex-session-start/); - assert.equal(findBiliCodexHook(plan.text), hookCommand); - // Both entries survive as SEPARATE array-of-tables entries. - assert.equal(plan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 2); - assert.equal(assertCodexConfigLoads(plan.text), undefined); - - // Re-running is a no-op, and removal takes back only ours. - const again = planCodexHook(plan.text, hookCommand); - assert.equal(again.action, "keep"); - const stripped = stripCodexHook(plan.text); - assert.equal(stripped.removed, true); - assert.match(stripped.text, /lean-ctx\.exe hook codex-session-start/); - assert.doesNotMatch(stripped.text, /bootstrap-hook\.js/); + // `[[hooks.SessionStart]]` is an array: a foreign entry is a SIBLING, so + // bili adds its own instead of giving up. This is the real-machine case + // (lean-ctx already owns a SessionStart entry). + const foreign = `model = "gpt-5"\n\n[[hooks.SessionStart]]\nmatcher = "startup|resume|clear"\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\n`; + const plan = planCodexHook(foreign, hookCommand); + assert.equal(plan.action, "install"); + assert.match(plan.text, /lean-ctx\.exe hook codex-session-start/); + assert.equal(findBiliCodexHook(plan.text), hookCommand); + // Both entries survive as SEPARATE array-of-tables entries. + assert.equal(plan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 2); + assert.equal(assertCodexConfigLoads(plan.text), undefined); + + // Re-running is a no-op, and removal takes back only ours. + const again = planCodexHook(plan.text, hookCommand); + assert.equal(again.action, "keep"); + const stripped = stripCodexHook(plan.text); + assert.equal(stripped.removed, true); + assert.match(stripped.text, /lean-ctx\.exe hook codex-session-start/); + assert.doesNotMatch(stripped.text, /bootstrap-hook\.js/); }); test("our entry is always the nested MatcherGroup shape Codex registers", () => { - // THE regression the user hit. Codex deserializes each entry as a - // `MatcherGroup` = `{ matcher?, hooks = [ {type, command, timeout} ] }`. - // Handler fields set DIRECTLY on the entry are unknown keys, so serde drops - // them silently: the config loads, `codex mcp list` succeeds, and the hook - // never registers. Only Codex's app-server `hooks/list` RPC sees this, so a - // load probe can never cover it — this shape assertion is the guard. - const rendered = codexHookTable(hookCommand); - assert.match( - rendered, - /^\[\[hooks\.SessionStart\]\]\nhooks = \[\{ type = "command", command = .*, timeout = 15 \}\]\n$/, - ); - // The flat shape must never be emitted. - assert.doesNotMatch(rendered, /^type = "command"$/m); - - // And the guard must reject the flat shape when it is OURS... - const flatOurs = `[[hooks.SessionStart]]\ntype = "command"\ncommand = ${JSON.stringify(hookCommand)}\ntimeout = 15\n`; - const reason = assertCodexConfigLoads(flatOurs); - assert.notEqual(reason, undefined); - assert.match(String(reason), /must nest its handler/); - - // ...while a FOREIGN flat entry is not bili's to police: it must not block - // installing our own correct entry (that would strand exactly the users who - // already run another hook tool). - const foreignFlat = `model = "gpt-5"\n\n[[hooks.SessionStart]]\ntype = "command"\ncommand = "lean-ctx.exe hook codex-session-start"\ntimeout = 10\n`; - assert.equal(assertCodexConfigLoads(foreignFlat), undefined); - const plan = planCodexHook(foreignFlat, hookCommand); - assert.equal(plan.action, "install"); - assert.equal(assertCodexConfigLoads(plan.text), undefined); + // THE regression the user hit. Codex deserializes each entry as a + // `MatcherGroup` = `{ matcher?, hooks = [ {type, command, timeout} ] }`. + // Handler fields set DIRECTLY on the entry are unknown keys, so serde drops + // them silently: the config loads, `codex mcp list` succeeds, and the hook + // never registers. Only Codex's app-server `hooks/list` RPC sees this, so a + // load probe can never cover it — this shape assertion is the guard. + const rendered = codexHookTable(hookCommand); + assert.match( + rendered, + /^\[\[hooks\.SessionStart\]\]\nhooks = \[\{ type = "command", command = .*, timeout = 15 \}\]\n$/, + ); + // The flat shape must never be emitted. + assert.doesNotMatch(rendered, /^type = "command"$/m); + + // And the guard must reject the flat shape when it is OURS... + const flatOurs = `[[hooks.SessionStart]]\ntype = "command"\ncommand = ${JSON.stringify(hookCommand)}\ntimeout = 15\n`; + const reason = assertCodexConfigLoads(flatOurs); + assert.notEqual(reason, undefined); + assert.match(String(reason), /must nest its handler/); + + // ...while a FOREIGN flat entry is not bili's to police: it must not block + // installing our own correct entry (that would strand exactly the users who + // already run another hook tool). + const foreignFlat = `model = "gpt-5"\n\n[[hooks.SessionStart]]\ntype = "command"\ncommand = "lean-ctx.exe hook codex-session-start"\ntimeout = 10\n`; + assert.equal(assertCodexConfigLoads(foreignFlat), undefined); + const plan = planCodexHook(foreignFlat, hookCommand); + assert.equal(plan.action, "install"); + assert.equal(assertCodexConfigLoads(plan.text), undefined); }); test("an existing flat bili entry is upgraded in place, not left invisible", () => { - // Self-heal: bili's own older output carried the flat shape. Detecting it as - // "owned" and merely rewriting the command string would leave it silently - // ignored forever, so the whole entry must be replaced. - const flatOurs = `model = "gpt-5"\n\n[[hooks.SessionStart]]\ntype = "command"\ncommand = ${JSON.stringify(hookCommand)}\ntimeout = 15\n`; - const plan = planCodexHook(flatOurs, hookCommand); - assert.equal(plan.action, "refresh"); - assert.match(plan.note, /upgraded to the shape Codex registers/); - assert.equal(assertCodexConfigLoads(plan.text), undefined); - assert.doesNotMatch(plan.text, /^type = "command"$/m); - // Still exactly one entry, still ours, and the user's other tables survive. - assert.equal(plan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 1); - assert.equal(findBiliCodexHook(plan.text), hookCommand); - assert.match(plan.text, /model = "gpt-5"/); + // Self-heal: bili's own older output carried the flat shape. Detecting it as + // "owned" and merely rewriting the command string would leave it silently + // ignored forever, so the whole entry must be replaced. + const flatOurs = `model = "gpt-5"\n\n[[hooks.SessionStart]]\ntype = "command"\ncommand = ${JSON.stringify(hookCommand)}\ntimeout = 15\n`; + const plan = planCodexHook(flatOurs, hookCommand); + assert.equal(plan.action, "refresh"); + assert.match(plan.note, /upgraded to the shape Codex registers/); + assert.equal(assertCodexConfigLoads(plan.text), undefined); + assert.doesNotMatch(plan.text, /^type = "command"$/m); + // Still exactly one entry, still ours, and the user's other tables survive. + assert.equal(plan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 1); + assert.equal(findBiliCodexHook(plan.text), hookCommand); + assert.match(plan.text, /model = "gpt-5"/); }); test("strip removes only our entry and drops the table when it was ours alone", () => { - const original = 'model = "gpt-5"\n'; - const installed = planCodexHook(original, hookCommand).text; - const stripped = stripCodexHook(installed); - assert.equal(stripped.removed, true); - assert.equal(findBiliCodexHook(stripped.text), undefined); - assert.doesNotMatch(stripped.text, /hooks\.SessionStart/); - assert.match(stripped.text, /model = "gpt-5"/); - assert.equal(stripCodexHook(original).removed, false); + const original = 'model = "gpt-5"\n'; + const installed = planCodexHook(original, hookCommand).text; + const stripped = stripCodexHook(installed); + assert.equal(stripped.removed, true); + assert.equal(findBiliCodexHook(stripped.text), undefined); + assert.doesNotMatch(stripped.text, /hooks\.SessionStart/); + assert.match(stripped.text, /model = "gpt-5"/); + assert.equal(stripCodexHook(original).removed, false); }); test("strip keeps foreign entries in a shared SessionStart table", () => { - const shared = `model = "gpt-5"\n\n[[hooks.SessionStart]]\nmatcher = "startup|resume|clear"\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\n`; - const withOurs = `${shared.trimEnd()}\n\n${codexHookTable(hookCommand).trimEnd()}\n`; - // Two separate tables: ours is dropped, theirs survives untouched. - const stripped = stripCodexHook(withOurs); - assert.equal(stripped.removed, true); - assert.match(stripped.text, /lean-ctx\.exe hook codex-session-start/); - assert.doesNotMatch(stripped.text, /bootstrap-hook\.js/); + const shared = `model = "gpt-5"\n\n[[hooks.SessionStart]]\nmatcher = "startup|resume|clear"\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\n`; + const withOurs = `${shared.trimEnd()}\n\n${codexHookTable(hookCommand).trimEnd()}\n`; + // Two separate tables: ours is dropped, theirs survives untouched. + const stripped = stripCodexHook(withOurs); + assert.equal(stripped.removed, true); + assert.match(stripped.text, /lean-ctx\.exe hook codex-session-start/); + assert.doesNotMatch(stripped.text, /bootstrap-hook\.js/); }); test("hooks feature note reports a disabled or missing switch", () => { - assert.match(codexHooksEnabledNote('model = "gpt-5"\n'), /hooks = true/); - assert.match( - codexHooksEnabledNote("[features]\nhooks = false\n"), - /disables hooks/, - ); - assert.equal(codexHooksEnabledNote("[features]\nhooks = true\n"), ""); + assert.match(codexHooksEnabledNote('model = "gpt-5"\n'), /hooks = true/); + assert.match( + codexHooksEnabledNote("[features]\nhooks = false\n"), + /disables hooks/, + ); + assert.equal(codexHooksEnabledNote("[features]\nhooks = true\n"), ""); }); test("the feature switch is read on CRLF configs (Windows)", () => { - // Codex keeps CRLF on Windows. An anchored `$` that does not admit the - // trailing `\r` silently missed the switch, so the installer claimed hook - // execution was off on a config that plainly had `hooks = true`. - const crlf = - 'model = "gpt-5"\r\n\r\n[features]\r\nhooks = true\r\n\r\n[[hooks.SessionStart]]\r\nhooks = [{ type = "command", command = "node C:/x/codex/bootstrap-hook.js", timeout = 15 }]\r\n'; - assert.deepEqual(codexHooksFeature(crlf), { value: true, raw: "true" }); - assert.equal(codexHooksEnabledNote(crlf), ""); - assert.equal(findBiliCodexHook(crlf), "node C:/x/codex/bootstrap-hook.js"); - assert.equal(assertCodexConfigLoads(crlf), undefined); - - // And a CRLF config with the switch explicitly off still reports it. - const off = crlf.replace("hooks = true", "hooks = false"); - assert.equal(codexHooksFeature(off)?.value, false); - assert.match(codexHooksEnabledNote(off), /disables hooks/); + // Codex keeps CRLF on Windows. An anchored `$` that does not admit the + // trailing `\r` silently missed the switch, so the installer claimed hook + // execution was off on a config that plainly had `hooks = true`. + const crlf = + 'model = "gpt-5"\r\n\r\n[features]\r\nhooks = true\r\n\r\n[[hooks.SessionStart]]\r\nhooks = [{ type = "command", command = "node C:/x/codex/bootstrap-hook.js", timeout = 15 }]\r\n'; + assert.deepEqual(codexHooksFeature(crlf), { value: true, raw: "true" }); + assert.equal(codexHooksEnabledNote(crlf), ""); + assert.equal(findBiliCodexHook(crlf), "node C:/x/codex/bootstrap-hook.js"); + assert.equal(assertCodexConfigLoads(crlf), undefined); + + // And a CRLF config with the switch explicitly off still reports it. + const off = crlf.replace("hooks = true", "hooks = false"); + assert.equal(codexHooksFeature(off)?.value, false); + assert.match(codexHooksEnabledNote(off), /disables hooks/); }); test("an appended entry follows the file's existing line endings", () => { - // The repo convention (src/kimi/toml-edit.ts:21, src/launcher.ts:2466) is to - // never convert a user's file nor mix endings into it. Appending with a bare - // "\n" left a CRLF config with a mixed-ending block. - const crlfBase = - 'model = "gpt-5"\r\n\r\n[features]\r\nhooks = true\r\n\r\n[[hooks.SessionStart]]\r\nmatcher = "startup"\r\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\r\n'; - const crlfPlan = planCodexHook(crlfBase, hookCommand); - assert.equal(crlfPlan.action, "install"); - // No lone LF anywhere in the CRLF file after the append. - assert.equal(/[^\r]\n/.test(crlfPlan.text), false); - assert.equal(crlfPlan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 2); - assert.equal(findBiliCodexHook(crlfPlan.text), hookCommand); - - // An LF file stays LF. - const lfBase = 'model = "gpt-5"\n'; - const lfPlan = planCodexHook(lfBase, hookCommand); - assert.equal(lfPlan.text.includes("\r"), false); + // The repo convention (src/kimi/toml-edit.ts:21, src/launcher.ts:2466) is to + // never convert a user's file nor mix endings into it. Appending with a bare + // "\n" left a CRLF config with a mixed-ending block. + const crlfBase = + 'model = "gpt-5"\r\n\r\n[features]\r\nhooks = true\r\n\r\n[[hooks.SessionStart]]\r\nmatcher = "startup"\r\nhooks = [{ type = "command", command = "lean-ctx.exe hook codex-session-start", timeout = 10 }]\r\n'; + const crlfPlan = planCodexHook(crlfBase, hookCommand); + assert.equal(crlfPlan.action, "install"); + // No lone LF anywhere in the CRLF file after the append. + assert.equal(/[^\r]\n/.test(crlfPlan.text), false); + assert.equal(crlfPlan.text.match(/\[\[hooks\.SessionStart\]\]/g)?.length, 2); + assert.equal(findBiliCodexHook(crlfPlan.text), hookCommand); + + // An LF file stays LF. + const lfBase = 'model = "gpt-5"\n'; + const lfPlan = planCodexHook(lfBase, hookCommand); + assert.equal(lfPlan.text.includes("\r"), false); }); test("hook table rendering and region detection agree", () => { - // codexHookTable already emits the header; the region finder must see an - // ARRAY-of-tables header, not just a plain one. - const text = codexHookTable(hookCommand); - assert.match(text, /^\[\[hooks\.SessionStart\]\]\n/); - const regions = tableRegions(text, "hooks.SessionStart"); - assert.equal(regions.length, 1); - assert.deepEqual(readCodexHookCommands(regions[0]!), [hookCommand]); + // codexHookTable already emits the header; the region finder must see an + // ARRAY-of-tables header, not just a plain one. + const text = codexHookTable(hookCommand); + assert.match(text, /^\[\[hooks\.SessionStart\]\]\n/); + const regions = tableRegions(text, "hooks.SessionStart"); + assert.equal(regions.length, 1); + assert.deepEqual(readCodexHookCommands(regions[0]!), [hookCommand]); }); test("the pre-write guard rejects every shape Codex refuses to load", () => { - // The regression that broke Codex Desktop: a map-valued `hooks`. This exact - // shape is what bili used to write. - const rejected = `[hooks.SessionStart]\nhooks = [{ type = "command", command = ${JSON.stringify(hookCommand)}, timeout = 15 }]\n`; - const reason = assertCodexConfigLoads(rejected); - assert.notEqual(reason, undefined); - assert.match(String(reason), /\[\[hooks\.SessionStart\]\]/); - - // A top-level `hooks = ...` collapses the sequence too. - assert.notEqual(assertCodexConfigLoads("hooks = []\n"), undefined); - - // The flat-sequence shape Codex also refuses (`expected struct HooksToml`). - assert.notEqual( - assertCodexConfigLoads( - `[[hooks]]\nevent = "SessionStart"\ncommand = ${JSON.stringify(hookCommand)}\n`, - ), - undefined, - ); - - // An entry with no command at all — the stub a buggy strip once left behind. - assert.notEqual( - assertCodexConfigLoads('[[hooks.SessionStart]]\ntype = "command"\n'), - undefined, - ); - - // What bili actually writes must pass. - assert.equal(assertCodexConfigLoads(codexHookTable(hookCommand)), undefined); - assert.equal( - assertCodexConfigLoads( - `model = "gpt-5"\n\n[features]\nhooks = true\n\n${codexHookTable(hookCommand)}`, - ), - undefined, - ); + // The regression that broke Codex Desktop: a map-valued `hooks`. This exact + // shape is what bili used to write. + const rejected = `[hooks.SessionStart]\nhooks = [{ type = "command", command = ${JSON.stringify(hookCommand)}, timeout = 15 }]\n`; + const reason = assertCodexConfigLoads(rejected); + assert.notEqual(reason, undefined); + assert.match(String(reason), /\[\[hooks\.SessionStart\]\]/); + + // A top-level `hooks = ...` collapses the sequence too. + assert.notEqual(assertCodexConfigLoads("hooks = []\n"), undefined); + + // The flat-sequence shape Codex also refuses (`expected struct HooksToml`). + assert.notEqual( + assertCodexConfigLoads( + `[[hooks]]\nevent = "SessionStart"\ncommand = ${JSON.stringify(hookCommand)}\n`, + ), + undefined, + ); + + // An entry with no command at all — the stub a buggy strip once left behind. + assert.notEqual( + assertCodexConfigLoads('[[hooks.SessionStart]]\ntype = "command"\n'), + undefined, + ); + + // What bili actually writes must pass. + assert.equal(assertCodexConfigLoads(codexHookTable(hookCommand)), undefined); + assert.equal( + assertCodexConfigLoads( + `model = "gpt-5"\n\n[features]\nhooks = true\n\n${codexHookTable(hookCommand)}`, + ), + undefined, + ); }); test("Codex's own hooks.state trust ledger is not mistaken for our stage table", () => { - // Codex records hook approval in `[hooks.state.':::']`, - // a SINGLE-bracket table holding key/value pairs. A guard that treated every - // `hooks`-prefixed header as bili's malformed stage table rejected the whole - // config, so `plugin install codex` skipped the hook face on any config where - // a hook had ever been trusted — with no error, just "hook: skipped". - const trustLedger = `[hooks.state.'C:\\Users\\me\\.codex\\config.toml:session_start:0:0']\ntrusted_hash = "sha256:d89b106f182af9d93c0e2d7611ce5a43b270367c15ec4b3fa8dfeb53768ce2fe"\n`; - assert.equal(assertCodexConfigLoads(trustLedger), undefined); - - // And together with our own entry, which is what a real config looks like. - const withLedger = `${codexHookTable(hookCommand)}\n${trustLedger}`; - assert.equal(assertCodexConfigLoads(withLedger), undefined); - - // The plan still installs into such a file rather than bailing out. - const plan = planCodexHook(trustLedger, hookCommand); - assert.equal(plan.action, "install"); - assert.match(plan.text, /\[\[hooks\.SessionStart\]\]/); - assert.match(plan.text, /hooks\.state/); - assert.equal(assertCodexConfigLoads(plan.text), undefined); + // Codex records hook approval in `[hooks.state.':::']`, + // a SINGLE-bracket table holding key/value pairs. A guard that treated every + // `hooks`-prefixed header as bili's malformed stage table rejected the whole + // config, so `plugin install codex` skipped the hook face on any config where + // a hook had ever been trusted — with no error, just "hook: skipped". + const trustLedger = `[hooks.state.'C:\\Users\\me\\.codex\\config.toml:session_start:0:0']\ntrusted_hash = "sha256:d89b106f182af9d93c0e2d7611ce5a43b270367c15ec4b3fa8dfeb53768ce2fe"\n`; + assert.equal(assertCodexConfigLoads(trustLedger), undefined); + + // And together with our own entry, which is what a real config looks like. + const withLedger = `${codexHookTable(hookCommand)}\n${trustLedger}`; + assert.equal(assertCodexConfigLoads(withLedger), undefined); + + // The plan still installs into such a file rather than bailing out. + const plan = planCodexHook(trustLedger, hookCommand); + assert.equal(plan.action, "install"); + assert.match(plan.text, /\[\[hooks\.SessionStart\]\]/); + assert.match(plan.text, /hooks\.state/); + assert.equal(assertCodexConfigLoads(plan.text), undefined); }); test("insertTableRaw lands inside the table, before trailing comments", () => { - const text = "[features]\na = 1\n\n# next section follows\n[other]\nb = 2\n"; - const next = insertTableRaw(text, "features", "hooks = true"); - assert.match( - next, - /\[features\]\na = 1\nhooks = true\n\n# next section follows/, - ); - assert.match(next, /\[other\]\nb = 2/); + const text = "[features]\na = 1\n\n# next section follows\n[other]\nb = 2\n"; + const next = insertTableRaw(text, "features", "hooks = true"); + assert.match( + next, + /\[features\]\na = 1\nhooks = true\n\n# next section follows/, + ); + assert.match(next, /\[other\]\nb = 2/); }); test("skill install writes our document and is idempotent", () => { - const { env, dir } = tempHome(); - try { - assert.equal(codexSkillStatus(env), "missing"); - const first = installCodexSkill(env); - assert.equal(first.written, true); - assert.equal(codexSkillStatus(env), "installed"); - assert.equal( - fs.readFileSync(codexSkillFile(env), "utf8"), - CODEX_SKILL_MARKDOWN, - ); - assert.equal(readSkillName(CODEX_SKILL_MARKDOWN), "bili"); - assert.equal(path.dirname(codexSkillFile(env)), codexSkillDir(env)); - - const again = installCodexSkill(env); - assert.equal(again.written, false); - assert.equal(again.note, "ACP skill already installed"); - } finally { - fs.rmSync(dir, { recursive: true, force: true }); - } + const { env, dir } = tempHome(); + try { + assert.equal(codexSkillStatus(env), "missing"); + const first = installCodexSkill(env); + assert.equal(first.written, true); + assert.equal(codexSkillStatus(env), "installed"); + assert.equal( + fs.readFileSync(codexSkillFile(env), "utf8"), + CODEX_SKILL_MARKDOWN, + ); + assert.equal(readSkillName(CODEX_SKILL_MARKDOWN), "bili"); + assert.equal(path.dirname(codexSkillFile(env)), codexSkillDir(env)); + + const again = installCodexSkill(env); + assert.equal(again.written, false); + assert.equal(again.note, "ACP skill already installed"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } }); test("a foreign same-named skill is never overwritten or deleted", () => { - const { env, dir } = tempHome(); - try { - fs.mkdirSync(codexSkillDir(env), { recursive: true }); - const mine = - "---\nname: bili\ndescription: user's own skill\n---\n\nkeep me\n"; - fs.writeFileSync(codexSkillFile(env), mine); - assert.equal(codexSkillStatus(env), "foreign"); - const install = installCodexSkill(env); - assert.equal(install.written, false); - assert.match(install.note, /left untouched/); - - fs.writeFileSync( - codexSkillFile(env), - "---\nname: someone-else\n---\nbody\n", - ); - assert.equal(codexSkillStatus(env), "foreign"); - const removal = removeCodexSkill(env); - assert.equal(removal.removed, false); - assert.equal( - fs.readFileSync(codexSkillFile(env), "utf8"), - "---\nname: someone-else\n---\nbody\n", - ); - } finally { - fs.rmSync(dir, { recursive: true, force: true }); - } + const { env, dir } = tempHome(); + try { + fs.mkdirSync(codexSkillDir(env), { recursive: true }); + const mine = + "---\nname: bili\ndescription: user's own skill\n---\n\nkeep me\n"; + fs.writeFileSync(codexSkillFile(env), mine); + assert.equal(codexSkillStatus(env), "foreign"); + const install = installCodexSkill(env); + assert.equal(install.written, false); + assert.match(install.note, /left untouched/); + + fs.writeFileSync( + codexSkillFile(env), + "---\nname: someone-else\n---\nbody\n", + ); + assert.equal(codexSkillStatus(env), "foreign"); + const removal = removeCodexSkill(env); + assert.equal(removal.removed, false); + assert.equal( + fs.readFileSync(codexSkillFile(env), "utf8"), + "---\nname: someone-else\n---\nbody\n", + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } }); test("an owned-but-edited skill is marked outdated and refreshed", () => { - const { env, dir } = tempHome(); - try { - installCodexSkill(env); - fs.writeFileSync( - codexSkillFile(env), - `${CODEX_SKILL_MARKDOWN}\nlocal note\n`, - ); - assert.equal(codexSkillStatus(env), "outdated"); - const refreshed = installCodexSkill(env); - assert.equal(refreshed.written, true); - assert.equal(codexSkillStatus(env), "installed"); - assert.equal( - fs.readFileSync(codexSkillFile(env), "utf8"), - CODEX_SKILL_MARKDOWN, - ); - } finally { - fs.rmSync(dir, { recursive: true, force: true }); - } + const { env, dir } = tempHome(); + try { + installCodexSkill(env); + fs.writeFileSync( + codexSkillFile(env), + `${CODEX_SKILL_MARKDOWN}\nlocal note\n`, + ); + assert.equal(codexSkillStatus(env), "outdated"); + const refreshed = installCodexSkill(env); + assert.equal(refreshed.written, true); + assert.equal(codexSkillStatus(env), "installed"); + assert.equal( + fs.readFileSync(codexSkillFile(env), "utf8"), + CODEX_SKILL_MARKDOWN, + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } }); test("remove deletes only our skill and leaves a non-empty directory", () => { - const { env, dir } = tempHome(); - try { - installCodexSkill(env); - fs.writeFileSync(path.join(codexSkillDir(env), "notes.md"), "user notes\n"); - const removal = removeCodexSkill(env); - assert.equal(removal.removed, true); - assert.equal(fs.existsSync(codexSkillFile(env)), false); - assert.equal( - fs.existsSync(path.join(codexSkillDir(env), "notes.md")), - true, - ); - assert.equal(codexSkillStatus(env), "missing"); - } finally { - fs.rmSync(dir, { recursive: true, force: true }); - } + const { env, dir } = tempHome(); + try { + installCodexSkill(env); + fs.writeFileSync(path.join(codexSkillDir(env), "notes.md"), "user notes\n"); + const removal = removeCodexSkill(env); + assert.equal(removal.removed, true); + assert.equal(fs.existsSync(codexSkillFile(env)), false); + assert.equal( + fs.existsSync(path.join(codexSkillDir(env), "notes.md")), + true, + ); + assert.equal(codexSkillStatus(env), "missing"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } }); diff --git a/tests/codex-install-faces.test.ts b/tests/codex-install-faces.test.ts index 2127abda18..0079d6835a 100644 --- a/tests/codex-install-faces.test.ts +++ b/tests/codex-install-faces.test.ts @@ -5,30 +5,30 @@ import path from "node:path"; import test from "node:test"; function withEnv( - vars: Record, - fn: () => void | Promise, + vars: Record, + fn: () => void | Promise, ): Promise { - const saved = new Map(); - for (const [key, value] of Object.entries(vars)) { - saved.set(key, process.env[key]); - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } - const restore = (): void => { - for (const [key, value] of saved) { - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } - }; - try { - const result = fn(); - if (result instanceof Promise) return result.finally(restore); - restore(); - return Promise.resolve(); - } catch (error) { - restore(); - return Promise.reject(error); - } + const saved = new Map(); + for (const [key, value] of Object.entries(vars)) { + saved.set(key, process.env[key]); + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + const restore = (): void => { + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }; + try { + const result = fn(); + if (result instanceof Promise) return result.finally(restore); + restore(); + return Promise.resolve(); + } catch (error) { + restore(); + return Promise.reject(error); + } } // Ticket 08 regression: the Codex install flow must land ALL four faces — @@ -36,110 +36,110 @@ function withEnv( // them all back out. The user's report was exactly this gap: the desktop Codex // saw the MCP plugin but neither a hook nor an ACP skill. test("plugin install codex writes MCP + route + hook + skill, and remove reverts all four", async () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-faces-")); - const { pluginInstall, pluginRemove, pluginStatusAll } = await import( - "../src/plugin-install.ts" - ); - try { - await withEnv({ CODEX_HOME: home }, () => { - // `dist/` must exist on disk: the installer refuses to register a - // hook whose script is not built, so simulate a built checkout. - const root = path.dirname( - path.dirname(path.resolve("src/plugin-install.ts")), - ); - const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); - assert.equal( - fs.existsSync(hookScript), - true, - "build before running this test: npm run build", - ); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-faces-")); + const { pluginInstall, pluginRemove, pluginStatusAll } = await import( + "../src/plugin-install.ts" + ); + try { + await withEnv({ CODEX_HOME: home }, () => { + // `dist/` must exist on disk: the installer refuses to register a + // hook whose script is not built, so simulate a built checkout. + const root = path.dirname( + path.dirname(path.resolve("src/plugin-install.ts")), + ); + const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); + assert.equal( + fs.existsSync(hookScript), + true, + "build before running this test: npm run build", + ); - const message = pluginInstall("codex"); - assert.match(message, /^codex: installed/); - assert.match(message, /mcp: installed \[mcp_servers\.bili\]/); - assert.match(message, /model route:/); - assert.match(message, /hook: SessionStart hook added/); - assert.match(message, /skill: ACP skill installed/); + const message = pluginInstall("codex"); + assert.match(message, /^codex: installed/); + assert.match(message, /mcp: installed \[mcp_servers\.bili\]/); + assert.match(message, /model route:/); + assert.match(message, /hook: SessionStart hook added/); + assert.match(message, /skill: ACP skill installed/); - const toml = fs.readFileSync(path.join(home, "config.toml"), "utf8"); - assert.match(toml, /\[mcp_servers\.bili\]\ncommand = /); - // Array-of-tables is required by Codex (`hooks` is a sequence); the - // map form is rejected at load time and breaks the whole host. - assert.match(toml, /\[\[hooks\.SessionStart\]\]\n/); - // ...and the handler must be NESTED in the `hooks = [...]` array. - // Fields set directly on the entry are silently dropped by Codex, so - // this asserts the exact shape its `hooks/list` RPC registers. - assert.match( - toml, - /\[\[hooks\.SessionStart\]\]\nhooks = \[\{ type = "command", command = /, - ); - assert.doesNotMatch(toml, /\[hooks\.SessionStart\]\n/); - assert.doesNotMatch(toml, /\[\[hooks\.SessionStart\]\]\ntype = /); - assert.match(toml, /codex[\\/]bootstrap-hook\.js/); - assert.match( - toml, - /openai_base_url = "http:\/\/127\.0\.0\.1:\d+\/bili\/https:\/\/api\.openai\.com\/v1"/, - ); + const toml = fs.readFileSync(path.join(home, "config.toml"), "utf8"); + assert.match(toml, /\[mcp_servers\.bili\]\ncommand = /); + // Array-of-tables is required by Codex (`hooks` is a sequence); the + // map form is rejected at load time and breaks the whole host. + assert.match(toml, /\[\[hooks\.SessionStart\]\]\n/); + // ...and the handler must be NESTED in the `hooks = [...]` array. + // Fields set directly on the entry are silently dropped by Codex, so + // this asserts the exact shape its `hooks/list` RPC registers. + assert.match( + toml, + /\[\[hooks\.SessionStart\]\]\nhooks = \[\{ type = "command", command = /, + ); + assert.doesNotMatch(toml, /\[hooks\.SessionStart\]\n/); + assert.doesNotMatch(toml, /\[\[hooks\.SessionStart\]\]\ntype = /); + assert.match(toml, /codex[\\/]bootstrap-hook\.js/); + assert.match( + toml, + /openai_base_url = "http:\/\/127\.0\.0\.1:\d+\/bili\/https:\/\/api\.openai\.com\/v1"/, + ); - const skillFile = path.join(home, "skills", "bili", "SKILL.md"); - assert.equal(fs.existsSync(skillFile), true); - assert.match(fs.readFileSync(skillFile, "utf8"), /^---\nname: bili\n/); - assert.match(fs.readFileSync(skillFile, "utf8"), /acp_cache/); + const skillFile = path.join(home, "skills", "bili", "SKILL.md"); + assert.equal(fs.existsSync(skillFile), true); + assert.match(fs.readFileSync(skillFile, "utf8"), /^---\nname: bili\n/); + assert.match(fs.readFileSync(skillFile, "utf8"), /acp_cache/); - // A rerun is a no-op that still reports every face. - const second = pluginInstall("codex"); - assert.match(second, /^codex: already installed/); - assert.match(second, /hook: SessionStart hook already installed/); - assert.match(second, /skill: ACP skill already installed/); + // A rerun is a no-op that still reports every face. + const second = pluginInstall("codex"); + assert.match(second, /^codex: already installed/); + assert.match(second, /hook: SessionStart hook already installed/); + assert.match(second, /skill: ACP skill already installed/); - // Lane status surfaces the faces separately (doctor reads this). - const lane = pluginStatusAll().find((entry) => entry.agent === "codex"); - assert.ok(lane, "codex lane must be reported"); - assert.match(lane!.status, /mcp installed/); - assert.match(lane!.status, /route installed/); - assert.match(lane!.status, /hook installed/); - assert.match(lane!.status, /skill installed/); + // Lane status surfaces the faces separately (doctor reads this). + const lane = pluginStatusAll().find((entry) => entry.agent === "codex"); + assert.ok(lane, "codex lane must be reported"); + assert.match(lane!.status, /mcp installed/); + assert.match(lane!.status, /route installed/); + assert.match(lane!.status, /hook installed/); + assert.match(lane!.status, /skill installed/); - const removed = pluginRemove("codex"); - assert.match(removed, /^codex: removed/); - assert.match(removed, /hook removed/); - const tomlAfter = fs.readFileSync(path.join(home, "config.toml"), "utf8"); - assert.doesNotMatch(tomlAfter, /mcp_servers\.bili/); - assert.doesNotMatch(tomlAfter, /hooks\.SessionStart/); - assert.doesNotMatch(tomlAfter, /bootstrap-hook\.js/); - assert.doesNotMatch(tomlAfter, /openai_base_url/); - assert.equal(fs.existsSync(skillFile), false); - }); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } + const removed = pluginRemove("codex"); + assert.match(removed, /^codex: removed/); + assert.match(removed, /hook removed/); + const tomlAfter = fs.readFileSync(path.join(home, "config.toml"), "utf8"); + assert.doesNotMatch(tomlAfter, /mcp_servers\.bili/); + assert.doesNotMatch(tomlAfter, /hooks\.SessionStart/); + assert.doesNotMatch(tomlAfter, /bootstrap-hook\.js/); + assert.doesNotMatch(tomlAfter, /openai_base_url/); + assert.equal(fs.existsSync(skillFile), false); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } }); // The hook face must never be claimed when it was not written: an unbuilt // checkout installs the MCP + route faces and SAYS the hook was skipped. test("plugin install codex reports a skipped hook when dist is not built", async () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-nohook-")); - const { pluginInstall } = await import("../src/plugin-install.ts"); - try { - await withEnv({ CODEX_HOME: home }, () => { - const root = path.dirname( - path.dirname(path.resolve("src/plugin-install.ts")), - ); - const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); - if (!fs.existsSync(hookScript)) { - const message = pluginInstall("codex"); - assert.match( - message, - /hook: skipped \(dist\/codex\/bootstrap-hook\.js missing\)/, - ); - assert.match(message, /! codex: hook script missing/); - assert.doesNotMatch( - fs.readFileSync(path.join(home, "config.toml"), "utf8"), - /\[hooks\.SessionStart\]/, - ); - } - }); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-nohook-")); + const { pluginInstall } = await import("../src/plugin-install.ts"); + try { + await withEnv({ CODEX_HOME: home }, () => { + const root = path.dirname( + path.dirname(path.resolve("src/plugin-install.ts")), + ); + const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); + if (!fs.existsSync(hookScript)) { + const message = pluginInstall("codex"); + assert.match( + message, + /hook: skipped \(dist\/codex\/bootstrap-hook\.js missing\)/, + ); + assert.match(message, /! codex: hook script missing/); + assert.doesNotMatch( + fs.readFileSync(path.join(home, "config.toml"), "utf8"), + /\[hooks\.SessionStart\]/, + ); + } + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } }); diff --git a/tests/codex-route.test.ts b/tests/codex-route.test.ts index 4aa557e8b7..1121f6b87c 100644 --- a/tests/codex-route.test.ts +++ b/tests/codex-route.test.ts @@ -1,155 +1,155 @@ import assert from "node:assert/strict"; import test from "node:test"; import { - codexRouteValue, - planCodexRoute, - readCodexRoute, - restoreCodexRoute, - type CodexRouteRecord, + codexRouteValue, + planCodexRoute, + readCodexRoute, + restoreCodexRoute, + type CodexRouteRecord, } from "../src/codex-integration/route.ts"; import { - findTableScalar, - findTopLevelScalar, - removeTopLevelScalar, - setTableScalar, - setTopLevelScalar, + findTableScalar, + findTopLevelScalar, + removeTopLevelScalar, + setTableScalar, + setTopLevelScalar, } from "../src/codex-integration/toml-field.ts"; const origin = "http://127.0.0.1:18787"; test("top-level scalar edits preserve tables and unrelated text", () => { - const original = - '# user\nmodel = "gpt-test"\n\n[sandbox]\nmode = "workspace-write"\n'; - const inserted = setTopLevelScalar( - original, - "openai_base_url", - "http://127.0.0.1:18787/bili/https://api.openai.com/v1", - ); - assert.equal( - findTopLevelScalar(inserted, "openai_base_url")?.value, - "http://127.0.0.1:18787/bili/https://api.openai.com/v1", - ); - assert.match(inserted, /\[sandbox\]\nmode = "workspace-write"/); - assert.equal(removeTopLevelScalar(inserted, "openai_base_url"), original); - assert.equal( - findTopLevelScalar( - '[model_providers.openai]\nopenai_base_url = "nested"\n', - "openai_base_url", - ), - undefined, - ); + const original = + '# user\nmodel = "gpt-test"\n\n[sandbox]\nmode = "workspace-write"\n'; + const inserted = setTopLevelScalar( + original, + "openai_base_url", + "http://127.0.0.1:18787/bili/https://api.openai.com/v1", + ); + assert.equal( + findTopLevelScalar(inserted, "openai_base_url")?.value, + "http://127.0.0.1:18787/bili/https://api.openai.com/v1", + ); + assert.match(inserted, /\[sandbox\]\nmode = "workspace-write"/); + assert.equal(removeTopLevelScalar(inserted, "openai_base_url"), original); + assert.equal( + findTopLevelScalar( + '[model_providers.openai]\nopenai_base_url = "nested"\n', + "openai_base_url", + ), + undefined, + ); }); test("route planner owns only a sidecar-recorded value and detects provider shadowing", () => { - const empty = 'model = "gpt-test"\n[sandbox]\nmode = "workspace-write"\n'; - const first = planCodexRoute(empty, { origin }); - assert.equal(first.action, "install"); - assert.equal( - first.value, - codexRouteValue(origin, "https://api.openai.com/v1"), - ); - assert.equal( - planCodexRoute(first.text, { origin }).action, - "conflict", - "a loopback-looking URL without ownership evidence is foreign", - ); - assert.equal( - planCodexRoute(first.text, { origin, ownedValue: first.value }).action, - "keep", - ); - const moved = planCodexRoute(first.text, { - origin: "http://127.0.0.1:18788", - ownedValue: first.value, - }); - assert.equal(moved.action, "refresh"); - assert.equal( - planCodexRoute('openai_base_url = "https://relay.example/v1"\n', { origin }) - .action, - "conflict", - ); - const shadowed = planCodexRoute( - 'model_provider = "relay"\n[model_providers.relay]\nbase_url = "https://relay.example/v1"\n', - { origin }, - ); - assert.equal(shadowed.conflict?.kind, "shadowed-by-provider"); - assert.equal(readCodexRoute(first.text).routed, false); - assert.equal(readCodexRoute(first.text, first.value).routed, true); + const empty = 'model = "gpt-test"\n[sandbox]\nmode = "workspace-write"\n'; + const first = planCodexRoute(empty, { origin }); + assert.equal(first.action, "install"); + assert.equal( + first.value, + codexRouteValue(origin, "https://api.openai.com/v1"), + ); + assert.equal( + planCodexRoute(first.text, { origin }).action, + "conflict", + "a loopback-looking URL without ownership evidence is foreign", + ); + assert.equal( + planCodexRoute(first.text, { origin, ownedValue: first.value }).action, + "keep", + ); + const moved = planCodexRoute(first.text, { + origin: "http://127.0.0.1:18788", + ownedValue: first.value, + }); + assert.equal(moved.action, "refresh"); + assert.equal( + planCodexRoute('openai_base_url = "https://relay.example/v1"\n', { origin }) + .action, + "conflict", + ); + const shadowed = planCodexRoute( + 'model_provider = "relay"\n[model_providers.relay]\nbase_url = "https://relay.example/v1"\n', + { origin }, + ); + assert.equal(shadowed.conflict?.kind, "shadowed-by-provider"); + assert.equal(readCodexRoute(first.text).routed, false); + assert.equal(readCodexRoute(first.text, first.value).routed, true); }); test("uninstall restores only the exact route value from the ownership record", () => { - const original = 'model = "gpt-test"\n[sandbox]\nmode = "workspace-write"\n'; - const plan = planCodexRoute(original, { origin }); - const record: CodexRouteRecord = { - schemaVersion: 1, - writtenValue: plan.value!, - previousValue: null, - upstream: "https://api.openai.com/v1", - }; - assert.deepEqual(restoreCodexRoute(plan.text, record), { - text: original, - restored: true, - stillOwned: true, - }); - const userEdited = plan.text.replace(plan.value!, "https://user.example/v1"); - assert.deepEqual(restoreCodexRoute(userEdited, record), { - text: userEdited, - restored: false, - stillOwned: false, - }); + const original = 'model = "gpt-test"\n[sandbox]\nmode = "workspace-write"\n'; + const plan = planCodexRoute(original, { origin }); + const record: CodexRouteRecord = { + schemaVersion: 1, + writtenValue: plan.value!, + previousValue: null, + upstream: "https://api.openai.com/v1", + }; + assert.deepEqual(restoreCodexRoute(plan.text, record), { + text: original, + restored: true, + stillOwned: true, + }); + const userEdited = plan.text.replace(plan.value!, "https://user.example/v1"); + assert.deepEqual(restoreCodexRoute(userEdited, record), { + text: userEdited, + restored: false, + stillOwned: false, + }); }); test("CC Switch Direct routes only its active provider base_url with reversible ownership", () => { - const original = [ - 'model_provider = "custom"', - 'openai_base_url = "https://root.example/v1"', - "", - "[model_providers.custom]", - 'base_url = "https://api.kourichat.com/v1" # CC Switch Direct', - 'model = "test-model"', - "", - "[sandbox]", - 'mode = "workspace-write"', - "", - ].join("\n"); - const unsupported = planCodexRoute(original, { origin }); - assert.equal(unsupported.action, "conflict"); - const installed = planCodexRoute(original, { origin, ccSwitchMode: "direct" }); - assert.equal(installed.action, "install"); - assert.deepEqual(installed.target, { kind: "provider", provider: "custom" }); - assert.equal( - findTableScalar(installed.text, "model_providers.custom", "base_url")?.value, - codexRouteValue(origin, "https://api.kourichat.com/v1"), - ); - assert.match(installed.text, /openai_base_url = "https:\/\/root\.example\/v1"/); - assert.match(installed.text, /base_url = .* # CC Switch Direct/); - const record: CodexRouteRecord = { - schemaVersion: 1, - writtenValue: installed.value!, - previousValue: "https://api.kourichat.com/v1", - upstream: "https://api.kourichat.com/v1", - target: installed.target, - }; - assert.equal(readCodexRoute(installed.text, record).routed, true); - assert.equal( - planCodexRoute(installed.text, { origin, ccSwitchMode: "direct", ownedRecord: record }).action, - "keep", - ); - assert.equal( - planCodexRoute(original, { origin, ccSwitchMode: "routing" }).action, - "conflict", - ); - assert.deepEqual(restoreCodexRoute(installed.text, record), { - text: original, - restored: true, - stillOwned: true, - }); - const changedBySwitch = original.replace( - 'base_url = "https://api.kourichat.com/v1" # CC Switch Direct', - 'base_url = "https://other-provider.example/v1" # CC Switch Direct', - ); - assert.equal( - planCodexRoute(changedBySwitch, { origin, ccSwitchMode: "direct", ownedRecord: record }).action, - "conflict", - "a CC Switch rewrite after install must not be fought or adopted as a new backup", - ); + const original = [ + 'model_provider = "custom"', + 'openai_base_url = "https://root.example/v1"', + "", + "[model_providers.custom]", + 'base_url = "https://api.kourichat.com/v1" # CC Switch Direct', + 'model = "test-model"', + "", + "[sandbox]", + 'mode = "workspace-write"', + "", + ].join("\n"); + const unsupported = planCodexRoute(original, { origin }); + assert.equal(unsupported.action, "conflict"); + const installed = planCodexRoute(original, { origin, ccSwitchMode: "direct" }); + assert.equal(installed.action, "install"); + assert.deepEqual(installed.target, { kind: "provider", provider: "custom" }); + assert.equal( + findTableScalar(installed.text, "model_providers.custom", "base_url")?.value, + codexRouteValue(origin, "https://api.kourichat.com/v1"), + ); + assert.match(installed.text, /openai_base_url = "https:\/\/root\.example\/v1"/); + assert.match(installed.text, /base_url = .* # CC Switch Direct/); + const record: CodexRouteRecord = { + schemaVersion: 1, + writtenValue: installed.value!, + previousValue: "https://api.kourichat.com/v1", + upstream: "https://api.kourichat.com/v1", + target: installed.target, + }; + assert.equal(readCodexRoute(installed.text, record).routed, true); + assert.equal( + planCodexRoute(installed.text, { origin, ccSwitchMode: "direct", ownedRecord: record }).action, + "keep", + ); + assert.equal( + planCodexRoute(original, { origin, ccSwitchMode: "routing" }).action, + "conflict", + ); + assert.deepEqual(restoreCodexRoute(installed.text, record), { + text: original, + restored: true, + stillOwned: true, + }); + const changedBySwitch = original.replace( + 'base_url = "https://api.kourichat.com/v1" # CC Switch Direct', + 'base_url = "https://other-provider.example/v1" # CC Switch Direct', + ); + assert.equal( + planCodexRoute(changedBySwitch, { origin, ccSwitchMode: "direct", ownedRecord: record }).action, + "conflict", + "a CC Switch rewrite after install must not be fought or adopted as a new backup", + ); }); diff --git a/tests/doctor.test.ts b/tests/doctor.test.ts index f41c6b3289..5761c2242d 100644 --- a/tests/doctor.test.ts +++ b/tests/doctor.test.ts @@ -5,1307 +5,1307 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { - existsSync, - mkdtempSync, - mkdirSync, - readFileSync, - writeFileSync, + existsSync, + mkdtempSync, + mkdirSync, + readFileSync, + writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { - dshBundleShadowWarning, - globalVerdict, - laneVerdict, - renderDoctorReport, - runDoctor, - type DoctorLane, - type DoctorProcess, - type DoctorReport, + dshBundleShadowWarning, + globalVerdict, + laneVerdict, + renderDoctorReport, + runDoctor, + type DoctorLane, + type DoctorProcess, + type DoctorReport, } from "../src/doctor.ts"; import { PLUGIN_AGENTS, inspectLanePresence } from "../src/plugin-install.ts"; import { rmrf } from "./tmp-rm.ts"; function withEnv( - vars: Record, - fn: () => void | Promise, + vars: Record, + fn: () => void | Promise, ): Promise | void { - const effective: Record = { ...vars }; - // Windows os.homedir() resolves through USERPROFILE, not HOME — mirror the - // sandboxed HOME there or real-machine config (~/.dsh, ~/.zcode, …) leaks - // into tests that believe they are running in an empty home. - if ( - process.platform === "win32" && - effective.HOME !== undefined && - effective.USERPROFILE === undefined - ) { - effective.USERPROFILE = effective.HOME; - } - const saved: Record = {}; - for (const [k, v] of Object.entries(effective)) { - saved[k] = process.env[k]; - if (v === undefined) delete process.env[k]; - else process.env[k] = v; - } - const restore = (): void => { - for (const [k, v] of Object.entries(saved)) { - if (v === undefined) delete process.env[k]; - else process.env[k] = v; - } - }; - const r = fn(); - return r instanceof Promise ? r.finally(restore) : (restore(), undefined); + const effective: Record = { ...vars }; + // Windows os.homedir() resolves through USERPROFILE, not HOME — mirror the + // sandboxed HOME there or real-machine config (~/.dsh, ~/.zcode, …) leaks + // into tests that believe they are running in an empty home. + if ( + process.platform === "win32" && + effective.HOME !== undefined && + effective.USERPROFILE === undefined + ) { + effective.USERPROFILE = effective.HOME; + } + const saved: Record = {}; + for (const [k, v] of Object.entries(effective)) { + saved[k] = process.env[k]; + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + const restore = (): void => { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }; + const r = fn(); + return r instanceof Promise ? r.finally(restore) : (restore(), undefined); } function mockFetch( - handler: (url: string) => Response | Promise, + handler: (url: string) => Response | Promise, ): (fn: () => Promise) => Promise { - const original = globalThis.fetch; - return (fn) => { - globalThis.fetch = ((url: unknown) => - Promise.resolve(handler(String(url)))) as unknown as typeof fetch; - return fn().finally(() => { - globalThis.fetch = original; - }); - }; + const original = globalThis.fetch; + return (fn) => { + globalThis.fetch = ((url: unknown) => + Promise.resolve(handler(String(url)))) as unknown as typeof fetch; + return fn().finally(() => { + globalThis.fetch = original; + }); + }; } test("laneVerdict precedence: absent < broken < frozen < stale < ok", () => { - assert.equal( - laneVerdict({ installed: false, targetMissing: true, frozen: true }), - "absent", - ); - assert.equal( - laneVerdict({ - installed: true, - targetMissing: true, - frozen: true, - copyVersion: "0.1.1", - registryVersion: "999.0.0", - }), - "broken", - ); - assert.equal( - laneVerdict({ - installed: true, - targetMissing: false, - frozen: true, - copyVersion: "0.1.1", - registryVersion: "999.0.0", - }), - "frozen", - ); - assert.equal( - laneVerdict({ - installed: true, - targetMissing: false, - frozen: false, - copyVersion: "0.1.1", - registryVersion: "999.0.0", - }), - "stale", - ); - assert.equal( - laneVerdict({ - installed: true, - targetMissing: false, - frozen: false, - copyVersion: "999.0.0", - registryVersion: "0.1.1", - }), - "ok", - ); - // Freshness is only claimed when both versions are resolvable — an - // unreachable registry must never produce a false-stale verdict. - assert.equal( - laneVerdict({ - installed: true, - targetMissing: false, - frozen: false, - copyVersion: "0.1.1", - }), - "ok", - ); + assert.equal( + laneVerdict({ installed: false, targetMissing: true, frozen: true }), + "absent", + ); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: true, + frozen: true, + copyVersion: "0.1.1", + registryVersion: "999.0.0", + }), + "broken", + ); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: true, + copyVersion: "0.1.1", + registryVersion: "999.0.0", + }), + "frozen", + ); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: "0.1.1", + registryVersion: "999.0.0", + }), + "stale", + ); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: "999.0.0", + registryVersion: "0.1.1", + }), + "ok", + ); + // Freshness is only claimed when both versions are resolvable — an + // unreachable registry must never produce a false-stale verdict. + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: "0.1.1", + }), + "ok", + ); }); test("globalVerdict: checkout is frozen regardless of registry; registry newer than disk is stale", () => { - assert.equal( - globalVerdict({ - form: "checkout", - diskVersion: "0.1.143", - registryVersion: "999.0.0", - }), - "frozen", - ); - assert.equal( - globalVerdict({ - form: "npm", - diskVersion: "0.1.143", - registryVersion: "0.1.144", - }), - "stale", - ); - assert.equal( - globalVerdict({ - form: "npm", - diskVersion: "0.1.143", - registryVersion: "0.1.143", - }), - "ok", - ); - assert.equal( - globalVerdict({ form: "host-managed", diskVersion: "0.1.143" }), - "ok", - ); + assert.equal( + globalVerdict({ + form: "checkout", + diskVersion: "0.1.143", + registryVersion: "999.0.0", + }), + "frozen", + ); + assert.equal( + globalVerdict({ + form: "npm", + diskVersion: "0.1.143", + registryVersion: "0.1.144", + }), + "stale", + ); + assert.equal( + globalVerdict({ + form: "npm", + diskVersion: "0.1.143", + registryVersion: "0.1.143", + }), + "ok", + ); + assert.equal( + globalVerdict({ form: "host-managed", diskVersion: "0.1.143" }), + "ok", + ); }); test("#2891: dshBundleShadowWarning fires only when a machine-global copy coexists with a divergent profile copy", () => { - assert.equal( - dshBundleShadowWarning({ - packageName: "billion-context", - globalInstallDir: "/g/bc", - globalDiskVersion: "0.1.135", - profileName: "web", - bundleInstalled: false, - profileCopyVersion: undefined, - }), - undefined, - ); - assert.equal( - dshBundleShadowWarning({ - packageName: "billion-context", - globalInstallDir: undefined, - globalDiskVersion: undefined, - profileName: "web", - bundleInstalled: true, - profileCopyVersion: "0.1.194", - }), - undefined, - ); - assert.equal( - dshBundleShadowWarning({ - packageName: "billion-context", - globalInstallDir: "/g/bc", - globalDiskVersion: "0.1.194", - profileName: "web", - bundleInstalled: true, - profileCopyVersion: "0.1.194", - }), - undefined, - ); - const w = dshBundleShadowWarning({ - packageName: "billion-context", - globalInstallDir: "/g/bc", - globalDiskVersion: "0.1.135", - profileName: "web", - bundleInstalled: true, - profileCopyVersion: "0.1.194", - }); - assert.ok( - typeof w === "string" && - w.includes("v0.1.135") && - w.includes("v0.1.194") && - w.includes("installation-anchor-first") && - w.includes("dsh --profile web --dump-config"), - `expected divergent-version shadow warning, got: ${w}`, - ); - assert.ok( - dshBundleShadowWarning({ - packageName: "billion-context", - globalInstallDir: "/g/bc", - globalDiskVersion: undefined, - profileName: "web", - bundleInstalled: true, - profileCopyVersion: "0.1.194", - }) !== undefined, - ); + assert.equal( + dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: "/g/bc", + globalDiskVersion: "0.1.135", + profileName: "web", + bundleInstalled: false, + profileCopyVersion: undefined, + }), + undefined, + ); + assert.equal( + dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: undefined, + globalDiskVersion: undefined, + profileName: "web", + bundleInstalled: true, + profileCopyVersion: "0.1.194", + }), + undefined, + ); + assert.equal( + dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: "/g/bc", + globalDiskVersion: "0.1.194", + profileName: "web", + bundleInstalled: true, + profileCopyVersion: "0.1.194", + }), + undefined, + ); + const w = dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: "/g/bc", + globalDiskVersion: "0.1.135", + profileName: "web", + bundleInstalled: true, + profileCopyVersion: "0.1.194", + }); + assert.ok( + typeof w === "string" && + w.includes("v0.1.135") && + w.includes("v0.1.194") && + w.includes("installation-anchor-first") && + w.includes("dsh --profile web --dump-config"), + `expected divergent-version shadow warning, got: ${w}`, + ); + assert.ok( + dshBundleShadowWarning({ + packageName: "billion-context", + globalInstallDir: "/g/bc", + globalDiskVersion: undefined, + profileName: "web", + bundleInstalled: true, + profileCopyVersion: "0.1.194", + }) !== undefined, + ); }); test("#2891: a dsh lane carrying the shadow warning renders under its row without touching the verdict", () => { - const text = renderDoctorReport( - syntheticReport({ - lanes: [ - { - agent: "dsh:web", - kind: "host-managed", - installed: true, - detail: "dep spec: ^0.1.194", - copyVersion: "0.1.194", - verdict: "stale", - registryVersion: "0.1.195", - warnings: [ - "shadowed copy: a machine-global billion-context (/g/bc, v0.1.135) coexists with this profile's own copy (v0.1.194)", - ], - }, - ], - }), - ); - assert.match(text, /⚠️ shadowed copy/); - assert.match( - text, - /dsh:web\s+stale \(v0\.1\.194 → v0\.1\.195\)\s+host-managed/, - ); + const text = renderDoctorReport( + syntheticReport({ + lanes: [ + { + agent: "dsh:web", + kind: "host-managed", + installed: true, + detail: "dep spec: ^0.1.194", + copyVersion: "0.1.194", + verdict: "stale", + registryVersion: "0.1.195", + warnings: [ + "shadowed copy: a machine-global billion-context (/g/bc, v0.1.135) coexists with this profile's own copy (v0.1.194)", + ], + }, + ], + }), + ); + assert.match(text, /⚠️ shadowed copy/); + assert.match( + text, + /dsh:web\s+stale \(v0\.1\.194 → v0\.1\.195\)\s+host-managed/, + ); }); test("#2891: runDoctor wires the shadow warning onto the divergent dsh profile lane and stays silent when versions match", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-shadow-run-")); - const runWithFetch = mockFetch( - () => - new Response( - JSON.stringify({ name: "billion-context", version: "999.0.0" }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), - ); - // For runDoctor the running test process IS the machine-global copy: findInstallDir - // walks up from src/update.ts to this repo root (#1628). Pin the profile fixture - // against that real disk version — divergent vs equal — instead of faking a global dir. - const repoPkg = JSON.parse( - readFileSync(new URL("../package.json", import.meta.url), "utf8"), - ) as { version?: unknown }; - const repoVersion = - typeof repoPkg.version === "string" ? repoPkg.version : undefined; - assert.ok(repoVersion, "the repo package.json must carry its own version"); - try { - await runWithFetch(async () => { - const cases: Array<[string, string]> = [ - ["divergent", "999.999.999"], - ["equal", repoVersion], - ]; - for (const [profileName, copyVersion] of cases) { - const home = path.join(base, profileName); - const profileDir = path.join(home, "dsh", "profiles", profileName); - const copyDir = path.join( - profileDir, - "node_modules", - "billion-context", - ); - mkdirSync(copyDir, { recursive: true }); - writeFileSync( - path.join(profileDir, "package.json"), - JSON.stringify({ - dependencies: { "billion-context": "^0.1.140" }, - dsh: { profile: { bundles: ["billion-context"] } }, - }), - ); - writeFileSync( - path.join(copyDir, "package.json"), - JSON.stringify({ name: "billion-context", version: copyVersion }), - ); - await withEnv( - { ...doctorSandboxEnv(home), DSH_HOME: path.join(home, "dsh") }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - const lane = report.lanes.find( - (l) => l.agent === `dsh:${profileName}`, - ); - assert.ok(lane !== undefined, `dsh:${profileName} lane present`); - if (copyVersion === repoVersion) { - assert.equal( - lane?.warnings, - undefined, - `matching versions must not warn: ${JSON.stringify(lane?.warnings)}`, - ); - } else { - assert.ok( - lane?.warnings?.some( - (w) => - w.startsWith("shadowed copy:") && - w.includes(`v${repoVersion}`), - ), - `divergent versions must warn, got: ${JSON.stringify(lane?.warnings)}`, - ); - assert.match(renderDoctorReport(report), /⚠️ shadowed copy/); - } - }, - ); - } - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-shadow-run-")); + const runWithFetch = mockFetch( + () => + new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ); + // For runDoctor the running test process IS the machine-global copy: findInstallDir + // walks up from src/update.ts to this repo root (#1628). Pin the profile fixture + // against that real disk version — divergent vs equal — instead of faking a global dir. + const repoPkg = JSON.parse( + readFileSync(new URL("../package.json", import.meta.url), "utf8"), + ) as { version?: unknown }; + const repoVersion = + typeof repoPkg.version === "string" ? repoPkg.version : undefined; + assert.ok(repoVersion, "the repo package.json must carry its own version"); + try { + await runWithFetch(async () => { + const cases: Array<[string, string]> = [ + ["divergent", "999.999.999"], + ["equal", repoVersion], + ]; + for (const [profileName, copyVersion] of cases) { + const home = path.join(base, profileName); + const profileDir = path.join(home, "dsh", "profiles", profileName); + const copyDir = path.join( + profileDir, + "node_modules", + "billion-context", + ); + mkdirSync(copyDir, { recursive: true }); + writeFileSync( + path.join(profileDir, "package.json"), + JSON.stringify({ + dependencies: { "billion-context": "^0.1.140" }, + dsh: { profile: { bundles: ["billion-context"] } }, + }), + ); + writeFileSync( + path.join(copyDir, "package.json"), + JSON.stringify({ name: "billion-context", version: copyVersion }), + ); + await withEnv( + { ...doctorSandboxEnv(home), DSH_HOME: path.join(home, "dsh") }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const lane = report.lanes.find( + (l) => l.agent === `dsh:${profileName}`, + ); + assert.ok(lane !== undefined, `dsh:${profileName} lane present`); + if (copyVersion === repoVersion) { + assert.equal( + lane?.warnings, + undefined, + `matching versions must not warn: ${JSON.stringify(lane?.warnings)}`, + ); + } else { + assert.ok( + lane?.warnings?.some( + (w) => + w.startsWith("shadowed copy:") && + w.includes(`v${repoVersion}`), + ), + `divergent versions must warn, got: ${JSON.stringify(lane?.warnings)}`, + ); + assert.match(renderDoctorReport(report), /⚠️ shadowed copy/); + } + }, + ); + } + }); + } finally { + rmrf(base); + } }); function syntheticReport(overrides?: { - lanes?: DoctorLane[]; - processes?: DoctorProcess[]; + lanes?: DoctorLane[]; + processes?: DoctorProcess[]; }): DoctorReport { - return { - generatedAt: Date.parse("2026-09-24T00:00:00Z"), - packageName: "billion-context", - global: { - installDir: "/x/node_modules/billion-context", - form: "npm", - diskVersion: "0.1.143", - runningVersion: "0.1.143", - registryVersion: "0.1.143", - updateTag: "latest", - lastCheckTime: Date.parse("2026-09-24T00:00:00Z"), - verdict: "ok", - }, - lanes: overrides?.lanes ?? [], - processes: overrides?.processes ?? [], - codexIntegration: { - state: "unknown", - route: "absent", - proxyHealthy: false, - observedCodexRequest: false, - detail: "not configured", - }, - ccSwitch: { - discovered: false, - mode: "unknown", - compatibility: "unsupported", - evidence: [], - detail: "not detected", - }, - chatGptDesktop: { - state: "待完成/可实现", - credentials: "not-read-not-persisted", - officialLoginChannels: "preserved", - desktopMcp: "separate-from-model-routing", - }, - }; + return { + generatedAt: Date.parse("2026-09-24T00:00:00Z"), + packageName: "billion-context", + global: { + installDir: "/x/node_modules/billion-context", + form: "npm", + diskVersion: "0.1.143", + runningVersion: "0.1.143", + registryVersion: "0.1.143", + updateTag: "latest", + lastCheckTime: Date.parse("2026-09-24T00:00:00Z"), + verdict: "ok", + }, + lanes: overrides?.lanes ?? [], + processes: overrides?.processes ?? [], + codexIntegration: { + state: "unknown", + route: "absent", + proxyHealthy: false, + observedCodexRequest: false, + detail: "not configured", + }, + ccSwitch: { + discovered: false, + mode: "unknown", + compatibility: "unsupported", + evidence: [], + detail: "not detected", + }, + chatGptDesktop: { + state: "待完成/可实现", + credentials: "not-read-not-persisted", + officialLoginChannels: "preserved", + desktopMcp: "separate-from-model-routing", + }, + }; } test("renderDoctorReport: verdict lines carry the issue-specified formats", () => { - const text = renderDoctorReport( - syntheticReport({ - lanes: [ - { - agent: "omp", - kind: "reference", - installed: true, - detail: "/old/dist/agent/omp-native.js", - channel: "the global bili install (entry points at it)", - verdict: "stale", - copyVersion: "0.1.1", - registryVersion: "0.1.2", - }, - { - agent: "dsh:dev", - kind: "host-managed", - installed: true, - detail: "dep spec: link:/local/x (local pin — dev lane, manual)", - verdict: "frozen", - reason: - "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)", - }, - { - agent: "pi", - kind: "host-managed", - installed: false, - detail: "not installed", - verdict: "absent", - }, - ], - processes: [ - { - instanceId: "abc", - pid: 4242, - port: 8787, - origin: "http://127.0.0.1:8787", - startedAt: Date.parse("2026-09-24T00:00:00Z"), - alive: true, - runningFrom: "/x/node_modules/billion-context/dist/index.js", - }, - { - instanceId: "def", - pid: 5555, - port: 8788, - origin: "http://127.0.0.1:8788", - startedAt: Date.parse("2026-09-24T00:00:00Z"), - alive: false, - }, - ], - }), - ); - assert.match(text, /stale \(v0\.1\.1 → v0\.1\.2\)/); - assert.match(text, /frozen/); - assert.match(text, /zombie \(process gone, marker left behind\)/); - assert.match( - text, - /summary: 0 ok, 1 stale, 1 frozen, 0 broken, 1 absent; processes: 1 live, 1 zombie/, - ); - assert.match( - text, - /updates via: the global bili install \(entry points at it\)/, - ); + const text = renderDoctorReport( + syntheticReport({ + lanes: [ + { + agent: "omp", + kind: "reference", + installed: true, + detail: "/old/dist/agent/omp-native.js", + channel: "the global bili install (entry points at it)", + verdict: "stale", + copyVersion: "0.1.1", + registryVersion: "0.1.2", + }, + { + agent: "dsh:dev", + kind: "host-managed", + installed: true, + detail: "dep spec: link:/local/x (local pin — dev lane, manual)", + verdict: "frozen", + reason: + "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)", + }, + { + agent: "pi", + kind: "host-managed", + installed: false, + detail: "not installed", + verdict: "absent", + }, + ], + processes: [ + { + instanceId: "abc", + pid: 4242, + port: 8787, + origin: "http://127.0.0.1:8787", + startedAt: Date.parse("2026-09-24T00:00:00Z"), + alive: true, + runningFrom: "/x/node_modules/billion-context/dist/index.js", + }, + { + instanceId: "def", + pid: 5555, + port: 8788, + origin: "http://127.0.0.1:8788", + startedAt: Date.parse("2026-09-24T00:00:00Z"), + alive: false, + }, + ], + }), + ); + assert.match(text, /stale \(v0\.1\.1 → v0\.1\.2\)/); + assert.match(text, /frozen/); + assert.match(text, /zombie \(process gone, marker left behind\)/); + assert.match( + text, + /summary: 0 ok, 1 stale, 1 frozen, 0 broken, 1 absent; processes: 1 live, 1 zombie/, + ); + assert.match( + text, + /updates via: the global bili install \(entry points at it\)/, + ); }); test("inspectLanePresence omp: dead entry is a broken lane, live entry resolves its copy version", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-omp-")); - try { - const ompHome = path.join(base, "omp"); - const deadEntry = path.join(base, "dead", "dist", "agent", "omp-native.js"); - const liveRoot = path.join(base, "fakepkg"); - const liveEntry = path.join(liveRoot, "dist", "agent", "omp-native.js"); - mkdirSync(path.join(ompHome), { recursive: true }); - mkdirSync(path.dirname(liveEntry), { recursive: true }); - writeFileSync(liveEntry, "export {};\n"); - writeFileSync( - path.join(liveRoot, "package.json"), - JSON.stringify({ name: "billion-context", version: "0.1.143" }), - ); - const cfg = (entries: string[]): string => - ["extensions:", ...entries.map((e) => ` - ${e}`)].join("\n") + "\n"; - writeFileSync(path.join(ompHome, "config.yml"), cfg([deadEntry])); - withEnv({ PI_CODING_AGENT_DIR: ompHome }, () => { - const dead = inspectLanePresence("omp"); - assert.equal(dead.installed, true); - assert.deepEqual(dead.targets, [deadEntry]); - assert.equal( - laneVerdict({ - installed: dead.installed, - targetMissing: !existsSync(deadEntry), - frozen: false, - copyVersion: dead.copyVersion, - registryVersion: "999.0.0", - }), - "broken", - ); - }); - writeFileSync(path.join(ompHome, "config.yml"), cfg([liveEntry])); - withEnv({ PI_CODING_AGENT_DIR: ompHome }, () => { - const live = inspectLanePresence("omp"); - assert.equal(live.installed, true); - assert.equal(live.copyVersion, "0.1.143"); - assert.ok(live.targets.every((t) => existsSync(t))); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-omp-")); + try { + const ompHome = path.join(base, "omp"); + const deadEntry = path.join(base, "dead", "dist", "agent", "omp-native.js"); + const liveRoot = path.join(base, "fakepkg"); + const liveEntry = path.join(liveRoot, "dist", "agent", "omp-native.js"); + mkdirSync(path.join(ompHome), { recursive: true }); + mkdirSync(path.dirname(liveEntry), { recursive: true }); + writeFileSync(liveEntry, "export {};\n"); + writeFileSync( + path.join(liveRoot, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.143" }), + ); + const cfg = (entries: string[]): string => + ["extensions:", ...entries.map((e) => ` - ${e}`)].join("\n") + "\n"; + writeFileSync(path.join(ompHome, "config.yml"), cfg([deadEntry])); + withEnv({ PI_CODING_AGENT_DIR: ompHome }, () => { + const dead = inspectLanePresence("omp"); + assert.equal(dead.installed, true); + assert.deepEqual(dead.targets, [deadEntry]); + assert.equal( + laneVerdict({ + installed: dead.installed, + targetMissing: !existsSync(deadEntry), + frozen: false, + copyVersion: dead.copyVersion, + registryVersion: "999.0.0", + }), + "broken", + ); + }); + writeFileSync(path.join(ompHome, "config.yml"), cfg([liveEntry])); + withEnv({ PI_CODING_AGENT_DIR: ompHome }, () => { + const live = inspectLanePresence("omp"); + assert.equal(live.installed, true); + assert.equal(live.copyVersion, "0.1.143"); + assert.ok(live.targets.every((t) => existsSync(t))); + }); + } finally { + rmrf(base); + } }); test("inspectLanePresence dsh: local pin flags a frozen dev lane, registry pin resolves bundle version", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-dsh-")); - try { - const dshHome = path.join(base, "dsh"); - const devDir = path.join(dshHome, "profiles", "dev"); - const mainDir = path.join(dshHome, "profiles", "main"); - const mainCopy = path.join(mainDir, "node_modules", "billion-context"); - mkdirSync(devDir, { recursive: true }); - mkdirSync(mainCopy, { recursive: true }); - writeFileSync( - path.join(devDir, "package.json"), - JSON.stringify({ - dependencies: { "billion-context": "link:/local/x" }, - dsh: { profile: { bundles: ["billion-context"] } }, - }), - ); - writeFileSync( - path.join(mainDir, "package.json"), - JSON.stringify({ - dependencies: { "billion-context": "^0.1.140" }, - dsh: { profile: { bundles: ["billion-context"] } }, - }), - ); - writeFileSync( - path.join(mainCopy, "package.json"), - JSON.stringify({ name: "billion-context", version: "0.1.140" }), - ); - withEnv({ DSH_HOME: dshHome }, () => { - const p = inspectLanePresence("dsh"); - assert.equal(p.installed, true); - assert.equal(p.form, "local-path"); - const dev = p.profiles?.find((x) => x.name === "dev"); - assert.equal(dev?.pinned, true); - assert.equal(dev?.spec, "link:/local/x"); - assert.equal( - laneVerdict({ - installed: true, - targetMissing: false, - frozen: dev?.pinned === true, - copyVersion: dev?.copyVersion, - registryVersion: "999.0.0", - }), - "frozen", - ); - const main = p.profiles?.find((x) => x.name === "main"); - assert.equal(main?.pinned, false); - assert.equal(main?.copyVersion, "0.1.140"); - assert.equal( - laneVerdict({ - installed: true, - targetMissing: false, - frozen: false, - copyVersion: main?.copyVersion, - registryVersion: "999.0.0", - }), - "stale", - ); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-dsh-")); + try { + const dshHome = path.join(base, "dsh"); + const devDir = path.join(dshHome, "profiles", "dev"); + const mainDir = path.join(dshHome, "profiles", "main"); + const mainCopy = path.join(mainDir, "node_modules", "billion-context"); + mkdirSync(devDir, { recursive: true }); + mkdirSync(mainCopy, { recursive: true }); + writeFileSync( + path.join(devDir, "package.json"), + JSON.stringify({ + dependencies: { "billion-context": "link:/local/x" }, + dsh: { profile: { bundles: ["billion-context"] } }, + }), + ); + writeFileSync( + path.join(mainDir, "package.json"), + JSON.stringify({ + dependencies: { "billion-context": "^0.1.140" }, + dsh: { profile: { bundles: ["billion-context"] } }, + }), + ); + writeFileSync( + path.join(mainCopy, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.140" }), + ); + withEnv({ DSH_HOME: dshHome }, () => { + const p = inspectLanePresence("dsh"); + assert.equal(p.installed, true); + assert.equal(p.form, "local-path"); + const dev = p.profiles?.find((x) => x.name === "dev"); + assert.equal(dev?.pinned, true); + assert.equal(dev?.spec, "link:/local/x"); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: dev?.pinned === true, + copyVersion: dev?.copyVersion, + registryVersion: "999.0.0", + }), + "frozen", + ); + const main = p.profiles?.find((x) => x.name === "main"); + assert.equal(main?.pinned, false); + assert.equal(main?.copyVersion, "0.1.140"); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: main?.copyVersion, + registryVersion: "999.0.0", + }), + "stale", + ); + }); + } finally { + rmrf(base); + } }); test("#2850: inspectLanePresence pi: npm lane resolves the real copy root for every spec form", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-npm-")); - try { - const piHome = path.join(base, "pi"); - const realCopy = path.join( - piHome, - "npm", - "node_modules", - "billion-context", - ); - mkdirSync(realCopy, { recursive: true }); - writeFileSync( - path.join(realCopy, "package.json"), - JSON.stringify({ name: "billion-context", version: "0.1.143" }), - ); - // Decoy at the OLD buggy probe path (/agent/npm/...) — must never be read. - const decoy = path.join( - piHome, - "agent", - "npm", - "node_modules", - "billion-context", - ); - mkdirSync(decoy, { recursive: true }); - writeFileSync( - path.join(decoy, "package.json"), - JSON.stringify({ name: "billion-context", version: "9.9.9" }), - ); - mkdirSync(piHome, { recursive: true }); - const settings = (packages: string[]): void => - writeFileSync( - path.join(piHome, "settings.json"), - JSON.stringify({ packages }), - ); - for (const spec of [ - "npm:billion-context", - "npm:billion-context@0.1.150", - "npm:billion-context@latest", - ]) { - settings([spec]); - withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { - const p = inspectLanePresence("pi"); - assert.equal(p.installed, true); - assert.equal(p.form, "npm"); - assert.deepEqual( - p.targets, - [realCopy], - `${spec}: target must be the real pi materialization dir`, - ); - assert.equal( - p.copyVersion, - "0.1.143", - `${spec}: the decoy at the old wrong path must not leak`, - ); - }); - } - // Copy not materialized yet → empty targets (the doctor hint applies), still installed/npm. - settings(["npm:billion-context"]); - rmrf(realCopy); - withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { - const p = inspectLanePresence("pi"); - assert.equal(p.installed, true); - assert.equal(p.form, "npm"); - assert.deepEqual(p.targets, []); - assert.equal(p.copyVersion, undefined); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-npm-")); + try { + const piHome = path.join(base, "pi"); + const realCopy = path.join( + piHome, + "npm", + "node_modules", + "billion-context", + ); + mkdirSync(realCopy, { recursive: true }); + writeFileSync( + path.join(realCopy, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.143" }), + ); + // Decoy at the OLD buggy probe path (/agent/npm/...) — must never be read. + const decoy = path.join( + piHome, + "agent", + "npm", + "node_modules", + "billion-context", + ); + mkdirSync(decoy, { recursive: true }); + writeFileSync( + path.join(decoy, "package.json"), + JSON.stringify({ name: "billion-context", version: "9.9.9" }), + ); + mkdirSync(piHome, { recursive: true }); + const settings = (packages: string[]): void => + writeFileSync( + path.join(piHome, "settings.json"), + JSON.stringify({ packages }), + ); + for (const spec of [ + "npm:billion-context", + "npm:billion-context@0.1.150", + "npm:billion-context@latest", + ]) { + settings([spec]); + withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { + const p = inspectLanePresence("pi"); + assert.equal(p.installed, true); + assert.equal(p.form, "npm"); + assert.deepEqual( + p.targets, + [realCopy], + `${spec}: target must be the real pi materialization dir`, + ); + assert.equal( + p.copyVersion, + "0.1.143", + `${spec}: the decoy at the old wrong path must not leak`, + ); + }); + } + // Copy not materialized yet → empty targets (the doctor hint applies), still installed/npm. + settings(["npm:billion-context"]); + rmrf(realCopy); + withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { + const p = inspectLanePresence("pi"); + assert.equal(p.installed, true); + assert.equal(p.form, "npm"); + assert.deepEqual(p.targets, []); + assert.equal(p.copyVersion, undefined); + }); + } finally { + rmrf(base); + } }); test("#2850: inspectLanePresence pi: absolute-path entry keeps local-path semantics; corrupt settings stays a probe failure", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-abs-")); - try { - const piHome = path.join(base, "pi"); - // A real dev checkout is named billion-context — the recognition regex - // keys off that basename (or a node_modules/billion-context segment). - const absRoot = path.join(base, "billion-context"); - mkdirSync(absRoot, { recursive: true }); - mkdirSync(piHome, { recursive: true }); - writeFileSync( - path.join(absRoot, "package.json"), - JSON.stringify({ name: "billion-context", version: "0.1.142" }), - ); - writeFileSync( - path.join(piHome, "settings.json"), - JSON.stringify({ packages: [absRoot] }), - ); - withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { - const p = inspectLanePresence("pi"); - assert.equal(p.installed, true); - assert.equal(p.form, "local-path"); - assert.deepEqual(p.targets, [absRoot]); - assert.equal(p.copyVersion, "0.1.142"); - }); - // Corrupt settings: single-source probe propagates the parse error (no false absent). - writeFileSync(path.join(piHome, "settings.json"), "{ not json"); - withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { - assert.throws(() => inspectLanePresence("pi"), /not valid JSON/); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-abs-")); + try { + const piHome = path.join(base, "pi"); + // A real dev checkout is named billion-context — the recognition regex + // keys off that basename (or a node_modules/billion-context segment). + const absRoot = path.join(base, "billion-context"); + mkdirSync(absRoot, { recursive: true }); + mkdirSync(piHome, { recursive: true }); + writeFileSync( + path.join(absRoot, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.142" }), + ); + writeFileSync( + path.join(piHome, "settings.json"), + JSON.stringify({ packages: [absRoot] }), + ); + withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { + const p = inspectLanePresence("pi"); + assert.equal(p.installed, true); + assert.equal(p.form, "local-path"); + assert.deepEqual(p.targets, [absRoot]); + assert.equal(p.copyVersion, "0.1.142"); + }); + // Corrupt settings: single-source probe propagates the parse error (no false absent). + writeFileSync(path.join(piHome, "settings.json"), "{ not json"); + withEnv({ PI_CODING_AGENT_DIR: piHome }, () => { + assert.throws(() => inspectLanePresence("pi"), /not valid JSON/); + }); + } finally { + rmrf(base); + } }); test("#2850: runDoctor pi npm lane verdicts off the real copy and drops the false materialize hint", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-run-")); - const piHome = path.join(base, "pi"); - const realCopy = path.join(piHome, "npm", "node_modules", "billion-context"); - mkdirSync(realCopy, { recursive: true }); - writeFileSync( - path.join(realCopy, "package.json"), - JSON.stringify({ name: "billion-context", version: "0.1.143" }), - ); - writeFileSync( - path.join(piHome, "settings.json"), - JSON.stringify({ packages: ["npm:billion-context"] }), - ); - const registryDoc = (version: string): Response => - new Response(JSON.stringify({ name: "billion-context", version }), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); - try { - await mockFetch(() => registryDoc("999.0.0"))(async () => { - await withEnv( - { ...doctorSandboxEnv(base), PI_CODING_AGENT_DIR: piHome }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - const pi = report.lanes.find((l) => l.agent === "pi"); - assert.equal(pi?.installed, true); - assert.equal(pi?.copyVersion, "0.1.143"); - assert.equal(pi?.verdict, "stale"); - assert.match( - renderDoctorReport(report), - /stale \(v0\.1\.143 → v999\.0\.0\)/, - ); - assert.ok( - !(pi?.detail ?? "").includes("materializes"), - `copy exists — no false hint: ${pi?.detail}`, - ); - }, - ); - }); - // Copy genuinely absent → the pre-materialization hint applies again. - rmrf(realCopy); - await mockFetch(() => registryDoc("999.0.0"))(async () => { - await withEnv( - { ...doctorSandboxEnv(base), PI_CODING_AGENT_DIR: piHome }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - const pi = report.lanes.find((l) => l.agent === "pi"); - assert.equal(pi?.installed, true); - assert.match( - pi?.detail ?? "", - /pi materializes the npm copy on next startup/, - ); - }, - ); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-pi-run-")); + const piHome = path.join(base, "pi"); + const realCopy = path.join(piHome, "npm", "node_modules", "billion-context"); + mkdirSync(realCopy, { recursive: true }); + writeFileSync( + path.join(realCopy, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.143" }), + ); + writeFileSync( + path.join(piHome, "settings.json"), + JSON.stringify({ packages: ["npm:billion-context"] }), + ); + const registryDoc = (version: string): Response => + new Response(JSON.stringify({ name: "billion-context", version }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + try { + await mockFetch(() => registryDoc("999.0.0"))(async () => { + await withEnv( + { ...doctorSandboxEnv(base), PI_CODING_AGENT_DIR: piHome }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const pi = report.lanes.find((l) => l.agent === "pi"); + assert.equal(pi?.installed, true); + assert.equal(pi?.copyVersion, "0.1.143"); + assert.equal(pi?.verdict, "stale"); + assert.match( + renderDoctorReport(report), + /stale \(v0\.1\.143 → v999\.0\.0\)/, + ); + assert.ok( + !(pi?.detail ?? "").includes("materializes"), + `copy exists — no false hint: ${pi?.detail}`, + ); + }, + ); + }); + // Copy genuinely absent → the pre-materialization hint applies again. + rmrf(realCopy); + await mockFetch(() => registryDoc("999.0.0"))(async () => { + await withEnv( + { ...doctorSandboxEnv(base), PI_CODING_AGENT_DIR: piHome }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const pi = report.lanes.find((l) => l.agent === "pi"); + assert.equal(pi?.installed, true); + assert.match( + pi?.detail ?? "", + /pi materializes the npm copy on next startup/, + ); + }, + ); + }); + } finally { + rmrf(base); + } }); test("inspectLanePresence hermes: baked plugin.yaml version is the freshness signal", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-hermes-")); - try { - const hermesHome = path.join(base, "hermes"); - const pluginDir = path.join(hermesHome, "plugins", "billion-context"); - const proxyScript = path.join(base, "global", "dist", "index.js"); - mkdirSync(pluginDir, { recursive: true }); - writeFileSync(path.join(pluginDir, "__init__.py"), ""); - writeFileSync( - path.join(pluginDir, "plugin.yaml"), - "id: billion-context\nversion: 0.1.100\nname: Billion Context\n", - ); - writeFileSync( - path.join(pluginDir, "bili.json"), - JSON.stringify({ proxyScript, nodePath: "node" }), - ); - withEnv({ HERMES_HOME: hermesHome }, () => { - const p = inspectLanePresence("hermes"); - assert.equal(p.installed, true); - assert.equal(p.form, "local-path"); - assert.equal(p.copyVersion, "0.1.100"); - assert.deepEqual(p.targets, [proxyScript]); - assert.equal( - laneVerdict({ - installed: true, - targetMissing: false, - frozen: false, - copyVersion: p.copyVersion, - registryVersion: "999.0.0", - }), - "stale", - ); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-hermes-")); + try { + const hermesHome = path.join(base, "hermes"); + const pluginDir = path.join(hermesHome, "plugins", "billion-context"); + const proxyScript = path.join(base, "global", "dist", "index.js"); + mkdirSync(pluginDir, { recursive: true }); + writeFileSync(path.join(pluginDir, "__init__.py"), ""); + writeFileSync( + path.join(pluginDir, "plugin.yaml"), + "id: billion-context\nversion: 0.1.100\nname: Billion Context\n", + ); + writeFileSync( + path.join(pluginDir, "bili.json"), + JSON.stringify({ proxyScript, nodePath: "node" }), + ); + withEnv({ HERMES_HOME: hermesHome }, () => { + const p = inspectLanePresence("hermes"); + assert.equal(p.installed, true); + assert.equal(p.form, "local-path"); + assert.equal(p.copyVersion, "0.1.100"); + assert.deepEqual(p.targets, [proxyScript]); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: p.copyVersion, + registryVersion: "999.0.0", + }), + "stale", + ); + }); + } finally { + rmrf(base); + } }); test("inspectLanePresence: corrupt single-source config is a probe failure, not a false absent", () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-corrupt-")); - try { - const ocDir = path.join(base, "opencode"); - mkdirSync(ocDir, { recursive: true }); - writeFileSync(path.join(ocDir, "opencode.json"), "{ not json"); - withEnv({ OPENCODE_CONFIG: path.join(ocDir, "opencode.json") }, () => { - assert.throws(() => inspectLanePresence("opencode"), /not valid JSON/); - }); - // zcode resolves its config via os.homedir(), which follows $HOME on - // POSIX but not on Windows — sandboxable only where $HOME rules. - if (process.platform !== "win32") { - const zcDir = path.join(base, "home", ".zcode", "cli"); - mkdirSync(zcDir, { recursive: true }); - writeFileSync(path.join(zcDir, "config.json"), "{ not json"); - withEnv({ HOME: path.join(base, "home") }, () => { - assert.throws(() => inspectLanePresence("zcode"), /not valid JSON/); - }); - } - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-corrupt-")); + try { + const ocDir = path.join(base, "opencode"); + mkdirSync(ocDir, { recursive: true }); + writeFileSync(path.join(ocDir, "opencode.json"), "{ not json"); + withEnv({ OPENCODE_CONFIG: path.join(ocDir, "opencode.json") }, () => { + assert.throws(() => inspectLanePresence("opencode"), /not valid JSON/); + }); + // zcode resolves its config via os.homedir(), which follows $HOME on + // POSIX but not on Windows — sandboxable only where $HOME rules. + if (process.platform !== "win32") { + const zcDir = path.join(base, "home", ".zcode", "cli"); + mkdirSync(zcDir, { recursive: true }); + writeFileSync(path.join(zcDir, "config.json"), "{ not json"); + withEnv({ HOME: path.join(base, "home") }, () => { + assert.throws(() => inspectLanePresence("zcode"), /not valid JSON/); + }); + } + } finally { + rmrf(base); + } }); test("runDoctor: corrupt lane config surfaces as a broken probe row, not absent", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-corrupt-run-")); - const ocCfg = path.join(base, "opencode.json"); - writeFileSync(ocCfg, "{ not json"); - const runWithFetch = mockFetch( - () => - new Response( - JSON.stringify({ name: "billion-context", version: "999.0.0" }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), - ); - try { - await runWithFetch(async () => { - await withEnv( - { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: ocCfg, - }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - const oc = report.lanes.find((l) => l.agent === "opencode"); - assert.equal(oc?.verdict, "broken"); - assert.match(oc?.detail ?? "", /probe failed: .*not valid JSON/); - for (const l of report.lanes.filter((x) => x.agent !== "opencode")) { - assert.equal( - l.verdict, - "absent", - `${l.agent} should be absent in an empty sandbox`, - ); - } - assert.match(renderDoctorReport(report), /probe failed/); - }, - ); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-corrupt-run-")); + const ocCfg = path.join(base, "opencode.json"); + writeFileSync(ocCfg, "{ not json"); + const runWithFetch = mockFetch( + () => + new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ); + try { + await runWithFetch(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: ocCfg, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const oc = report.lanes.find((l) => l.agent === "opencode"); + assert.equal(oc?.verdict, "broken"); + assert.match(oc?.detail ?? "", /probe failed: .*not valid JSON/); + for (const l of report.lanes.filter((x) => x.agent !== "opencode")) { + assert.equal( + l.verdict, + "absent", + `${l.agent} should be absent in an empty sandbox`, + ); + } + assert.match(renderDoctorReport(report), /probe failed/); + }, + ); + }); + } finally { + rmrf(base); + } }); test("#2199: opencode npm lane surfaces the cache copy path + disk version and goes stale only when the registry leads", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-oc-cache-")); - const ocCfg = path.join(base, "opencode.json"); - writeFileSync(ocCfg, JSON.stringify({ plugin: ["billion-context"] })); - const cacheRoot = path.join( - base, - "xdg-cache", - "opencode", - "npm", - "billion-context@latest", - "1760000000000", - "node_modules", - "billion-context", - ); - mkdirSync(cacheRoot, { recursive: true }); - writeFileSync( - path.join(cacheRoot, "package.json"), - JSON.stringify({ name: "billion-context", version: "0.1.143" }), - ); - const registryDoc = (version: string): Response => - new Response(JSON.stringify({ name: "billion-context", version }), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); - try { - await mockFetch(() => registryDoc("999.0.0"))(async () => { - await withEnv( - { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: ocCfg, - }, - async () => { - const presence = inspectLanePresence("opencode"); - assert.equal(presence.form, "npm"); - assert.equal(presence.targets[0], cacheRoot); - assert.equal(presence.copyVersion, "0.1.143"); - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - const oc = report.lanes.find((l) => l.agent === "opencode"); - assert.equal(oc?.copyVersion, "0.1.143"); - assert.equal(oc?.verdict, "stale"); - assert.match(oc?.detail ?? "", /cache copy \(/); - assert.ok( - (oc?.detail ?? "").includes(presence.targets[0]!), - `detail must carry the actual load path: ${oc?.detail}`, - ); - assert.match(oc?.detail ?? "", /reload\/restart OpenCode/); - assert.match( - renderDoctorReport(report), - /stale \(v0\.1\.143 → v999\.0\.0\)/, - ); - }, - ); - }); - // Same layout, registry at the same version as disk — must stay ok (no false-stale). - await mockFetch(() => registryDoc("0.1.143"))(async () => { - await withEnv( - { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: ocCfg, - }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - const oc = report.lanes.find((l) => l.agent === "opencode"); - assert.equal(oc?.verdict, "ok"); - }, - ); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-oc-cache-")); + const ocCfg = path.join(base, "opencode.json"); + writeFileSync(ocCfg, JSON.stringify({ plugin: ["billion-context"] })); + const cacheRoot = path.join( + base, + "xdg-cache", + "opencode", + "npm", + "billion-context@latest", + "1760000000000", + "node_modules", + "billion-context", + ); + mkdirSync(cacheRoot, { recursive: true }); + writeFileSync( + path.join(cacheRoot, "package.json"), + JSON.stringify({ name: "billion-context", version: "0.1.143" }), + ); + const registryDoc = (version: string): Response => + new Response(JSON.stringify({ name: "billion-context", version }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + try { + await mockFetch(() => registryDoc("999.0.0"))(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: ocCfg, + }, + async () => { + const presence = inspectLanePresence("opencode"); + assert.equal(presence.form, "npm"); + assert.equal(presence.targets[0], cacheRoot); + assert.equal(presence.copyVersion, "0.1.143"); + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const oc = report.lanes.find((l) => l.agent === "opencode"); + assert.equal(oc?.copyVersion, "0.1.143"); + assert.equal(oc?.verdict, "stale"); + assert.match(oc?.detail ?? "", /cache copy \(/); + assert.ok( + (oc?.detail ?? "").includes(presence.targets[0]!), + `detail must carry the actual load path: ${oc?.detail}`, + ); + assert.match(oc?.detail ?? "", /reload\/restart OpenCode/); + assert.match( + renderDoctorReport(report), + /stale \(v0\.1\.143 → v999\.0\.0\)/, + ); + }, + ); + }); + // Same layout, registry at the same version as disk — must stay ok (no false-stale). + await mockFetch(() => registryDoc("0.1.143"))(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: ocCfg, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const oc = report.lanes.find((l) => l.agent === "opencode"); + assert.equal(oc?.verdict, "ok"); + }, + ); + }); + } finally { + rmrf(base); + } }); test("renderDoctorReport: lane warnings render under the lane row without touching the verdict", () => { - const text = renderDoctorReport( - syntheticReport({ - lanes: [ - { - agent: "claude", - kind: "reference", - installed: true, - detail: "installed", - verdict: "ok", - warnings: [ - "Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL", - ], - }, - { - agent: "pi", - kind: "host-managed", - installed: false, - detail: "not installed", - verdict: "absent", - }, - ], - }), - ); - assert.match(text, /⚠️ Claude Desktop detected/); - assert.match(text, /claude\s+ok\s+reference/); + const text = renderDoctorReport( + syntheticReport({ + lanes: [ + { + agent: "claude", + kind: "reference", + installed: true, + detail: "installed", + verdict: "ok", + warnings: [ + "Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL", + ], + }, + { + agent: "pi", + kind: "host-managed", + installed: false, + detail: "not installed", + verdict: "absent", + }, + ], + }), + ); + assert.match(text, /⚠️ Claude Desktop detected/); + assert.match(text, /claude\s+ok\s+reference/); }); test("#2290: claude lane surfaces the last hook-detected routing bypass from the state marker", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-claude-warn-")); - const cfgDir = path.join(base, "claude-cfg"); - mkdirSync(cfgDir, { recursive: true }); - writeFileSync( - path.join(cfgDir, "settings.json"), - JSON.stringify({ - env: { - ANTHROPIC_BASE_URL: - "http://127.0.0.1:48787/bili/https://api.anthropic.com", - DISABLE_AUTO_COMPACT: "1", - }, - }), - ); - const stateLane = path.join(base, "xdg-state", "billion-context"); - mkdirSync(stateLane, { recursive: true }); - writeFileSync( - path.join(stateLane, "claude-routing-warning.json"), - JSON.stringify({ - at: Date.parse("2026-10-07T00:00:00Z"), - reasons: [ - "CLAUDE_CODE_ENTRYPOINT=claude-desktop — this host sets its own ANTHROPIC_BASE_URL", - ], - }), - ); - try { - await mockFetch( - () => - new Response( - JSON.stringify({ name: "billion-context", version: "999.0.0" }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), - )(async () => { - await withEnv( - { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: cfgDir, - OPENCODE_CONFIG: undefined, - }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - const cl = report.lanes.find((l) => l.agent === "claude"); - assert.equal(cl?.installed, true); - assert.ok( - cl?.warnings?.some( - (w) => - w.includes("routing bypass") && - w.includes("CLAUDE_CODE_ENTRYPOINT=claude-desktop"), - ), - `warnings: ${JSON.stringify(cl?.warnings)}`, - ); - assert.match(renderDoctorReport(report), /⚠️ .*routing bypass/); - }, - ); - }); - // Corrupt marker: surfaced as nothing, never as a probe failure. - writeFileSync( - path.join(stateLane, "claude-routing-warning.json"), - "{ not json", - ); - await mockFetch( - () => - new Response( - JSON.stringify({ name: "billion-context", version: "999.0.0" }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), - )(async () => { - await withEnv( - { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: cfgDir, - OPENCODE_CONFIG: undefined, - }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - const cl = report.lanes.find((l) => l.agent === "claude"); - assert.equal(cl?.verdict, "ok"); - assert.ok( - !cl?.warnings?.some((w) => w.includes("routing bypass")), - `corrupt marker must not surface: ${JSON.stringify(cl?.warnings)}`, - ); - }, - ); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-claude-warn-")); + const cfgDir = path.join(base, "claude-cfg"); + mkdirSync(cfgDir, { recursive: true }); + writeFileSync( + path.join(cfgDir, "settings.json"), + JSON.stringify({ + env: { + ANTHROPIC_BASE_URL: + "http://127.0.0.1:48787/bili/https://api.anthropic.com", + DISABLE_AUTO_COMPACT: "1", + }, + }), + ); + const stateLane = path.join(base, "xdg-state", "billion-context"); + mkdirSync(stateLane, { recursive: true }); + writeFileSync( + path.join(stateLane, "claude-routing-warning.json"), + JSON.stringify({ + at: Date.parse("2026-10-07T00:00:00Z"), + reasons: [ + "CLAUDE_CODE_ENTRYPOINT=claude-desktop — this host sets its own ANTHROPIC_BASE_URL", + ], + }), + ); + try { + await mockFetch( + () => + new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + )(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: cfgDir, + OPENCODE_CONFIG: undefined, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const cl = report.lanes.find((l) => l.agent === "claude"); + assert.equal(cl?.installed, true); + assert.ok( + cl?.warnings?.some( + (w) => + w.includes("routing bypass") && + w.includes("CLAUDE_CODE_ENTRYPOINT=claude-desktop"), + ), + `warnings: ${JSON.stringify(cl?.warnings)}`, + ); + assert.match(renderDoctorReport(report), /⚠️ .*routing bypass/); + }, + ); + }); + // Corrupt marker: surfaced as nothing, never as a probe failure. + writeFileSync( + path.join(stateLane, "claude-routing-warning.json"), + "{ not json", + ); + await mockFetch( + () => + new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + )(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: cfgDir, + OPENCODE_CONFIG: undefined, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + const cl = report.lanes.find((l) => l.agent === "claude"); + assert.equal(cl?.verdict, "ok"); + assert.ok( + !cl?.warnings?.some((w) => w.includes("routing bypass")), + `corrupt marker must not surface: ${JSON.stringify(cl?.warnings)}`, + ); + }, + ); + }); + } finally { + rmrf(base); + } }); test("runDoctor: full report against a mocked registry, sandboxed homes", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-run-")); - const urls: string[] = []; - const runWithFetch = mockFetch((url) => { - urls.push(url); - return new Response( - JSON.stringify({ name: "billion-context", version: "999.0.0" }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ); - }); - try { - await runWithFetch(async () => { - await withEnv( - { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: undefined, - }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - assert.ok( - urls.some((u) => - u.includes("registry.npmjs.org/billion-context/latest"), - ), - `registry URL hit: ${urls.join(", ")}`, - ); - assert.equal(report.global.registryVersion, "999.0.0"); - assert.equal(report.global.updateTag, "latest"); - assert.deepEqual( - report.lanes.map((l) => l.agent).sort(), - [...PLUGIN_AGENTS].sort(), - ); - for (const lane of report.lanes) { - assert.equal( - lane.installed, - false, - `${lane.agent} should be absent in an empty sandbox`, - ); - assert.equal(lane.verdict, "absent"); - assert.equal(lane.registryVersion, "999.0.0"); - } - assert.deepEqual(report.processes, []); - if (report.global.form === "checkout") { - assert.equal(report.global.verdict, "frozen"); - } else { - assert.ok(["ok", "stale"].includes(report.global.verdict)); - } - const parsed = JSON.parse( - JSON.stringify(report, null, 2), - ) as DoctorReport; - assert.equal(parsed.global.registryVersion, "999.0.0"); - assert.ok(renderDoctorReport(parsed).includes("bili doctor")); - }, - ); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-run-")); + const urls: string[] = []; + const runWithFetch = mockFetch((url) => { + urls.push(url); + return new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }); + try { + await runWithFetch(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: undefined, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + assert.ok( + urls.some((u) => + u.includes("registry.npmjs.org/billion-context/latest"), + ), + `registry URL hit: ${urls.join(", ")}`, + ); + assert.equal(report.global.registryVersion, "999.0.0"); + assert.equal(report.global.updateTag, "latest"); + assert.deepEqual( + report.lanes.map((l) => l.agent).sort(), + [...PLUGIN_AGENTS].sort(), + ); + for (const lane of report.lanes) { + assert.equal( + lane.installed, + false, + `${lane.agent} should be absent in an empty sandbox`, + ); + assert.equal(lane.verdict, "absent"); + assert.equal(lane.registryVersion, "999.0.0"); + } + assert.deepEqual(report.processes, []); + if (report.global.form === "checkout") { + assert.equal(report.global.verdict, "frozen"); + } else { + assert.ok(["ok", "stale"].includes(report.global.verdict)); + } + const parsed = JSON.parse( + JSON.stringify(report, null, 2), + ) as DoctorReport; + assert.equal(parsed.global.registryVersion, "999.0.0"); + assert.ok(renderDoctorReport(parsed).includes("bili doctor")); + }, + ); + }); + } finally { + rmrf(base); + } }); test("runDoctor: unreachable registry never produces a false-stale verdict", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-run-")); - const runWithFetch = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); - try { - await runWithFetch(async () => { - await withEnv( - { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: undefined, - }, - async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - }); - assert.equal(report.global.registryVersion, undefined); - assert.match(report.global.reason ?? "", /registry unreachable/); - for (const lane of report.lanes) { - assert.notEqual(lane.verdict, "stale"); - } - }, - ); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-run-")); + const runWithFetch = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); + try { + await runWithFetch(async () => { + await withEnv( + { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: undefined, + }, + async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + }); + assert.equal(report.global.registryVersion, undefined); + assert.match(report.global.reason ?? "", /registry unreachable/); + for (const lane of report.lanes) { + assert.notEqual(lane.verdict, "stale"); + } + }, + ); + }); + } finally { + rmrf(base); + } }); function advisoryDocFor( - entries: Array<{ - id: string; - affected: string; - target: string; - reason: string; - }>, + entries: Array<{ + id: string; + affected: string; + target: string; + reason: string; + }>, ): Record { - return { - billionContextAdvisories: { - schema: 1, - updated: "2026-09-28", - advisories: entries, - }, - }; + return { + billionContextAdvisories: { + schema: 1, + updated: "2026-09-28", + advisories: entries, + }, + }; } const ADVISORY_URL = "https://registry.test/bc-advisories.json"; function doctorSandboxEnv(base: string): Record { - return { - HOME: path.join(base, "home"), - XDG_CONFIG_HOME: path.join(base, "xdg-config"), - XDG_DATA_HOME: path.join(base, "xdg-data"), - XDG_CACHE_HOME: path.join(base, "xdg-cache"), - XDG_STATE_HOME: path.join(base, "xdg-state"), - PI_CODING_AGENT_DIR: undefined, - PI_HOME: undefined, - DSH_HOME: undefined, - HERMES_HOME: undefined, - KIMI_CODE_HOME: undefined, - CODEX_HOME: undefined, - CLAUDE_CONFIG_DIR: undefined, - OPENCODE_CONFIG: undefined, - }; + return { + HOME: path.join(base, "home"), + XDG_CONFIG_HOME: path.join(base, "xdg-config"), + XDG_DATA_HOME: path.join(base, "xdg-data"), + XDG_CACHE_HOME: path.join(base, "xdg-cache"), + XDG_STATE_HOME: path.join(base, "xdg-state"), + PI_CODING_AGENT_DIR: undefined, + PI_HOME: undefined, + DSH_HOME: undefined, + HERMES_HOME: undefined, + KIMI_CODE_HOME: undefined, + CODEX_HOME: undefined, + CLAUDE_CONFIG_DIR: undefined, + OPENCODE_CONFIG: undefined, + }; } test("#1577: bili doctor reports an active advisory against the on-disk version", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-adv-")); - const advDoc = advisoryDocFor([ - { - id: "bc-2026-001", - affected: ">=0.0.0", - target: "99.0.0", - reason: "corrupts tool-call arguments", - }, - ]); - const runWithFetch = mockFetch((url) => - url.includes("bc-advisories.json") - ? new Response(JSON.stringify(advDoc)) - : new Response( - JSON.stringify({ name: "billion-context", version: "999.0.0" }), - { status: 200, headers: { "content-type": "application/json" } }, - ), - ); - try { - await runWithFetch(async () => { - await withEnv(doctorSandboxEnv(base), async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - advisoryUrl: ADVISORY_URL, - }); - assert.equal(report.global.advisory?.error, undefined); - assert.equal(report.global.advisory?.active?.id, "bc-2026-001"); - assert.equal( - report.global.advisory?.active?.currentVersion, - report.global.diskVersion ?? "0.1.143", - ); - const text = renderDoctorReport(report); - assert.match( - text, - /advisory {6}⚠️ \[bc-2026-001\] .*corrupts tool-call arguments/, - ); - assert.ok(text.includes("npm install -g billion-context@99.0.0")); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-adv-")); + const advDoc = advisoryDocFor([ + { + id: "bc-2026-001", + affected: ">=0.0.0", + target: "99.0.0", + reason: "corrupts tool-call arguments", + }, + ]); + const runWithFetch = mockFetch((url) => + url.includes("bc-advisories.json") + ? new Response(JSON.stringify(advDoc)) + : new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ); + try { + await runWithFetch(async () => { + await withEnv(doctorSandboxEnv(base), async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + advisoryUrl: ADVISORY_URL, + }); + assert.equal(report.global.advisory?.error, undefined); + assert.equal(report.global.advisory?.active?.id, "bc-2026-001"); + assert.equal( + report.global.advisory?.active?.currentVersion, + report.global.diskVersion ?? "0.1.143", + ); + const text = renderDoctorReport(report); + assert.match( + text, + /advisory {6}⚠️ \[bc-2026-001\] .*corrupts tool-call arguments/, + ); + assert.ok(text.includes("npm install -g billion-context@99.0.0")); + }); + }); + } finally { + rmrf(base); + } }); test("#1577: bili doctor reports a clean advisory state as 'none' and a failed source as unknown", async () => { - const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-adv-none-")); - const cleanDoc = advisoryDocFor([]); - const runClean = mockFetch((url) => - url.includes("bc-advisories.json") - ? new Response(JSON.stringify(cleanDoc)) - : new Response( - JSON.stringify({ name: "billion-context", version: "999.0.0" }), - { status: 200, headers: { "content-type": "application/json" } }, - ), - ); - try { - await runClean(async () => { - await withEnv(doctorSandboxEnv(base), async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - advisoryUrl: ADVISORY_URL, - }); - assert.equal(report.global.advisory?.active, undefined); - assert.equal(report.global.advisory?.error, undefined); - assert.match(renderDoctorReport(report), /advisory {6}none/); - }); - }); - const runFail = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); - await runFail(async () => { - await withEnv(doctorSandboxEnv(base), async () => { - const report = await runDoctor({ - packageName: "billion-context", - runningVersion: "0.1.143", - advisoryUrl: ADVISORY_URL, - }); - assert.equal(report.global.advisory?.active, undefined); - assert.match(report.global.advisory?.error ?? "", /ENOTFOUND|fetch/i); - assert.match( - renderDoctorReport(report), - /advisory {6}check failed .*— status unknown/, - ); - }); - }); - } finally { - rmrf(base); - } + const base = mkdtempSync(path.join(tmpdir(), "bc-doctor-adv-none-")); + const cleanDoc = advisoryDocFor([]); + const runClean = mockFetch((url) => + url.includes("bc-advisories.json") + ? new Response(JSON.stringify(cleanDoc)) + : new Response( + JSON.stringify({ name: "billion-context", version: "999.0.0" }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ); + try { + await runClean(async () => { + await withEnv(doctorSandboxEnv(base), async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + advisoryUrl: ADVISORY_URL, + }); + assert.equal(report.global.advisory?.active, undefined); + assert.equal(report.global.advisory?.error, undefined); + assert.match(renderDoctorReport(report), /advisory {6}none/); + }); + }); + const runFail = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); + await runFail(async () => { + await withEnv(doctorSandboxEnv(base), async () => { + const report = await runDoctor({ + packageName: "billion-context", + runningVersion: "0.1.143", + advisoryUrl: ADVISORY_URL, + }); + assert.equal(report.global.advisory?.active, undefined); + assert.match(report.global.advisory?.error ?? "", /ENOTFOUND|fetch/i); + assert.match( + renderDoctorReport(report), + /advisory {6}check failed .*— status unknown/, + ); + }); + }); + } finally { + rmrf(base); + } }); diff --git a/tests/proxy-service.test.ts b/tests/proxy-service.test.ts index 9a6b551b7b..97c3061428 100644 --- a/tests/proxy-service.test.ts +++ b/tests/proxy-service.test.ts @@ -4,426 +4,426 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { - BILI_TASK_NAME, - planTaskDelete, - planTaskDisable, - planTaskEnable, - planTaskEnd, - planTaskQuery, - planTaskRegister, - planTaskRegisterXml, - planTaskRun, - renderTaskLauncherVbs, - renderTaskXml, - type TaskRunner, + BILI_TASK_NAME, + planTaskDelete, + planTaskDisable, + planTaskEnable, + planTaskEnd, + planTaskQuery, + planTaskRegister, + planTaskRegisterXml, + planTaskRun, + renderTaskLauncherVbs, + renderTaskXml, + type TaskRunner, } from "../src/proxy-service/task-scheduler.ts"; import { - disableProxyService, - enableProxyService, - installProxyService, - proxyServiceStatus, - removeProxyService, - restartProxyService, - type TaskCommand, - type TaskRunnerResult, + disableProxyService, + enableProxyService, + installProxyService, + proxyServiceStatus, + removeProxyService, + restartProxyService, + type TaskCommand, + type TaskRunnerResult, } from "../src/proxy-service/index.ts"; import { - planDaemonReload, - planSystemdEnableNow, - planSystemdIsActive, - planSystemdIsEnabled, - renderSystemdUnit, + planDaemonReload, + planSystemdEnableNow, + planSystemdIsActive, + planSystemdIsEnabled, + renderSystemdUnit, } from "../src/proxy-service/systemd.ts"; import { parseArgs } from "../src/cli.ts"; const result = ( - exitCode: number, - stdout = "", - stderr = "", + exitCode: number, + stdout = "", + stderr = "", ): TaskRunnerResult => ({ exitCode, stdout, stderr }); const taskRow = - 'true'; + 'true'; test("Task Scheduler command plans are per-user logon and safely quoted", () => { - const planned = planTaskRegister({ - nodePath: "C:\\Program Files\\nodejs\\node.exe", - entryPath: - "C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js", - port: 18787, - host: "127.0.0.1", - }); - assert.equal(planned.file, "schtasks.exe"); - assert.deepEqual(planned.args.slice(0, 2), ["/Create", "/TN"]); - assert.ok(planned.args.includes("ONLOGON")); - assert.ok(planned.args.includes("LIMITED")); - const taskRun = planned.args[planned.args.indexOf("/TR") + 1]!; - assert.ok(taskRun.includes('"C:\\Program Files\\nodejs\\node.exe"')); - assert.ok( - taskRun.includes( - '"C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js"', - ), - ); - assert.ok(taskRun.includes("--port 18787")); - assert.equal( - planTaskQuery().args.join(" "), - `/Query /TN ${BILI_TASK_NAME} /XML`, - ); - assert.deepEqual(planTaskRun().args.slice(0, 2), ["/Run", "/TN"]); - assert.deepEqual(planTaskEnd().args.slice(0, 2), ["/End", "/TN"]); - assert.ok(planTaskDisable().args.includes("/DISABLE")); - assert.ok(planTaskEnable().args.includes("/ENABLE")); - assert.ok(planTaskDelete().args.includes("/F")); - assert.throws( - () => - planTaskRegister({ - nodePath: "node.exe", - entryPath: "C:\\bili.js", - port: 8787, - }), - /absolute/, - ); - assert.throws( - () => - planTaskRegister({ - nodePath: "C:\\node.exe", - entryPath: "C:\\bili.js", - port: 65536, - }), - /port/, - ); + const planned = planTaskRegister({ + nodePath: "C:\\Program Files\\nodejs\\node.exe", + entryPath: + "C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js", + port: 18787, + host: "127.0.0.1", + }); + assert.equal(planned.file, "schtasks.exe"); + assert.deepEqual(planned.args.slice(0, 2), ["/Create", "/TN"]); + assert.ok(planned.args.includes("ONLOGON")); + assert.ok(planned.args.includes("LIMITED")); + const taskRun = planned.args[planned.args.indexOf("/TR") + 1]!; + assert.ok(taskRun.includes('"C:\\Program Files\\nodejs\\node.exe"')); + assert.ok( + taskRun.includes( + '"C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js"', + ), + ); + assert.ok(taskRun.includes("--port 18787")); + assert.equal( + planTaskQuery().args.join(" "), + `/Query /TN ${BILI_TASK_NAME} /XML`, + ); + assert.deepEqual(planTaskRun().args.slice(0, 2), ["/Run", "/TN"]); + assert.deepEqual(planTaskEnd().args.slice(0, 2), ["/End", "/TN"]); + assert.ok(planTaskDisable().args.includes("/DISABLE")); + assert.ok(planTaskEnable().args.includes("/ENABLE")); + assert.ok(planTaskDelete().args.includes("/F")); + assert.throws( + () => + planTaskRegister({ + nodePath: "node.exe", + entryPath: "C:\\bili.js", + port: 8787, + }), + /absolute/, + ); + assert.throws( + () => + planTaskRegister({ + nodePath: "C:\\node.exe", + entryPath: "C:\\bili.js", + port: 65536, + }), + /port/, + ); }); // The proxy must never put a console window in the user's session: an unhidden // at-logon task makes Task Scheduler create one and no child-side windowsHide // can suppress it. These assertions pin the setting that prevents the window. test("the registered task document is hidden and registers from XML", () => { - const planned = planTaskRegisterXml( - "C:\\Users\\Alice\\AppData\\Local\\bili\\task.xml", - ); - assert.equal(planned.file, "schtasks.exe"); - assert.deepEqual(planned.args.slice(0, 2), ["/Create", "/TN"]); - assert.ok(planned.args.includes("/XML")); - assert.equal( - planned.args[planned.args.indexOf("/XML") + 1], - "C:\\Users\\Alice\\AppData\\Local\\bili\\task.xml", - ); + const planned = planTaskRegisterXml( + "C:\\Users\\Alice\\AppData\\Local\\bili\\task.xml", + ); + assert.equal(planned.file, "schtasks.exe"); + assert.deepEqual(planned.args.slice(0, 2), ["/Create", "/TN"]); + assert.ok(planned.args.includes("/XML")); + assert.equal( + planned.args[planned.args.indexOf("/XML") + 1], + "C:\\Users\\Alice\\AppData\\Local\\bili\\task.xml", + ); - const xml = renderTaskXml({ - nodePath: "C:\\Program Files\\nodejs\\node.exe", - entryPath: "C:\\bili & sons\\dist\\index.js", - port: 18787, - host: "127.0.0.1", - launcherPath: "C:\\bili & sons\\launch.vbs", - }); - assert.ok(xml.includes("true"), "task must be hidden"); - assert.ok( - xml.includes("InteractiveToken"), - "must stay per-user and non-elevated", - ); - assert.ok(xml.includes("LeastPrivilege")); - assert.ok( - xml.includes( - "IgnoreNew", - ), - "a second logon must not race for the port", - ); - // alone does NOT stop the console window: the scheduler launches a - // console-subsystem node.exe in the interactive session. The action must go - // through wscript.exe running a hidden-mode .vbs, or a window appears. - assert.ok( - xml.includes("wscript.exe"), - "action must launch through the GUI-subsystem script host", - ); - assert.ok( - xml.includes("launch.vbs"), - "action must reference the generated launcher", - ); - assert.ok( - !xml.includes("C:\\Program Files\\nodejs\\node.exe"), - "node must never be the task action directly", - ); - // The launcher path is the only bili path in the task document; the entry - // path lives inside the .vbs. Ampersands must still be escaped. - assert.ok( - xml.includes("""), - "the quoted launcher argument must be XML-escaped", - ); - assert.ok( - xml.includes("launch.vbs""), - "escaping must not swallow the launcher path", - ); - assert.ok( - !xml.includes("& sons"), - "a raw ampersand must never survive into the document", - ); + const xml = renderTaskXml({ + nodePath: "C:\\Program Files\\nodejs\\node.exe", + entryPath: "C:\\bili & sons\\dist\\index.js", + port: 18787, + host: "127.0.0.1", + launcherPath: "C:\\bili & sons\\launch.vbs", + }); + assert.ok(xml.includes("true"), "task must be hidden"); + assert.ok( + xml.includes("InteractiveToken"), + "must stay per-user and non-elevated", + ); + assert.ok(xml.includes("LeastPrivilege")); + assert.ok( + xml.includes( + "IgnoreNew", + ), + "a second logon must not race for the port", + ); + // alone does NOT stop the console window: the scheduler launches a + // console-subsystem node.exe in the interactive session. The action must go + // through wscript.exe running a hidden-mode .vbs, or a window appears. + assert.ok( + xml.includes("wscript.exe"), + "action must launch through the GUI-subsystem script host", + ); + assert.ok( + xml.includes("launch.vbs"), + "action must reference the generated launcher", + ); + assert.ok( + !xml.includes("C:\\Program Files\\nodejs\\node.exe"), + "node must never be the task action directly", + ); + // The launcher path is the only bili path in the task document; the entry + // path lives inside the .vbs. Ampersands must still be escaped. + assert.ok( + xml.includes("""), + "the quoted launcher argument must be XML-escaped", + ); + assert.ok( + xml.includes("launch.vbs""), + "escaping must not swallow the launcher path", + ); + assert.ok( + !xml.includes("& sons"), + "a raw ampersand must never survive into the document", + ); }); test("the generated launcher runs the proxy in hidden mode through WSH", () => { - const vbs = renderTaskLauncherVbs({ - nodePath: "C:\\Program Files\\nodejs\\node.exe", - entryPath: "C:\\bili & sons\\dist\\index.js", - port: 18787, - host: "127.0.0.1", - }); - // VBScript escapes a literal quote by DOUBLING it, so the emitted source - // carries "" around each path while the value WSH sees is a single quote. - assert.ok( - vbs.includes( - 'cmd = """C:\\Program Files\\nodejs\\node.exe"" ""C:\\bili & sons\\dist\\index.js"" start', - ), - "must invoke the proxy with doubled-quote escaping", - ); - assert.ok(vbs.includes("--port 18787")); - assert.ok(vbs.includes("--no-auto-update")); - assert.ok( - /\.Run cmd, 0, True/.test(vbs), - "window style 0 = hidden, and True = wait so the task keeps owning the proxy", - ); - assert.ok( - !/\.Run cmd, 0, False/.test(vbs), - "False reparents node away from the task and orphans it on uninstall", - ); - assert.ok( - vbs.includes('CreateObject("WScript.Shell")'), - "must use the script host shell object", - ); + const vbs = renderTaskLauncherVbs({ + nodePath: "C:\\Program Files\\nodejs\\node.exe", + entryPath: "C:\\bili & sons\\dist\\index.js", + port: 18787, + host: "127.0.0.1", + }); + // VBScript escapes a literal quote by DOUBLING it, so the emitted source + // carries "" around each path while the value WSH sees is a single quote. + assert.ok( + vbs.includes( + 'cmd = """C:\\Program Files\\nodejs\\node.exe"" ""C:\\bili & sons\\dist\\index.js"" start', + ), + "must invoke the proxy with doubled-quote escaping", + ); + assert.ok(vbs.includes("--port 18787")); + assert.ok(vbs.includes("--no-auto-update")); + assert.ok( + /\.Run cmd, 0, True/.test(vbs), + "window style 0 = hidden, and True = wait so the task keeps owning the proxy", + ); + assert.ok( + !/\.Run cmd, 0, False/.test(vbs), + "False reparents node away from the task and orphans it on uninstall", + ); + assert.ok( + vbs.includes('CreateObject("WScript.Shell")'), + "must use the script host shell object", + ); }); test("the launcher quoting survives a path containing quotes", () => { - const vbs = renderTaskLauncherVbs({ - nodePath: 'C:\\odd "quoted" dir\\node.exe', - entryPath: "C:\\plain\\index.js", - port: 1, - host: "127.0.0.1", - }); - assert.ok( - vbs.includes('""quoted""'), - "an embedded quote must be doubled so it stays inside the VBS string literal", - ); - assert.ok( - vbs.includes('cmd = """C:\\odd ""quoted"" dir\\node.exe""'), - "the whole path must remain one quoted token for WSH", - ); + const vbs = renderTaskLauncherVbs({ + nodePath: 'C:\\odd "quoted" dir\\node.exe', + entryPath: "C:\\plain\\index.js", + port: 1, + host: "127.0.0.1", + }); + assert.ok( + vbs.includes('""quoted""'), + "an embedded quote must be doubled so it stays inside the VBS string literal", + ); + assert.ok( + vbs.includes('cmd = """C:\\odd ""quoted"" dir\\node.exe""'), + "the whole path must remain one quoted token for WSH", + ); }); test("service operations verify install, remain idempotent, and expose failures", async () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "bili-service-")); - const commands: TaskCommand[] = []; - let exists = false; - let disabled = false; - let failCreate = false; - const runner = async (command: TaskCommand): Promise => { - commands.push(command); - if (command.args[0] === "/Query") - return exists - ? result( - 0, - taskRow.replace( - "true", - disabled ? "false" : "true", - ), - ) - : result(1, "", "ERROR: The system cannot find the file specified."); - if (command.args[0] === "/Create") { - if (failCreate) return result(1, "", "Access is denied."); - exists = true; - return result(0, "SUCCESS: The scheduled task was created."); - } - if (command.args[0] === "/Delete") { - const previous = exists; - exists = false; - return previous - ? result(0, "SUCCESS") - : result(1, "", "ERROR: The system cannot find the file specified."); - } - if (command.args[0] === "/Change" && command.args.includes("/DISABLE")) { - disabled = true; - return result(0, "SUCCESS"); - } - if (command.args[0] === "/Change" && command.args.includes("/ENABLE")) { - disabled = false; - return result(0, "SUCCESS"); - } - return result(0, "SUCCESS"); - }; - const config = { - platform: "win32" as NodeJS.Platform, - nodePath: "C:\\node.exe", - entryPath: "C:\\bili\\dist\\index.js", - port: 18787, - stateDirectory: directory, - runner, - }; - try { - assert.equal((await proxyServiceStatus(config)).state, "missing"); - failCreate = true; - const refused = await installProxyService(config); - assert.equal(refused.ok, false); - assert.match(refused.message, /Access is denied/); - assert.equal( - fs.existsSync(path.join(directory, "proxy-service.json")), - false, - ); - failCreate = false; - const installed = await installProxyService(config); - assert.equal(installed.action, "installed"); - assert.equal(installed.state, "ready"); - assert.equal( - (await installProxyService(config)).action, - "already-installed", - ); - assert.equal((await disableProxyService(config)).state, "disabled"); - assert.equal((await proxyServiceStatus(config)).state, "disabled"); - assert.equal((await enableProxyService(config)).state, "ready"); - assert.equal((await restartProxyService(config)).action, "restarted"); - assert.equal((await removeProxyService(config)).action, "removed"); - assert.equal((await removeProxyService(config)).action, "already-absent"); - assert.ok(commands.some((c) => c.args[0] === "/Run")); - } finally { - fs.rmSync(directory, { recursive: true, force: true }); - } + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "bili-service-")); + const commands: TaskCommand[] = []; + let exists = false; + let disabled = false; + let failCreate = false; + const runner = async (command: TaskCommand): Promise => { + commands.push(command); + if (command.args[0] === "/Query") + return exists + ? result( + 0, + taskRow.replace( + "true", + disabled ? "false" : "true", + ), + ) + : result(1, "", "ERROR: The system cannot find the file specified."); + if (command.args[0] === "/Create") { + if (failCreate) return result(1, "", "Access is denied."); + exists = true; + return result(0, "SUCCESS: The scheduled task was created."); + } + if (command.args[0] === "/Delete") { + const previous = exists; + exists = false; + return previous + ? result(0, "SUCCESS") + : result(1, "", "ERROR: The system cannot find the file specified."); + } + if (command.args[0] === "/Change" && command.args.includes("/DISABLE")) { + disabled = true; + return result(0, "SUCCESS"); + } + if (command.args[0] === "/Change" && command.args.includes("/ENABLE")) { + disabled = false; + return result(0, "SUCCESS"); + } + return result(0, "SUCCESS"); + }; + const config = { + platform: "win32" as NodeJS.Platform, + nodePath: "C:\\node.exe", + entryPath: "C:\\bili\\dist\\index.js", + port: 18787, + stateDirectory: directory, + runner, + }; + try { + assert.equal((await proxyServiceStatus(config)).state, "missing"); + failCreate = true; + const refused = await installProxyService(config); + assert.equal(refused.ok, false); + assert.match(refused.message, /Access is denied/); + assert.equal( + fs.existsSync(path.join(directory, "proxy-service.json")), + false, + ); + failCreate = false; + const installed = await installProxyService(config); + assert.equal(installed.action, "installed"); + assert.equal(installed.state, "ready"); + assert.equal( + (await installProxyService(config)).action, + "already-installed", + ); + assert.equal((await disableProxyService(config)).state, "disabled"); + assert.equal((await proxyServiceStatus(config)).state, "disabled"); + assert.equal((await enableProxyService(config)).state, "ready"); + assert.equal((await restartProxyService(config)).action, "restarted"); + assert.equal((await removeProxyService(config)).action, "removed"); + assert.equal((await removeProxyService(config)).action, "already-absent"); + assert.ok(commands.some((c) => c.args[0] === "/Run")); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } }); test("install writes a persistent hidden launcher and remove deletes it", async () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "bili-launcher-")); - const commands: TaskCommand[] = []; - let exists = false; - const runner: TaskRunner = async (command) => { - commands.push(command); - if (command.args[0] === "/Query") - return exists - ? result(0, taskRow) - : result(1, "", "ERROR: The system cannot find the file specified."); - if (command.args[0] === "/Create") { - exists = true; - return result(0, "SUCCESS: The scheduled task was created."); - } - if (command.args[0] === "/Delete") { - const previous = exists; - exists = false; - return previous - ? result(0, "SUCCESS") - : result(1, "", "ERROR: The system cannot find the file specified."); - } - return result(0); - }; - const config = { - platform: "win32" as NodeJS.Platform, - nodePath: process.execPath, - entryPath: path.join(directory, "dist", "index.js"), - stateDirectory: directory, - runner, - }; - const launcher = path.join(directory, "Billion-Context-Proxy.launch.vbs"); - try { - const installed = await installProxyService(config); - assert.equal(installed.action, "installed"); - // The task references this file at every logon, so it must persist past - // the install command (unlike the temporary XML transport). - assert.ok(fs.existsSync(launcher), "launcher must persist after install"); - // Written UTF-16LE with a BOM for WSH; read it back the same way. - const vbs = fs.readFileSync(launcher, "utf16le"); - assert.ok(vbs.includes("sh.Run cmd, 0, True")); - // /Query also carries a bare /XML flag, so target the /Create command. - const xmlWrite = commands.find( - (c) => c.args[0] === "/Create" && c.args.includes("/XML"), - ); - assert.ok(xmlWrite !== undefined, "registration must go through /XML"); - const xmlPath = xmlWrite.args[xmlWrite.args.indexOf("/XML") + 1] ?? ""; - assert.notEqual(xmlPath, "", "the XML path must be present"); - assert.equal( - fs.existsSync(xmlPath), - false, - "the XML transport file must be cleaned up", - ); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "bili-launcher-")); + const commands: TaskCommand[] = []; + let exists = false; + const runner: TaskRunner = async (command) => { + commands.push(command); + if (command.args[0] === "/Query") + return exists + ? result(0, taskRow) + : result(1, "", "ERROR: The system cannot find the file specified."); + if (command.args[0] === "/Create") { + exists = true; + return result(0, "SUCCESS: The scheduled task was created."); + } + if (command.args[0] === "/Delete") { + const previous = exists; + exists = false; + return previous + ? result(0, "SUCCESS") + : result(1, "", "ERROR: The system cannot find the file specified."); + } + return result(0); + }; + const config = { + platform: "win32" as NodeJS.Platform, + nodePath: process.execPath, + entryPath: path.join(directory, "dist", "index.js"), + stateDirectory: directory, + runner, + }; + const launcher = path.join(directory, "Billion-Context-Proxy.launch.vbs"); + try { + const installed = await installProxyService(config); + assert.equal(installed.action, "installed"); + // The task references this file at every logon, so it must persist past + // the install command (unlike the temporary XML transport). + assert.ok(fs.existsSync(launcher), "launcher must persist after install"); + // Written UTF-16LE with a BOM for WSH; read it back the same way. + const vbs = fs.readFileSync(launcher, "utf16le"); + assert.ok(vbs.includes("sh.Run cmd, 0, True")); + // /Query also carries a bare /XML flag, so target the /Create command. + const xmlWrite = commands.find( + (c) => c.args[0] === "/Create" && c.args.includes("/XML"), + ); + assert.ok(xmlWrite !== undefined, "registration must go through /XML"); + const xmlPath = xmlWrite.args[xmlWrite.args.indexOf("/XML") + 1] ?? ""; + assert.notEqual(xmlPath, "", "the XML path must be present"); + assert.equal( + fs.existsSync(xmlPath), + false, + "the XML transport file must be cleaned up", + ); - await removeProxyService(config); - assert.equal( - fs.existsSync(launcher), - false, - "uninstall must not leave a launcher pointing at a removed dist tree", - ); - // The task is the only handle on the running proxy, so it must be stopped - // before the task is deleted. - const endIndex = commands.findIndex((c) => c.args[0] === "/End"); - const deleteIndex = commands.findIndex((c) => c.args[0] === "/Delete"); - assert.notEqual(endIndex, -1, "uninstall must stop the running instance"); - assert.notEqual(deleteIndex, -1, "uninstall must delete the task"); - assert.ok( - endIndex < deleteIndex, - "the instance must be stopped before the task handle is removed", - ); - } finally { - fs.rmSync(directory, { recursive: true, force: true }); - } + await removeProxyService(config); + assert.equal( + fs.existsSync(launcher), + false, + "uninstall must not leave a launcher pointing at a removed dist tree", + ); + // The task is the only handle on the running proxy, so it must be stopped + // before the task is deleted. + const endIndex = commands.findIndex((c) => c.args[0] === "/End"); + const deleteIndex = commands.findIndex((c) => c.args[0] === "/Delete"); + assert.notEqual(endIndex, -1, "uninstall must stop the running instance"); + assert.notEqual(deleteIndex, -1, "uninstall must delete the task"); + assert.ok( + endIndex < deleteIndex, + "the instance must be stopped before the task handle is removed", + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } }); test("service reports unsupported platforms without touching them", async () => { - // Windows (schtasks) and Linux (systemd user unit) are the two serviced - // platforms; everything else must refuse rather than silently do nothing. - const result = await installProxyService({ platform: "darwin" }); - assert.equal(result.action, "unsupported"); - assert.equal(result.ok, false); - assert.match(result.message, /darwin/); + // Windows (schtasks) and Linux (systemd user unit) are the two serviced + // platforms; everything else must refuse rather than silently do nothing. + const result = await installProxyService({ platform: "darwin" }); + assert.equal(result.action, "unsupported"); + assert.equal(result.ok, false); + assert.match(result.message, /darwin/); }); test("CLI parses service lifecycle actions", () => { - for (const action of [ - "install", - "status", - "restart", - "enable", - "disable", - "remove", - ] as const) { - const parsed = parseArgs(["service", action]); - assert.equal(parsed.command, "service"); - assert.equal(parsed.serviceAction, action); - } + for (const action of [ + "install", + "status", + "restart", + "enable", + "disable", + "remove", + ] as const) { + const parsed = parseArgs(["service", action]); + assert.equal(parsed.command, "service"); + assert.equal(parsed.serviceAction, action); + } }); test("service leaves an unowned task with the bili name untouched", async () => { - const directory = fs.mkdtempSync( - path.join(os.tmpdir(), "bili-service-collision-"), - ); - const commands: TaskCommand[] = []; - const runner = async (command: TaskCommand): Promise => { - commands.push(command); - if (command.args[0] === "/Query") return result(0, taskRow); - return result(0, "SUCCESS"); - }; - const config = { - platform: "win32" as NodeJS.Platform, - nodePath: "C:\\node.exe", - entryPath: "C:\\bili\\dist\\index.js", - port: 18787, - stateDirectory: directory, - runner, - }; - try { - assert.equal((await proxyServiceStatus(config)).state, "unknown"); - assert.equal((await installProxyService(config)).ok, false); - assert.equal((await disableProxyService(config)).ok, false); - assert.equal((await enableProxyService(config)).ok, false); - assert.equal((await restartProxyService(config)).ok, false); - assert.equal((await removeProxyService(config)).ok, false); - assert.equal( - commands.filter((command) => - ["/Create", "/Delete", "/Change", "/End"].includes(command.args[0]!), - ).length, - 0, - ); - } finally { - fs.rmSync(directory, { recursive: true, force: true }); - } + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "bili-service-collision-"), + ); + const commands: TaskCommand[] = []; + const runner = async (command: TaskCommand): Promise => { + commands.push(command); + if (command.args[0] === "/Query") return result(0, taskRow); + return result(0, "SUCCESS"); + }; + const config = { + platform: "win32" as NodeJS.Platform, + nodePath: "C:\\node.exe", + entryPath: "C:\\bili\\dist\\index.js", + port: 18787, + stateDirectory: directory, + runner, + }; + try { + assert.equal((await proxyServiceStatus(config)).state, "unknown"); + assert.equal((await installProxyService(config)).ok, false); + assert.equal((await disableProxyService(config)).ok, false); + assert.equal((await enableProxyService(config)).ok, false); + assert.equal((await restartProxyService(config)).ok, false); + assert.equal((await removeProxyService(config)).ok, false); + assert.equal( + commands.filter((command) => + ["/Create", "/Delete", "/Change", "/End"].includes(command.args[0]!), + ).length, + 0, + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } }); test("localized Task Scheduler missing-task output is treated as absent", async () => { - const runner = async (): Promise => - result(1, "", "错误: 系统找不到指定的文件。"); - const status = await proxyServiceStatus({ platform: "win32", runner }); - assert.equal(status.ok, true); - assert.equal(status.state, "missing"); + const runner = async (): Promise => + result(1, "", "错误: 系统找不到指定的文件。"); + const status = await proxyServiceStatus({ platform: "win32", runner }); + assert.equal(status.ok, true); + assert.equal(status.state, "missing"); }); // --------------------------------------------------------------------------- @@ -439,255 +439,255 @@ const UNIT_PATH = "/home/alice/.config/systemd/user/bili-proxy.service"; * SAME path the config passes to the service — the fake keys its liveness off * that file, exactly as systemd keys it off the unit it actually loaded. */ function fakeSystemctl( - commands: TaskCommand[], - initial?: { enabled?: boolean; active?: boolean; unitPath?: string }, + commands: TaskCommand[], + initial?: { enabled?: boolean; active?: boolean; unitPath?: string }, ) { - const unitPath = initial?.unitPath ?? UNIT_PATH; - let enabled = initial?.enabled ?? false; - let active = initial?.active ?? false; - const runner = async (command: TaskCommand): Promise => { - commands.push(command); - if (command.file !== "systemctl") return result(1, "", "unexpected binary"); - const args = command.args.filter((a) => a !== "--user"); - switch (args[0]) { - case "daemon-reload": - return result(0, ""); - case "is-enabled": - if (!fs.existsSync(unitPath)) - return result(1, "", "Unit bili-proxy.service could not be found."); - return result(0, enabled ? "enabled" : "disabled"); - case "is-active": - if (!fs.existsSync(unitPath)) return result(3, "inactive"); - return active ? result(0, "active") : result(3, "inactive"); - case "enable": - enabled = true; - // `enable --now` also starts; a bare `enable` does not. - if (command.args.includes("--now")) active = true; - return result(0, ""); - case "disable": - enabled = false; - active = false; - return result(0, ""); - case "start": - active = true; - return result(0, ""); - case "stop": - active = false; - return result(0, ""); - default: - return result(1, "", `unknown verb ${args[0]}`); - } - }; - return { runner, state: () => ({ enabled, active }) }; + const unitPath = initial?.unitPath ?? UNIT_PATH; + let enabled = initial?.enabled ?? false; + let active = initial?.active ?? false; + const runner = async (command: TaskCommand): Promise => { + commands.push(command); + if (command.file !== "systemctl") return result(1, "", "unexpected binary"); + const args = command.args.filter((a) => a !== "--user"); + switch (args[0]) { + case "daemon-reload": + return result(0, ""); + case "is-enabled": + if (!fs.existsSync(unitPath)) + return result(1, "", "Unit bili-proxy.service could not be found."); + return result(0, enabled ? "enabled" : "disabled"); + case "is-active": + if (!fs.existsSync(unitPath)) return result(3, "inactive"); + return active ? result(0, "active") : result(3, "inactive"); + case "enable": + enabled = true; + // `enable --now` also starts; a bare `enable` does not. + if (command.args.includes("--now")) active = true; + return result(0, ""); + case "disable": + enabled = false; + active = false; + return result(0, ""); + case "start": + active = true; + return result(0, ""); + case "stop": + active = false; + return result(0, ""); + default: + return result(1, "", `unknown verb ${args[0]}`); + } + }; + return { runner, state: () => ({ enabled, active }) }; } test("systemd unit plans are per-user, quoted and enable at logon", () => { - const planned = planSystemdEnableNow({ unitName: "bili-proxy.service" }); - assert.equal(planned.file, "systemctl"); - assert.deepEqual(planned.args, [ - "--user", - "enable", - "--now", - "bili-proxy.service", - ]); - assert.deepEqual(planDaemonReload().args, ["--user", "daemon-reload"]); - assert.deepEqual(planSystemdIsEnabled({ unitName: "u" }).args, [ - "--user", - "is-enabled", - "u", - ]); - assert.deepEqual(planSystemdIsActive({ unitName: "u" }).args, [ - "--user", - "is-active", - "u", - ]); + const planned = planSystemdEnableNow({ unitName: "bili-proxy.service" }); + assert.equal(planned.file, "systemctl"); + assert.deepEqual(planned.args, [ + "--user", + "enable", + "--now", + "bili-proxy.service", + ]); + assert.deepEqual(planDaemonReload().args, ["--user", "daemon-reload"]); + assert.deepEqual(planSystemdIsEnabled({ unitName: "u" }).args, [ + "--user", + "is-enabled", + "u", + ]); + assert.deepEqual(planSystemdIsActive({ unitName: "u" }).args, [ + "--user", + "is-active", + "u", + ]); - const unit = renderSystemdUnit({ - nodePath: "/usr/bin/node", - entryPath: "/opt/bili path/dist/index.js", - port: 18787, - host: "127.0.0.1", - unitPath: UNIT_PATH, - }); - assert.match(unit, /^\[Unit\]/m); - assert.match(unit, /WantedBy=default\.target/); - assert.match(unit, /Type=simple/); - assert.match(unit, /Restart=on-failure/); - assert.match(unit, /--no-auto-update/); - // The spaced entry path must survive as ONE argv element. - assert.ok( - unit.includes( - 'ExecStart="/usr/bin/node" "/opt/bili path/dist/index.js" start --host "127.0.0.1" --port 18787 --no-auto-update', - ), - ); - assert.throws( - () => - renderSystemdUnit({ - nodePath: "node", - entryPath: "/opt/bili/dist/index.js", - port: 8787, - unitPath: UNIT_PATH, - }), - /absolute/, - ); - assert.throws( - () => - renderSystemdUnit({ - nodePath: "/usr/bin/node", - entryPath: "/opt/bili/dist/index.js", - port: 0, - unitPath: UNIT_PATH, - }), - /RangeError|port/, - ); + const unit = renderSystemdUnit({ + nodePath: "/usr/bin/node", + entryPath: "/opt/bili path/dist/index.js", + port: 18787, + host: "127.0.0.1", + unitPath: UNIT_PATH, + }); + assert.match(unit, /^\[Unit\]/m); + assert.match(unit, /WantedBy=default\.target/); + assert.match(unit, /Type=simple/); + assert.match(unit, /Restart=on-failure/); + assert.match(unit, /--no-auto-update/); + // The spaced entry path must survive as ONE argv element. + assert.ok( + unit.includes( + 'ExecStart="/usr/bin/node" "/opt/bili path/dist/index.js" start --host "127.0.0.1" --port 18787 --no-auto-update', + ), + ); + assert.throws( + () => + renderSystemdUnit({ + nodePath: "node", + entryPath: "/opt/bili/dist/index.js", + port: 8787, + unitPath: UNIT_PATH, + }), + /absolute/, + ); + assert.throws( + () => + renderSystemdUnit({ + nodePath: "/usr/bin/node", + entryPath: "/opt/bili/dist/index.js", + port: 0, + unitPath: UNIT_PATH, + }), + /RangeError|port/, + ); }); test("quotes are escaped so a path can never inject extra ExecStart arguments", () => { - const unit = renderSystemdUnit({ - nodePath: '/usr/bin/node"', - entryPath: "/opt/b/dist/index.js", - port: 8787, - unitPath: UNIT_PATH, - }); - assert.ok( - unit.includes('ExecStart="/usr/bin/node\\"" "/opt/b/dist/index.js"'), - ); + const unit = renderSystemdUnit({ + nodePath: '/usr/bin/node"', + entryPath: "/opt/b/dist/index.js", + port: 8787, + unitPath: UNIT_PATH, + }); + assert.ok( + unit.includes('ExecStart="/usr/bin/node\\"" "/opt/b/dist/index.js"'), + ); }); test("systemd install writes the unit, enables it, starts it and is idempotent", async () => { - const directory = fs.mkdtempSync( - path.join(os.tmpdir(), "bili-systemd-install-"), - ); - const commands: TaskCommand[] = []; - const unitPath = path.join(directory, "bili-proxy.service"); - const fake = fakeSystemctl(commands, { unitPath }); - const config = { - platform: "linux" as NodeJS.Platform, - taskName: "bili-proxy.service", - nodePath: "/usr/bin/node", - entryPath: "/opt/bili/dist/index.js", - port: 18787, - stateDirectory: directory, - unitPath, - runner: fake.runner, - }; - try { - assert.equal((await proxyServiceStatus(config)).state, "missing"); - const installed = await installProxyService(config); - assert.equal(installed.action, "installed"); - assert.equal(installed.state, "ready"); - assert.ok(fs.readFileSync(config.unitPath, "utf8").includes("ExecStart=")); - assert.ok( - commands.some((c) => c.args.join(" ") === "--user daemon-reload"), - ); - assert.ok( - commands.some( - (c) => c.args.join(" ") === "--user enable --now bili-proxy.service", - ), - ); - assert.deepEqual(fake.state(), { enabled: true, active: true }); - assert.equal((await proxyServiceStatus(config)).state, "ready"); + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "bili-systemd-install-"), + ); + const commands: TaskCommand[] = []; + const unitPath = path.join(directory, "bili-proxy.service"); + const fake = fakeSystemctl(commands, { unitPath }); + const config = { + platform: "linux" as NodeJS.Platform, + taskName: "bili-proxy.service", + nodePath: "/usr/bin/node", + entryPath: "/opt/bili/dist/index.js", + port: 18787, + stateDirectory: directory, + unitPath, + runner: fake.runner, + }; + try { + assert.equal((await proxyServiceStatus(config)).state, "missing"); + const installed = await installProxyService(config); + assert.equal(installed.action, "installed"); + assert.equal(installed.state, "ready"); + assert.ok(fs.readFileSync(config.unitPath, "utf8").includes("ExecStart=")); + assert.ok( + commands.some((c) => c.args.join(" ") === "--user daemon-reload"), + ); + assert.ok( + commands.some( + (c) => c.args.join(" ") === "--user enable --now bili-proxy.service", + ), + ); + assert.deepEqual(fake.state(), { enabled: true, active: true }); + assert.equal((await proxyServiceStatus(config)).state, "ready"); - const again = await installProxyService(config); - assert.equal(again.action, "already-installed"); + const again = await installProxyService(config); + assert.equal(again.action, "already-installed"); - assert.equal((await disableProxyService(config)).state, "disabled"); - assert.deepEqual(fake.state(), { enabled: false, active: false }); - assert.equal((await proxyServiceStatus(config)).state, "disabled"); + assert.equal((await disableProxyService(config)).state, "disabled"); + assert.deepEqual(fake.state(), { enabled: false, active: false }); + assert.equal((await proxyServiceStatus(config)).state, "disabled"); - assert.equal((await enableProxyService(config)).state, "ready"); - assert.deepEqual(fake.state(), { enabled: true, active: true }); + assert.equal((await enableProxyService(config)).state, "ready"); + assert.deepEqual(fake.state(), { enabled: true, active: true }); - assert.equal((await restartProxyService(config)).action, "restarted"); - assert.equal((await removeProxyService(config)).action, "removed"); - assert.equal(fs.existsSync(config.unitPath), false); - assert.equal((await removeProxyService(config)).action, "already-absent"); - } finally { - fs.rmSync(directory, { recursive: true, force: true }); - } + assert.equal((await restartProxyService(config)).action, "restarted"); + assert.equal((await removeProxyService(config)).action, "removed"); + assert.equal(fs.existsSync(config.unitPath), false); + assert.equal((await removeProxyService(config)).action, "already-absent"); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } }); test("systemd install rolls the unit back when it never becomes active", async () => { - const directory = fs.mkdtempSync( - path.join(os.tmpdir(), "bili-systemd-rollback-"), - ); - const commands: TaskCommand[] = []; - const runner = async (command: TaskCommand): Promise => { - commands.push(command); - const args = command.args.filter((a) => a !== "--user"); - if (args[0] === "is-enabled") - return result(1, "", "Unit bili-proxy.service could not be found."); - if (args[0] === "is-active") return result(3, "inactive"); - return result(0, ""); - }; - const config = { - platform: "linux" as NodeJS.Platform, - taskName: "bili-proxy.service", - nodePath: "/usr/bin/node", - entryPath: "/opt/bili/dist/index.js", - port: 18787, - stateDirectory: directory, - unitPath: path.join(directory, "bili-proxy.service"), - runner, - }; - try { - const failed = await installProxyService(config); - assert.equal(failed.ok, false); - assert.match(failed.message, /did not become active/); - // The machine is left as it was: no unit file, no record. - assert.equal(fs.existsSync(config.unitPath), false); - assert.equal( - fs.existsSync(path.join(directory, "proxy-service.json")), - false, - ); - } finally { - fs.rmSync(directory, { recursive: true, force: true }); - } + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "bili-systemd-rollback-"), + ); + const commands: TaskCommand[] = []; + const runner = async (command: TaskCommand): Promise => { + commands.push(command); + const args = command.args.filter((a) => a !== "--user"); + if (args[0] === "is-enabled") + return result(1, "", "Unit bili-proxy.service could not be found."); + if (args[0] === "is-active") return result(3, "inactive"); + return result(0, ""); + }; + const config = { + platform: "linux" as NodeJS.Platform, + taskName: "bili-proxy.service", + nodePath: "/usr/bin/node", + entryPath: "/opt/bili/dist/index.js", + port: 18787, + stateDirectory: directory, + unitPath: path.join(directory, "bili-proxy.service"), + runner, + }; + try { + const failed = await installProxyService(config); + assert.equal(failed.ok, false); + assert.match(failed.message, /did not become active/); + // The machine is left as it was: no unit file, no record. + assert.equal(fs.existsSync(config.unitPath), false); + assert.equal( + fs.existsSync(path.join(directory, "proxy-service.json")), + false, + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } }); test("systemd refuses a host with no user manager and names the fix", async () => { - const runner = async (): Promise => - result(1, "", "Failed to connect to bus: No medium found"); - const installed = await installProxyService({ - platform: "linux", - unitPath: UNIT_PATH, - runner, - }); - assert.equal(installed.ok, false); - assert.match(installed.message, /enable-linger/); + const runner = async (): Promise => + result(1, "", "Failed to connect to bus: No medium found"); + const installed = await installProxyService({ + platform: "linux", + unitPath: UNIT_PATH, + runner, + }); + assert.equal(installed.ok, false); + assert.match(installed.message, /enable-linger/); }); test("systemd leaves a unit it does not own untouched", async () => { - const directory = fs.mkdtempSync( - path.join(os.tmpdir(), "bili-systemd-foreign-"), - ); - const commands: TaskCommand[] = []; - const fake = fakeSystemctl(commands, { enabled: true, active: true }); - fs.writeFileSync(path.join(directory, "bili-proxy.service"), "foreign\n"); - const config = { - platform: "linux" as NodeJS.Platform, - taskName: "bili-proxy.service", - nodePath: "/usr/bin/node", - entryPath: "/opt/bili/dist/index.js", - port: 18787, - stateDirectory: directory, - unitPath: path.join(directory, "bili-proxy.service"), - runner: fake.runner, - }; - try { - const refused = await installProxyService(config); - assert.equal(refused.ok, false); - assert.match(refused.message, /not owned by this bili copy/); - assert.equal(fs.readFileSync(config.unitPath, "utf8"), "foreign\n"); - assert.equal( - commands.filter((c) => - ["disable", "stop", "enable"].includes( - c.args.filter((a) => a !== "--user")[0]!, - ), - ).length, - 0, - ); - } finally { - fs.rmSync(directory, { recursive: true, force: true }); - } + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), "bili-systemd-foreign-"), + ); + const commands: TaskCommand[] = []; + const fake = fakeSystemctl(commands, { enabled: true, active: true }); + fs.writeFileSync(path.join(directory, "bili-proxy.service"), "foreign\n"); + const config = { + platform: "linux" as NodeJS.Platform, + taskName: "bili-proxy.service", + nodePath: "/usr/bin/node", + entryPath: "/opt/bili/dist/index.js", + port: 18787, + stateDirectory: directory, + unitPath: path.join(directory, "bili-proxy.service"), + runner: fake.runner, + }; + try { + const refused = await installProxyService(config); + assert.equal(refused.ok, false); + assert.match(refused.message, /not owned by this bili copy/); + assert.equal(fs.readFileSync(config.unitPath, "utf8"), "foreign\n"); + assert.equal( + commands.filter((c) => + ["disable", "stop", "enable"].includes( + c.args.filter((a) => a !== "--user")[0]!, + ), + ).length, + 0, + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } }); diff --git a/tsup.config.ts b/tsup.config.ts index d83831732b..12f97af2b7 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -3,122 +3,90 @@ import { fileURLToPath } from "node:url"; import { defineConfig } from "tsup"; export default [ - defineConfig({ - entry: [ - "src/index.ts", - "src/mcp.ts", - "src/claude-native-bootstrap.ts", - "src/agent/pi.ts", - "src/agent/pi-native.ts", - "src/agent/omp.ts", - "src/agent/omp-native.ts", - "src/agent/opencode.ts", - "src/agent/opencode-native.ts", - "src/agent/dsh-acp.ts", - "src/agent/dsh-native.ts", - "src/kimi/native-mcp.ts", - "src/kimi/bootstrap-hook.ts", - "src/zcode/mcp-entry.ts", - "src/zcode/bootstrap-hook.ts", - "src/codex/bootstrap-hook.ts", - ], - format: ["esm"], - target: "node20", - platform: "node", - // Non-minified esbuild output KEEPS JSDoc comments attached to class - // members (verified empirically against esbuild bundled with tsup 8.x): - // undici ships class-body JSDoc like `@param {import('./client.js')}` and - // those annotations survive into dist verbatim. Node's ESM loader ignores - // them, but opencode's plugin loader resolves them as REAL files and dies - // with ENOENT → the whole plugin fails to load (silent dead lane; see the - // issue filed from #1234). minifyWhitespace makes esbuild drop all - // non-legal comments while keeping code structure intact (no identifier - // mangling, no syntax rewriting); legal/license footers stay via the - // default legalComments. scripts/check-dist-import-annotations.mjs fails - // the build if any relative import()/require() text ever reappears. - esbuildOptions(options) { - options.minifyWhitespace = true; - // #2186: billion-context-pi-subagents is inlined via noExternal, and - // its ONLY runtime host import is a namespace import of - // @earendil-works/pi-coding-agent (config-dir reads CONFIG_DIR_NAME, - // falling back to ".pi" when absent — the package's documented - // degradation for aliased hosts). Alias it to an empty stub so the - // bundle keeps bili's zero-runtime-dependency contract; no bili entry - // ever imports the real package. - options.alias = { - "@earendil-works/pi-coding-agent": resolve( - dirname(fileURLToPath(import.meta.url)), - "src/agent/pi-host-stub.ts", - ), - }; - }, - outDir: "dist", - clean: true, - sourcemap: true, - splitting: false, - shims: false, - // acp-kernel is a BUILD-TIME dependency: tsup inlines it into dist so the - // published artifact is self-contained (zero runtime deps). Without - // noExternal, esbuild keeps `import ... from "acp-kernel"` in dist, and - // npm then installs acp-kernel as a runtime dep — breaking the - // "dist/index.js is self-contained" contract (AGENTS.md §2.1). Same for - // billion-context-pi-subagents (#2384): vendored under pi-subagents/, - // consumed via file:, and its own build already inlines its typebox peer, - // so its dist is self-contained too. - noExternal: [ - "acp-kernel", - "billion-context-pi-subagents", - "fzstd", - "node-forge", - "semver", - "tar", - "undici", - "jsonc-parser", - "ws", - ], - // sharp is an OPTIONAL runtime dependency (native module): it must stay - // EXTERNAL so dist keeps a real lazy `import("sharp")` that Node resolves - // at runtime from node_modules — missing ⇒ clean pass-through, and the - // bundle stays independent of which sharp version npm resolved (the caret - // range in optionalDependencies would otherwise bake that version into - // dist and break reproducible builds). tsup does not auto-externalize - // optionalDependencies, hence the explicit entry. - external: ["sharp"], - banner: { - // node-forge is a CommonJS dependency that calls require("crypto") etc. - // inlined into our ESM output, esbuild's __require shim throws in an - // ESM context where `require` is undefined. Provide a real require - // (via createRequire) so the shim can load node built-ins. Only node - // built-ins ever reach this path — node-forge is otherwise bundled. - js: "import { createRequire as __biliCreateRequire } from 'node:module';\nconst require = __biliCreateRequire(import.meta.url);", - }, - }), - // #1590: dsh web-profile settings entry (dsh.client browser half). Built as a - // classic script: CJS body wrapped in window.__ModuleLoader__.load({id, - // factory}) — the banner/footer locals shadow module/exports so esbuild's CJS - // output lands inside the factory closure, whose `require` parameter resolves - // externals through dsh's module system (react stays external; nothing else - // may be required). No clean here: this runs after the main config above. - defineConfig({ - entry: { "agent/dsh-native-client": "src/agent/dsh-native-client.ts" }, - format: ["cjs"], - target: "es2020", - platform: "browser", - external: ["react"], - outDir: "dist", - clean: false, - splitting: false, - shims: false, - // Keep the .js name (not tsup's default .cjs): this is a browser classic - // script, not a node CJS artifact, and package.json points at it as-is. - outExtension: () => ({ js: ".js" }), - banner: { - // Trailing balance: `load({ id, factory: (require) => {` opens call + - // object + arrow-body, so the footer closes all three. - js: 'window.__ModuleLoader__.load({ id: "billion-context", factory: (require) => {\nvar module = { exports: {} };\nvar exports = module.exports;\n', - }, - footer: { - js: "\nreturn module.exports;\n}});", - }, - }), +defineConfig({ + entry: ["src/index.ts", "src/mcp.ts", "src/claude-native-bootstrap.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/omp.ts", "src/agent/omp-native.ts", "src/agent/opencode.ts", "src/agent/opencode-native.ts", "src/agent/dsh-acp.ts", "src/agent/dsh-native.ts", "src/kimi/native-mcp.ts", "src/kimi/bootstrap-hook.ts", "src/zcode/mcp-entry.ts", "src/zcode/bootstrap-hook.ts", "src/codex/bootstrap-hook.ts"], + format: ["esm"], + target: "node20", + platform: "node", + // Non-minified esbuild output KEEPS JSDoc comments attached to class + // members (verified empirically against esbuild bundled with tsup 8.x): + // undici ships class-body JSDoc like `@param {import('./client.js')}` and + // those annotations survive into dist verbatim. Node's ESM loader ignores + // them, but opencode's plugin loader resolves them as REAL files and dies + // with ENOENT → the whole plugin fails to load (silent dead lane; see the + // issue filed from #1234). minifyWhitespace makes esbuild drop all + // non-legal comments while keeping code structure intact (no identifier + // mangling, no syntax rewriting); legal/license footers stay via the + // default legalComments. scripts/check-dist-import-annotations.mjs fails + // the build if any relative import()/require() text ever reappears. + esbuildOptions(options) { + options.minifyWhitespace = true; + // #2186: billion-context-pi-subagents is inlined via noExternal, and + // its ONLY runtime host import is a namespace import of + // @earendil-works/pi-coding-agent (config-dir reads CONFIG_DIR_NAME, + // falling back to ".pi" when absent — the package's documented + // degradation for aliased hosts). Alias it to an empty stub so the + // bundle keeps bili's zero-runtime-dependency contract; no bili entry + // ever imports the real package. + options.alias = { "@earendil-works/pi-coding-agent": resolve(dirname(fileURLToPath(import.meta.url)), "src/agent/pi-host-stub.ts") }; + }, + outDir: "dist", + clean: true, + sourcemap: true, + splitting: false, + shims: false, + // acp-kernel is a BUILD-TIME dependency: tsup inlines it into dist so the + // published artifact is self-contained (zero runtime deps). Without + // noExternal, esbuild keeps `import ... from "acp-kernel"` in dist, and + // npm then installs acp-kernel as a runtime dep — breaking the + // "dist/index.js is self-contained" contract (AGENTS.md §2.1). Same for + // billion-context-pi-subagents (#2384): vendored under pi-subagents/, + // consumed via file:, and its own build already inlines its typebox peer, + // so its dist is self-contained too. + noExternal: ["acp-kernel", "billion-context-pi-subagents", "fzstd", "node-forge", "semver", "tar", "undici", "jsonc-parser", "ws"], + // sharp is an OPTIONAL runtime dependency (native module): it must stay + // EXTERNAL so dist keeps a real lazy `import("sharp")` that Node resolves + // at runtime from node_modules — missing ⇒ clean pass-through, and the + // bundle stays independent of which sharp version npm resolved (the caret + // range in optionalDependencies would otherwise bake that version into + // dist and break reproducible builds). tsup does not auto-externalize + // optionalDependencies, hence the explicit entry. + external: ["sharp"], + banner: { + // node-forge is a CommonJS dependency that calls require("crypto") etc. + // inlined into our ESM output, esbuild's __require shim throws in an + // ESM context where `require` is undefined. Provide a real require + // (via createRequire) so the shim can load node built-ins. Only node + // built-ins ever reach this path — node-forge is otherwise bundled. + js: "import { createRequire as __biliCreateRequire } from 'node:module';\nconst require = __biliCreateRequire(import.meta.url);", + }, +}), +// #1590: dsh web-profile settings entry (dsh.client browser half). Built as a +// classic script: CJS body wrapped in window.__ModuleLoader__.load({id, +// factory}) — the banner/footer locals shadow module/exports so esbuild's CJS +// output lands inside the factory closure, whose `require` parameter resolves +// externals through dsh's module system (react stays external; nothing else +// may be required). No clean here: this runs after the main config above. +defineConfig({ + entry: { "agent/dsh-native-client": "src/agent/dsh-native-client.ts" }, + format: ["cjs"], + target: "es2020", + platform: "browser", + external: ["react"], + outDir: "dist", + clean: false, + splitting: false, + shims: false, + // Keep the .js name (not tsup's default .cjs): this is a browser classic + // script, not a node CJS artifact, and package.json points at it as-is. + outExtension: () => ({ js: ".js" }), + banner: { + // Trailing balance: `load({ id, factory: (require) => {` opens call + + // object + arrow-body, so the footer closes all three. + js: "window.__ModuleLoader__.load({ id: \"billion-context\", factory: (require) => {\nvar module = { exports: {} };\nvar exports = module.exports;\n", + }, + footer: { + js: "\nreturn module.exports;\n}});", + }, +}), ]; From 6db3d973c1d0b1c80c8a1a4162f510d9b7dac6f1 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 21:38:14 +0800 Subject: [PATCH 05/20] fix: make the codex service suite pass on POSIX CI lanes - task-scheduler: checkedOptions used path.isAbsolute, which on Linux rejects the Windows drive-letter paths the schtasks plans (and their unit tests) legitimately use; accept POSIX, drive-letter and UNC absolute forms. - codex-integration-status test: the loopback/foreign-evidence case expected 'configured' without ownership evidence, which contradicts the deliberate record-strict policy asserted in codex-route.test.ts ('a loopback-looking URL without ownership evidence is foreign'). Give the case a CODEX_HOME fixture with the sidecar route record (provider target), matching the setup pattern of the neighboring passing test; the file also picks up the 4-space style alignment. Part of #3176 (review fixes found while aligning the PR). --- src/proxy-service/task-scheduler.ts | 297 ++++++++++---------- tests/codex-integration-status.test.ts | 370 +++++++++++++------------ 2 files changed, 349 insertions(+), 318 deletions(-) diff --git a/src/proxy-service/task-scheduler.ts b/src/proxy-service/task-scheduler.ts index 672a3e662e..2d07b944d4 100644 --- a/src/proxy-service/task-scheduler.ts +++ b/src/proxy-service/task-scheduler.ts @@ -3,48 +3,59 @@ import path from "node:path"; export const BILI_TASK_NAME = "Billion Context Proxy"; export interface TaskCommand { - file: string; - args: string[]; + file: string; + args: string[]; } export interface ProxyTaskOptions { - taskName?: string; - nodePath: string; - entryPath: string; - port: number; - host?: string; - /** Absolute path of the generated .vbs launcher the task executes through - * wscript.exe. Required for the hidden registration; `planTaskRegister` - * (the flag form) ignores it. */ - launcherPath?: string; + taskName?: string; + nodePath: string; + entryPath: string; + port: number; + host?: string; + /** Absolute path of the generated .vbs launcher the task executes through + * wscript.exe. Required for the hidden registration; `planTaskRegister` + * (the flag form) ignores it. */ + launcherPath?: string; +} + +/** Absolute on ANY supported OS: these plans describe Windows command lines, + * but the unit suite also runs on POSIX hosts where `path.isAbsolute` rejects + * drive-letter paths. */ +function isAnyAbsolutePath(value: string): boolean { + return ( + path.isAbsolute(value) || + /^[A-Za-z]:[\\/]/.test(value) || + value.startsWith("\\\\") + ); } function checkedOptions(options: ProxyTaskOptions): Required { - if ( - !Number.isInteger(options.port) || - options.port < 1 || - options.port > 65535 - ) { - throw new RangeError( - "proxy service port must be an integer from 1 to 65535", - ); - } - if ( - !path.isAbsolute(options.nodePath) || - !path.isAbsolute(options.entryPath) - ) { - throw new TypeError( - "proxy service executable and entry paths must be absolute", - ); - } - return { - taskName: options.taskName ?? BILI_TASK_NAME, - nodePath: options.nodePath, - entryPath: options.entryPath, - port: options.port, - host: options.host ?? "127.0.0.1", - launcherPath: options.launcherPath ?? "", - }; + if ( + !Number.isInteger(options.port) || + options.port < 1 || + options.port > 65535 + ) { + throw new RangeError( + "proxy service port must be an integer from 1 to 65535", + ); + } + if ( + !isAnyAbsolutePath(options.nodePath) || + !isAnyAbsolutePath(options.entryPath) + ) { + throw new TypeError( + "proxy service executable and entry paths must be absolute", + ); + } + return { + taskName: options.taskName ?? BILI_TASK_NAME, + nodePath: options.nodePath, + entryPath: options.entryPath, + port: options.port, + host: options.host ?? "127.0.0.1", + launcherPath: options.launcherPath ?? "", + }; } /** Build a per-user, at-logon Task Scheduler registration. Paths remain @@ -55,31 +66,31 @@ function checkedOptions(options: ProxyTaskOptions): Required { * unhidden at-logon task runs the proxy WITH a console window in the user's * session (#silent-backend). Kept for runners/tests that assert the old shape. */ export function planTaskRegister(options: ProxyTaskOptions): TaskCommand { - const o = checkedOptions(options); - const run = `"${o.nodePath}" "${o.entryPath}" start --host "${o.host}" --port ${o.port} --no-auto-update`; - return { - file: "schtasks.exe", - args: [ - "/Create", - "/TN", - o.taskName, - "/SC", - "ONLOGON", - "/RL", - "LIMITED", - "/TR", - run, - "/F", - ], - }; + const o = checkedOptions(options); + const run = `"${o.nodePath}" "${o.entryPath}" start --host "${o.host}" --port ${o.port} --no-auto-update`; + return { + file: "schtasks.exe", + args: [ + "/Create", + "/TN", + o.taskName, + "/SC", + "ONLOGON", + "/RL", + "LIMITED", + "/TR", + run, + "/F", + ], + }; } function xmlEscape(value: string): string { - return value - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """); + return value + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); } /** The registration document for the at-logon proxy task. @@ -92,59 +103,59 @@ function xmlEscape(value: string): string { * MultipleInstancesPolicy=IgnoreNew makes a duplicate logon a no-op instead of * a second proxy racing for the same port. */ export function renderTaskXml(options: ProxyTaskOptions): string { - const o = checkedOptions(options); - if (o.launcherPath.length === 0) - throw new TypeError( - "hidden task registration requires an absolute launcher path (the generated .vbs the task runs through wscript.exe)", - ); - const author = process.env.USERNAME ?? process.env.USER ?? ""; - return [ - '', - '', - " ", - ` ${xmlEscape(author)}`, - " Billion Context compression proxy (per-user, at logon).", - " ", - " ", - " ", - " true", - " ", - " ", - " ", - ' ', - ` ${xmlEscape(author)}`, - " InteractiveToken", - " LeastPrivilege", - " ", - " ", - " ", - " IgnoreNew", - " false", - " false", - " true", - " true", - " false", - " ", - " false", - " false", - " ", - " true", - " true", - " true", - " false", - " false", - " PT0S", - " 7", - " ", - ' ', - " ", - ` wscript.exe`, - ` ${xmlEscape(`//B //Nologo "${o.launcherPath}"`)}`, - " ", - " ", - "", - "", - ].join("\r\n"); + const o = checkedOptions(options); + if (o.launcherPath.length === 0) + throw new TypeError( + "hidden task registration requires an absolute launcher path (the generated .vbs the task runs through wscript.exe)", + ); + const author = process.env.USERNAME ?? process.env.USER ?? ""; + return [ + '', + '', + " ", + ` ${xmlEscape(author)}`, + " Billion Context compression proxy (per-user, at logon).", + " ", + " ", + " ", + " true", + " ", + " ", + " ", + ' ', + ` ${xmlEscape(author)}`, + " InteractiveToken", + " LeastPrivilege", + " ", + " ", + " ", + " IgnoreNew", + " false", + " false", + " true", + " true", + " false", + " ", + " false", + " false", + " ", + " true", + " true", + " true", + " false", + " false", + " PT0S", + " 7", + " ", + ' ', + " ", + ` wscript.exe`, + ` ${xmlEscape(`//B //Nologo "${o.launcherPath}"`)}`, + " ", + " ", + "", + "", + ].join("\r\n"); } /** Windows Script Host launcher used as the task action. @@ -163,64 +174,64 @@ export function renderTaskXml(options: ProxyTaskOptions): string { * terminates it (verified: node's window stays 0 in both modes, but only WAIT * keeps the process reachable). */ export function renderTaskLauncherVbs(options: ProxyTaskOptions): string { - const o = checkedOptions(options); - const command = `"${o.nodePath}" "${o.entryPath}" start --host "${o.host}" --port ${o.port} --no-auto-update`; - return [ - "' bili: launch the compression proxy with no console window.", - "Dim sh, cmd", - `cmd = "${command.replace(/"/g, '""')}"`, - 'Set sh = CreateObject("WScript.Shell")', - "' 0 = hidden window, True = wait so the task keeps owning the proxy", - "sh.Run cmd, 0, True", - "", - ].join("\r\n"); + const o = checkedOptions(options); + const command = `"${o.nodePath}" "${o.entryPath}" start --host "${o.host}" --port ${o.port} --no-auto-update`; + return [ + "' bili: launch the compression proxy with no console window.", + "Dim sh, cmd", + `cmd = "${command.replace(/"/g, '""')}"`, + 'Set sh = CreateObject("WScript.Shell")', + "' 0 = hidden window, True = wait so the task keeps owning the proxy", + "sh.Run cmd, 0, True", + "", + ].join("\r\n"); } /** Register from the hidden document: schtasks reads the XML at a file path. */ export function planTaskRegisterXml( - xmlPath: string, - taskName = BILI_TASK_NAME, + xmlPath: string, + taskName = BILI_TASK_NAME, ): TaskCommand { - return { - file: "schtasks.exe", - args: ["/Create", "/TN", taskName, "/XML", xmlPath, "/F"], - }; + return { + file: "schtasks.exe", + args: ["/Create", "/TN", taskName, "/XML", xmlPath, "/F"], + }; } export function planTaskQuery(taskName = BILI_TASK_NAME): TaskCommand { - return { file: "schtasks.exe", args: ["/Query", "/TN", taskName, "/XML"] }; + return { file: "schtasks.exe", args: ["/Query", "/TN", taskName, "/XML"] }; } export function planTaskRun(taskName = BILI_TASK_NAME): TaskCommand { - return { file: "schtasks.exe", args: ["/Run", "/TN", taskName] }; + return { file: "schtasks.exe", args: ["/Run", "/TN", taskName] }; } export function planTaskEnd(taskName = BILI_TASK_NAME): TaskCommand { - return { file: "schtasks.exe", args: ["/End", "/TN", taskName] }; + return { file: "schtasks.exe", args: ["/End", "/TN", taskName] }; } export function planTaskDisable(taskName = BILI_TASK_NAME): TaskCommand { - return { - file: "schtasks.exe", - args: ["/Change", "/TN", taskName, "/DISABLE"], - }; + return { + file: "schtasks.exe", + args: ["/Change", "/TN", taskName, "/DISABLE"], + }; } export function planTaskEnable(taskName = BILI_TASK_NAME): TaskCommand { - return { - file: "schtasks.exe", - args: ["/Change", "/TN", taskName, "/ENABLE"], - }; + return { + file: "schtasks.exe", + args: ["/Change", "/TN", taskName, "/ENABLE"], + }; } export function planTaskDelete(taskName = BILI_TASK_NAME): TaskCommand { - return { file: "schtasks.exe", args: ["/Delete", "/TN", taskName, "/F"] }; + return { file: "schtasks.exe", args: ["/Delete", "/TN", taskName, "/F"] }; } export interface TaskRunnerResult { - exitCode: number; - stdout: string; - stderr: string; + exitCode: number; + stdout: string; + stderr: string; } export type TaskRunner = (command: TaskCommand) => Promise; diff --git a/tests/codex-integration-status.test.ts b/tests/codex-integration-status.test.ts index fcd3b1743a..11e58e0246 100644 --- a/tests/codex-integration-status.test.ts +++ b/tests/codex-integration-status.test.ts @@ -4,8 +4,8 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { - codexRouteRecordPath, - writeCodexRouteRecord, + codexRouteRecordPath, + writeCodexRouteRecord, } from "../src/codex-integration/route.ts"; import { inspectCodexIntegration } from "../src/codex-integration/status.ts"; @@ -13,197 +13,217 @@ import { inspectCodexIntegration } from "../src/codex-integration/status.ts"; * `lastSeen` string must still prove freshness, otherwise a user whose * scheduled service predates the numeric field never reaches `verified`. */ function isoOnlyFetch(options: { ageMs: number }) { - return async (input: string | URL | Request): Promise => { - const url = String(input); - if (url.endsWith("/__bili/health")) - return Response.json({ ok: true }, { status: 200 }); - if (url.endsWith("/__bili/stats")) - return Response.json({ - sessions: [ - { - codexClient: true, - requests: 2, - lastSeen: new Date(Date.now() - options.ageMs).toISOString(), - lastSeenMs: null, - }, - ], - }); - return new Response("not found", { status: 404 }); - }; + return async (input: string | URL | Request): Promise => { + const url = String(input); + if (url.endsWith("/__bili/health")) + return Response.json({ ok: true }, { status: 200 }); + if (url.endsWith("/__bili/stats")) + return Response.json({ + sessions: [ + { + codexClient: true, + requests: 2, + lastSeen: new Date(Date.now() - options.ageMs).toISOString(), + lastSeenMs: null, + }, + ], + }); + return new Response("not found", { status: 404 }); + }; } test("an ISO-only lastSeen still proves a fresh Codex request", async () => { - const route = "http://127.0.0.1:18787/bili/https://api.kourichat.com/v1"; - const config = `model_provider = "custom"\n\n[model_providers.custom]\nbase_url = "${route}"\n`; - const fresh = await inspectCodexIntegration({ - origin: "http://127.0.0.1:18787", - codexConfigText: config, - fetchImpl: isoOnlyFetch({ ageMs: 20_000 }), - }); - assert.equal(fresh.state, "verified"); - // Beyond the evidence window a session is history, not current proof. - const stale = await inspectCodexIntegration({ - origin: "http://127.0.0.1:18787", - codexConfigText: config, - fetchImpl: isoOnlyFetch({ ageMs: 25 * 60 * 60_000 }), - }); - assert.notEqual(stale.state, "verified"); + const route = "http://127.0.0.1:18787/bili/https://api.kourichat.com/v1"; + const config = `model_provider = "custom"\n\n[model_providers.custom]\nbase_url = "${route}"\n`; + const fresh = await inspectCodexIntegration({ + origin: "http://127.0.0.1:18787", + codexConfigText: config, + fetchImpl: isoOnlyFetch({ ageMs: 20_000 }), + }); + assert.equal(fresh.state, "verified"); + // Beyond the evidence window a session is history, not current proof. + const stale = await inspectCodexIntegration({ + origin: "http://127.0.0.1:18787", + codexConfigText: config, + fetchImpl: isoOnlyFetch({ ageMs: 25 * 60 * 60_000 }), + }); + assert.notEqual(stale.state, "verified"); }); /** Codex evidence must survive a user idling for a while, but a session served * from bili's own loopback test upstreams, or one whose hint names another * client, must never count. */ test("loopback-fixture sessions and foreign clients are not Codex evidence", async () => { - const origin = "http://127.0.0.1:18787"; - const route = `${origin}/bili/https://api.kourichat.com/v1`; - const config = `model_provider = "custom"\n\n[model_providers.custom]\nbase_url = "${route}"\n`; - const withSession = - (session: Record) => - async (input: string | URL | Request): Promise => { - const url = String(input); - if (url.endsWith("/__bili/health")) - return Response.json({ ok: true }, { status: 200 }); - if (url.endsWith("/__bili/stats")) - return Response.json({ - sessions: [ - { requests: 1, lastSeenMs: Date.now() - 1000, ...session }, - ], - }); - return new Response("not found", { status: 404 }); - }; + // The route is only "configured" once bili's sidecar record attests it — + // a shape match alone is foreign by design (codex-route.test.ts). + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-status-")); + const file = path.join(home, "config.toml"); + const env = { ...process.env, CODEX_HOME: home }; + const origin = "http://127.0.0.1:18787"; + const route = `${origin}/bili/https://api.kourichat.com/v1`; + const config = `model_provider = "custom"\n\n[model_providers.custom]\nbase_url = "${route}"\n`; + try { + fs.writeFileSync(file, config); + writeCodexRouteRecord(codexRouteRecordPath(file), { + schemaVersion: 1, + writtenValue: route, + previousValue: null, + upstream: "https://api.kourichat.com/v1", + target: { kind: "provider", provider: "custom" }, + }); + const withSession = + (session: Record) => + async (input: string | URL | Request): Promise => { + const url = String(input); + if (url.endsWith("/__bili/health")) + return Response.json({ ok: true }, { status: 200 }); + if (url.endsWith("/__bili/stats")) + return Response.json({ + sessions: [ + { requests: 1, lastSeenMs: Date.now() - 1000, ...session }, + ], + }); + return new Response("not found", { status: 404 }); + }; - // A fake-E2E session (loopback upstream) plus an idle hour: still only configured. - const fixture = await inspectCodexIntegration({ - origin, - codexConfigText: config, - fetchImpl: withSession({ - codexClient: true, - protocol: "responses", - upstream: `http://127.0.0.1:4805`, - }), - }); - assert.equal(fixture.state, "configured"); + // A fake-E2E session (loopback upstream) plus an idle hour: still only configured. + const fixture = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: withSession({ + codexClient: true, + protocol: "responses", + upstream: `http://127.0.0.1:4805`, + }), + }); + assert.equal(fixture.state, "configured"); - // A Responses-protocol session with no client hint is Codex's. - const hintless = await inspectCodexIntegration({ - origin, - codexConfigText: config, - fetchImpl: withSession({ - protocol: "responses", - upstream: "https://api.kourichat.com", - }), - }); - assert.equal(hintless.state, "verified"); + // A Responses-protocol session with no client hint is Codex's. + const hintless = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: withSession({ + protocol: "responses", + upstream: "https://api.kourichat.com", + }), + }); + assert.equal(hintless.state, "verified"); - // A hint naming another client vetoes an otherwise Codex-shaped session. - const foreign = await inspectCodexIntegration({ - origin, - codexConfigText: config, - fetchImpl: withSession({ - codexClient: true, - protocol: "responses", - clientHint: "curl/8.0", - upstream: "https://api.kourichat.com", - }), - }); - assert.equal(foreign.state, "configured"); + // A hint naming another client vetoes an otherwise Codex-shaped session. + const foreign = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: withSession({ + codexClient: true, + protocol: "responses", + clientHint: "curl/8.0", + upstream: "https://api.kourichat.com", + }), + }); + assert.equal(foreign.state, "configured"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } }); function fakeFetch(options: { - healthy: boolean; - codexObserved?: boolean; - codexAgeMs?: number; + healthy: boolean; + codexObserved?: boolean; + codexAgeMs?: number; }) { - return async (input: string | URL | Request): Promise => { - const url = String(input); - if (url.endsWith("/__bili/health")) - return Response.json( - { ok: options.healthy }, - { status: options.healthy ? 200 : 503 }, - ); - if (url.endsWith("/__bili/stats")) - return Response.json({ - sessions: options.codexObserved - ? [ - { - codexClient: true, - requests: 1, - lastSeenMs: Date.now() - (options.codexAgeMs ?? 0), - }, - ] - : [], - }); - return new Response("not found", { status: 404 }); - }; + return async (input: string | URL | Request): Promise => { + const url = String(input); + if (url.endsWith("/__bili/health")) + return Response.json( + { ok: options.healthy }, + { status: options.healthy ? 200 : 503 }, + ); + if (url.endsWith("/__bili/stats")) + return Response.json({ + sessions: options.codexObserved + ? [ + { + codexClient: true, + requests: 1, + lastSeenMs: Date.now() - (options.codexAgeMs ?? 0), + }, + ] + : [], + }); + return new Response("not found", { status: 404 }); + }; } test("Codex integration distinguishes proxy-ready, configured, verified, bypassed and unknown", async () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-status-")); - const file = path.join(home, "config.toml"); - const env = { ...process.env, CODEX_HOME: home }; - const origin = "http://127.0.0.1:18787"; - try { - const ready = await inspectCodexIntegration({ - env, - origin, - codexConfigText: "", - fetchImpl: fakeFetch({ healthy: true }), - }); - assert.equal(ready.state, "proxy-ready"); - const route = `${origin}/bili/https://api.openai.com/v1`; - const config = `openai_base_url = "${route}"\n`; - fs.writeFileSync(file, config); - writeCodexRouteRecord(codexRouteRecordPath(file), { - schemaVersion: 1, - writtenValue: route, - previousValue: null, - upstream: "https://api.openai.com/v1", - }); - const configured = await inspectCodexIntegration({ - env, - origin, - codexConfigText: config, - fetchImpl: fakeFetch({ healthy: true }), - }); - assert.equal(configured.state, "configured"); - const verified = await inspectCodexIntegration({ - env, - origin, - codexConfigText: config, - fetchImpl: fakeFetch({ healthy: true, codexObserved: true }), - }); - assert.equal(verified.state, "verified"); - const stale = await inspectCodexIntegration({ - env, - origin, - codexConfigText: config, - fetchImpl: fakeFetch({ - healthy: true, - codexObserved: true, - codexAgeMs: 25 * 60 * 60_000, - }), - }); - assert.equal( - stale.state, - "configured", - "old Codex sessions are not current route proof", - ); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-status-")); + const file = path.join(home, "config.toml"); + const env = { ...process.env, CODEX_HOME: home }; + const origin = "http://127.0.0.1:18787"; + try { + const ready = await inspectCodexIntegration({ + env, + origin, + codexConfigText: "", + fetchImpl: fakeFetch({ healthy: true }), + }); + assert.equal(ready.state, "proxy-ready"); + const route = `${origin}/bili/https://api.openai.com/v1`; + const config = `openai_base_url = "${route}"\n`; + fs.writeFileSync(file, config); + writeCodexRouteRecord(codexRouteRecordPath(file), { + schemaVersion: 1, + writtenValue: route, + previousValue: null, + upstream: "https://api.openai.com/v1", + }); + const configured = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: fakeFetch({ healthy: true }), + }); + assert.equal(configured.state, "configured"); + const verified = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: fakeFetch({ healthy: true, codexObserved: true }), + }); + assert.equal(verified.state, "verified"); + const stale = await inspectCodexIntegration({ + env, + origin, + codexConfigText: config, + fetchImpl: fakeFetch({ + healthy: true, + codexObserved: true, + codexAgeMs: 25 * 60 * 60_000, + }), + }); + assert.equal( + stale.state, + "configured", + "old Codex sessions are not current route proof", + ); - const bypassed = await inspectCodexIntegration({ - env, - origin, - codexConfigText: 'openai_base_url = "https://relay.example/v1"\n', - fetchImpl: fakeFetch({ healthy: true }), - }); - assert.equal(bypassed.state, "bypassed"); - const unknown = await inspectCodexIntegration({ - env, - origin, - codexConfigText: "", - fetchImpl: fakeFetch({ healthy: false }), - }); - assert.equal(unknown.state, "unknown"); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } + const bypassed = await inspectCodexIntegration({ + env, + origin, + codexConfigText: 'openai_base_url = "https://relay.example/v1"\n', + fetchImpl: fakeFetch({ healthy: true }), + }); + assert.equal(bypassed.state, "bypassed"); + const unknown = await inspectCodexIntegration({ + env, + origin, + codexConfigText: "", + fetchImpl: fakeFetch({ healthy: false }), + }); + assert.equal(unknown.state, "unknown"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } }); From 7075031026cc4ce3b98814896dc53cb199258eef Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 00:34:19 +0800 Subject: [PATCH 06/20] refactor: re-land codex install feature without formatting churn Rebuild src/plugin-install.ts, src/doctor.ts and the CLIENTS docs on the current master base carrying ONLY the functional diff of the codex integration (multi-face install/remove/status, doctor sections); the whole-file prettier-style reformatting of pre-existing lines is reverted so every changed line relates to this feature (#3176). Labeled minor fixes included: - drop the unused pathToFileURL import (dead in master) - readKimiInstalledRegistry: report corrupt JSON with file path and cause instead of a bare SyntaxError --- src/doctor.ts | 360 ++------- src/plugin-install.ts | 1560 ++++++++---------------------------- src/proxy-service/index.ts | 25 - 3 files changed, 394 insertions(+), 1551 deletions(-) delete mode 100644 src/proxy-service/index.ts diff --git a/src/doctor.ts b/src/doctor.ts index 9032dc0886..d2ff9e7f9a 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -7,41 +7,13 @@ import fs from "node:fs"; import path from "node:path"; import { isPidAlive, listInstances, procMainScript } from "./instance.js"; -import { - PLUGIN_AGENTS, - UPDATE_CHANNEL, - claudeDesktopPresent, - inspectLanePresence, - type PluginAgent, -} from "./plugin-install.js"; -import { - findInstallDir, - fetchRegistryVersion, - hostManagedInstall, - isGitWorkingTree, - isVersionNewer, - lastUpdateCheckTime, - normalizeUpdateTag, - staleInstallStatus, -} from "./update.js"; -import { - describeAdvisory, - evaluateAdvisories, - type AdvisoryEvaluation, -} from "./advisory.js"; +import { PLUGIN_AGENTS, UPDATE_CHANNEL, claudeDesktopPresent, inspectLanePresence, type PluginAgent } from "./plugin-install.js"; +import { findInstallDir, fetchRegistryVersion, hostManagedInstall, isGitWorkingTree, isVersionNewer, lastUpdateCheckTime, normalizeUpdateTag, staleInstallStatus } from "./update.js"; +import { describeAdvisory, evaluateAdvisories, type AdvisoryEvaluation } from "./advisory.js"; import { claudeRoutingWarningFile } from "./paths.js"; -import { - inspectCodexIntegration, - type CodexIntegrationReport, -} from "./codex-integration/status.js"; -import { - detectCcSwitch, - type CcSwitchDetection, -} from "./codex-integration/cc-switch.js"; -import { - chatGptDesktopCapability, - type ChatGptDesktopCapability, -} from "./codex-integration/chatgpt-capability.js"; +import { inspectCodexIntegration, type CodexIntegrationReport } from "./codex-integration/status.js"; +import { detectCcSwitch, type CcSwitchDetection } from "./codex-integration/cc-switch.js"; +import { chatGptDesktopCapability, type ChatGptDesktopCapability } from "./codex-integration/chatgpt-capability.js"; type LaneVerdict = "ok" | "stale" | "frozen" | "broken" | "absent"; @@ -112,22 +84,11 @@ interface LaneCtx { global: DoctorGlobalInfo; } -const REFERENCE_LANES = new Set([ - "omp", - "claude", - "codex", - "kimi", - "zcode", - "hermes", -]); +const REFERENCE_LANES = new Set(["omp", "claude", "codex", "kimi", "zcode", "hermes"]); function pkgVersionAt(rootDir: string): string | undefined { try { - const v = ( - JSON.parse( - fs.readFileSync(path.join(rootDir, "package.json"), "utf8"), - ) as { version?: unknown } - ).version; + const v = (JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8")) as { version?: unknown }).version; return typeof v === "string" ? v : undefined; } catch { return undefined; @@ -137,35 +98,17 @@ function pkgVersionAt(rootDir: string): string | undefined { /** Pure verdict logic (#1235): absent < broken < frozen < stale < ok. A * missing target beats a local pin because a dead entry means the host is * currently broken, not merely un-updatable. */ -export function laneVerdict(args: { - installed: boolean; - targetMissing: boolean; - frozen: boolean; - copyVersion?: string; - registryVersion?: string; -}): LaneVerdict { +export function laneVerdict(args: { installed: boolean; targetMissing: boolean; frozen: boolean; copyVersion?: string; registryVersion?: string }): LaneVerdict { if (!args.installed) return "absent"; if (args.targetMissing) return "broken"; if (args.frozen) return "frozen"; - if ( - args.copyVersion !== undefined && - args.registryVersion !== undefined && - isVersionNewer(args.registryVersion, args.copyVersion) - ) - return "stale"; + if (args.copyVersion !== undefined && args.registryVersion !== undefined && isVersionNewer(args.registryVersion, args.copyVersion)) return "stale"; return "ok"; } -export function globalVerdict( - g: Pick, -): LaneVerdict { +export function globalVerdict(g: Pick): LaneVerdict { if (g.form === "checkout") return "frozen"; - if ( - g.diskVersion !== undefined && - g.registryVersion !== undefined && - isVersionNewer(g.registryVersion, g.diskVersion) - ) - return "stale"; + if (g.diskVersion !== undefined && g.registryVersion !== undefined && isVersionNewer(g.registryVersion, g.diskVersion)) return "stale"; return "ok"; } @@ -181,18 +124,10 @@ export function dshBundleShadowWarning(args: { bundleInstalled: boolean; profileCopyVersion?: string; }): string | undefined { - if (!args.bundleInstalled || args.profileCopyVersion === undefined) - return undefined; + if (!args.bundleInstalled || args.profileCopyVersion === undefined) return undefined; if (args.globalInstallDir === undefined) return undefined; - if ( - args.globalDiskVersion !== undefined && - args.globalDiskVersion === args.profileCopyVersion - ) - return undefined; - const gv = - args.globalDiskVersion !== undefined - ? `v${args.globalDiskVersion}` - : "version unreadable"; + if (args.globalDiskVersion !== undefined && args.globalDiskVersion === args.profileCopyVersion) return undefined; + const gv = args.globalDiskVersion !== undefined ? `v${args.globalDiskVersion}` : "version unreadable"; return `shadowed copy: a machine-global ${args.packageName} (${args.globalInstallDir}, ${gv}) coexists with this profile's own copy (v${args.profileCopyVersion}); dsh resolves bare bundle names installation-anchor-first (#953/#1803) and loads whichever sits in its own install tree — with divergent versions you may be running a build different from what the profile declares (e.g. a pre-#1590 global lacks the dsh.client web face, so the settings-page menu silently vanishes). Verify which copy dsh actually loads: 'dsh --profile ${args.profileName} --dump-config' (read the bundle 'name:' line)`; } @@ -200,26 +135,13 @@ export async function runDoctor(opts: DoctorOpts): Promise { const tag = normalizeUpdateTag(opts.updateTag); const [installDir, registryVersion, lastCheck] = await Promise.all([ findInstallDir(opts.packageName), - fetchRegistryVersion( - { resolveProxy: opts.resolveProxy, updateTag: tag }, - opts.packageName, - ).catch(() => undefined), + fetchRegistryVersion({ resolveProxy: opts.resolveProxy, updateTag: tag }, opts.packageName).catch(() => undefined), lastUpdateCheckTime(), ]); - const gitTree = - installDir !== undefined ? await isGitWorkingTree(installDir) : false; - const managed = - installDir !== undefined ? hostManagedInstall(installDir) : undefined; - const diskVersion = - installDir !== undefined ? pkgVersionAt(installDir) : undefined; - const form: DoctorGlobalInfo["form"] = - installDir === undefined - ? "unknown" - : gitTree - ? "checkout" - : managed !== undefined - ? "host-managed" - : "npm"; + const gitTree = installDir !== undefined ? await isGitWorkingTree(installDir) : false; + const managed = installDir !== undefined ? hostManagedInstall(installDir) : undefined; + const diskVersion = installDir !== undefined ? pkgVersionAt(installDir) : undefined; + const form: DoctorGlobalInfo["form"] = installDir === undefined ? "unknown" : gitTree ? "checkout" : managed !== undefined ? "host-managed" : "npm"; // #1577: read-only advisory check against the on-disk version (what a next // start would load), independent of the advisoryCheck opt-out — doctor is a // diagnostic, not the auto-updater. Fail-open: a failed source yields @@ -242,33 +164,15 @@ export async function runDoctor(opts: DoctorOpts): Promise { verdict: globalVerdict({ form, diskVersion, registryVersion }), advisory, }; - if (g.verdict === "frozen") - g.reason = - "source checkout — rebuild manually (npm run build); bili refuses to auto-update a working tree (#580)"; - else if (g.verdict === "stale") - g.reason = - managed !== undefined - ? `newer on registry ${tag}: update through ${managed.owner}'s updater` - : `newer on registry ${tag}: run 'bili update'`; - else if ( - form !== "unknown" && - staleInstallStatus(diskVersion, opts.runningVersion) === "restart" - ) - g.reason = `running process is behind the on-disk install (v${opts.runningVersion} → v${diskVersion}) — restart bili`; - if (registryVersion === undefined) - g.reason = g.reason - ? `${g.reason}; registry unreachable — freshness unknown` - : "registry unreachable — freshness unknown"; + if (g.verdict === "frozen") g.reason = "source checkout — rebuild manually (npm run build); bili refuses to auto-update a working tree (#580)"; + else if (g.verdict === "stale") g.reason = managed !== undefined ? `newer on registry ${tag}: update through ${managed.owner}'s updater` : `newer on registry ${tag}: run 'bili update'`; + else if (form !== "unknown" && staleInstallStatus(diskVersion, opts.runningVersion) === "restart") g.reason = `running process is behind the on-disk install (v${opts.runningVersion} → v${diskVersion}) — restart bili`; + if (registryVersion === undefined) g.reason = g.reason ? `${g.reason}; registry unreachable — freshness unknown` : "registry unreachable — freshness unknown"; const lanes: DoctorLane[] = []; for (const agent of PLUGIN_AGENTS) { try { - lanes.push( - ...laneRowsFor(agent, inspectLanePresence(agent), registryVersion, { - packageName: opts.packageName, - global: g, - }), - ); + lanes.push(...laneRowsFor(agent, inspectLanePresence(agent), registryVersion, { packageName: opts.packageName, global: g })); } catch (err) { lanes.push({ agent, @@ -292,44 +196,18 @@ export async function runDoctor(opts: DoctorOpts): Promise { startedAt: e.startedAt, alive, runningFrom, - staleCopy: - runningFrom !== undefined && - installDir !== undefined && - !runningFrom.startsWith(installDir + path.sep), + staleCopy: runningFrom !== undefined && installDir !== undefined && !runningFrom.startsWith(installDir + path.sep), }; }); const codexIntegration = await inspectCodexIntegration(); const ccSwitch = detectCcSwitch(); - return { - generatedAt: Date.now(), - packageName: opts.packageName, - global: g, - lanes, - processes, - codexIntegration, - ccSwitch, - chatGptDesktop: chatGptDesktopCapability, - }; + return { generatedAt: Date.now(), packageName: opts.packageName, global: g, lanes, processes, codexIntegration, ccSwitch, chatGptDesktop: chatGptDesktopCapability }; } -function laneRowsFor( - agent: PluginAgent, - presence: ReturnType, - registryVersion: string | undefined, - ctx: LaneCtx, -): DoctorLane[] { +function laneRowsFor(agent: PluginAgent, presence: ReturnType, registryVersion: string | undefined, ctx: LaneCtx): DoctorLane[] { const kind = REFERENCE_LANES.has(agent) ? "reference" : "host-managed"; - const base: Omit< - DoctorLane, - | "agent" - | "installed" - | "detail" - | "targetExists" - | "copyVersion" - | "verdict" - | "reason" - > = { + const base: Omit = { kind, registryVersion, channel: UPDATE_CHANNEL[agent], @@ -341,55 +219,21 @@ function laneRowsFor( ...base, agent: `dsh:${p.name}`, installed: true, - detail: - p.spec !== undefined - ? `dep spec: ${p.spec}${p.pinned ? " (local pin — dev lane, manual)" : ""}` - : "(no dep spec)", - copyVersion: p.copyVersion, - verdict: laneVerdict({ - installed: true, - targetMissing: missing, - frozen: p.pinned, + detail: p.spec !== undefined ? `dep spec: ${p.spec}${p.pinned ? " (local pin — dev lane, manual)" : ""}` : "(no dep spec)", copyVersion: p.copyVersion, - registryVersion, - }), + verdict: laneVerdict({ installed: true, targetMissing: missing, frozen: p.pinned, copyVersion: p.copyVersion, registryVersion }), }; - if (row.verdict === "frozen") - row.reason = - "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)"; - else if (row.verdict === "broken") - row.reason = - "profile depends on billion-context but the bundle copy is missing — rerun 'bili plugin install dsh'"; - const shadow = dshBundleShadowWarning({ - packageName: ctx.packageName, - globalInstallDir: ctx.global.installDir, - globalDiskVersion: ctx.global.diskVersion, - profileName: p.name, - bundleInstalled: p.bundleInstalled, - profileCopyVersion: p.copyVersion, - }); - if (shadow !== undefined) - row.warnings = [...(row.warnings ?? []), shadow]; + if (row.verdict === "frozen") row.reason = "local-pin dep spec — no live update path; point it at a registry version or rebuild manually (AGENTS.md install-lane contract)"; + else if (row.verdict === "broken") row.reason = "profile depends on billion-context but the bundle copy is missing — rerun 'bili plugin install dsh'"; + const shadow = dshBundleShadowWarning({ packageName: ctx.packageName, globalInstallDir: ctx.global.installDir, globalDiskVersion: ctx.global.diskVersion, profileName: p.name, bundleInstalled: p.bundleInstalled, profileCopyVersion: p.copyVersion }); + if (shadow !== undefined) row.warnings = [...(row.warnings ?? []), shadow]; return row; }); } - const targetsExist = - presence.targets.length > 0 - ? presence.targets.every((t) => fs.existsSync(t)) - : undefined; + const targetsExist = presence.targets.length > 0 ? presence.targets.every((t) => fs.existsSync(t)) : undefined; const missingTargets = presence.targets.filter((t) => !fs.existsSync(t)); - let detail = - presence.pointers.length > 0 - ? presence.pointers.join("; ") - : presence.installed - ? "installed" - : "not installed"; - if ( - agent === "pi" && - presence.form === "npm" && - presence.targets.length === 0 - ) - detail += "; pi materializes the npm copy on next startup"; + let detail = presence.pointers.length > 0 ? presence.pointers.join("; ") : presence.installed ? "installed" : "not installed"; + if (agent === "pi" && presence.form === "npm" && presence.targets.length === 0) detail += "; pi materializes the npm copy on next startup"; const row: DoctorLane = { ...base, agent, @@ -397,24 +241,15 @@ function laneRowsFor( detail, targetExists: targetsExist, copyVersion: presence.copyVersion, - verdict: laneVerdict({ - installed: presence.installed, - targetMissing: missingTargets.length > 0, - frozen: false, - copyVersion: presence.copyVersion, - registryVersion, - }), + verdict: laneVerdict({ installed: presence.installed, targetMissing: missingTargets.length > 0, frozen: false, copyVersion: presence.copyVersion, registryVersion }), }; - if (row.verdict === "broken") - row.reason = missingTargets.map((t) => `target missing: ${t}`).join("; "); + if (row.verdict === "broken") row.reason = missingTargets.map((t) => `target missing: ${t}`).join("; "); if (agent === "opencode" && presence.installed && presence.form === "npm") { // #1234/#2199: the cache copy is bili-owned in place (self-updates via its // own proxy) — show the actual load path + disk version when resolvable so // the stale verdict below is honest, not "version not resolvable". - const cp = - presence.copyVersion !== undefined ? ` v${presence.copyVersion}` : ""; - const p = - presence.targets[0] !== undefined ? ` (${presence.targets[0]})` : ""; + const cp = presence.copyVersion !== undefined ? ` v${presence.copyVersion}` : ""; + const p = presence.targets[0] !== undefined ? ` (${presence.targets[0]})` : ""; row.detail += `; cache copy${p}${cp} is bili-owned and self-updates in place via its own proxy (#1234) — reload/restart OpenCode to activate a disk update`; } if (agent === "claude" && presence.installed) { @@ -425,26 +260,13 @@ function laneRowsFor( // hook-detected bypass (its stderr is invisible outside debug mode). const warnings: string[] = []; if (claudeDesktopPresent()) { - warnings.push( - "Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL, so desktop sessions bypass bili entirely AND lose native auto-compact (managed block sets DISABLE_AUTO_COMPACT=1) — #2290", - ); + warnings.push("Claude Desktop detected on this machine: its Code tab overrides ANTHROPIC_BASE_URL, so desktop sessions bypass bili entirely AND lose native auto-compact (managed block sets DISABLE_AUTO_COMPACT=1) — #2290"); } try { - const rec = JSON.parse( - fs.readFileSync(claudeRoutingWarningFile(), "utf8"), - ) as { at?: unknown; reasons?: unknown }; - if ( - Array.isArray(rec.reasons) && - rec.reasons.length > 0 && - rec.reasons.every((r) => typeof r === "string") - ) { - const at = - typeof rec.at === "number" - ? ` at ${new Date(rec.at).toISOString()}` - : ""; - warnings.push( - `last SessionStart hook detected a routing bypass${at}: ${(rec.reasons as string[]).join("; ")}`, - ); + const rec = JSON.parse(fs.readFileSync(claudeRoutingWarningFile(), "utf8")) as { at?: unknown; reasons?: unknown }; + if (Array.isArray(rec.reasons) && rec.reasons.length > 0 && rec.reasons.every((r) => typeof r === "string")) { + const at = typeof rec.at === "number" ? ` at ${new Date(rec.at).toISOString()}` : ""; + warnings.push(`last SessionStart hook detected a routing bypass${at}: ${(rec.reasons as string[]).join("; ")}`); } } catch { // no marker or unreadable — nothing to surface @@ -458,48 +280,24 @@ function fmtTime(ts: number): string { return new Date(ts).toISOString(); } -function verdictText( - v: LaneVerdict, - row: { oldVersion?: string; registryVersion?: string }, -): string { - if ( - v === "stale" && - row.oldVersion !== undefined && - row.registryVersion !== undefined - ) - return `stale (v${row.oldVersion} → v${row.registryVersion})`; +function verdictText(v: LaneVerdict, row: { oldVersion?: string; registryVersion?: string }): string { + if (v === "stale" && row.oldVersion !== undefined && row.registryVersion !== undefined) return `stale (v${row.oldVersion} → v${row.registryVersion})`; return v; } export function renderDoctorReport(report: DoctorReport): string { const lines: string[] = []; const g = report.global; - lines.push( - `bili doctor — ${report.packageName} (running v${g.runningVersion})`, - ); + lines.push(`bili doctor — ${report.packageName} (running v${g.runningVersion})`); lines.push(`generated ${fmtTime(report.generatedAt)}`); lines.push(""); lines.push("global"); - lines.push( - ` form ${g.form}${g.owner !== undefined ? ` (owned by ${g.owner})` : ""}${g.installDir !== undefined ? ` — ${g.installDir}` : " — install dir not found"}`, - ); - lines.push( - ` versions disk ${g.diskVersion ?? "?"} registry[${g.updateTag}] ${g.registryVersion ?? "unreachable"}`, - ); - lines.push( - ` last check ${g.lastCheckTime !== undefined ? fmtTime(g.lastCheckTime) : "never"}`, - ); - lines.push( - ` verdict ${verdictText(g.verdict, { oldVersion: g.diskVersion, registryVersion: g.registryVersion })}${g.reason !== undefined ? ` — ${g.reason}` : ""}`, - ); - if (g.advisory?.active !== undefined) - lines.push( - ` advisory ⚠️ ${describeAdvisory(g.advisory.active, g.advisory.error)}`, - ); - else if (g.advisory?.error !== undefined) - lines.push( - ` advisory check failed (${g.advisory.error}) — status unknown`, - ); + lines.push(` form ${g.form}${g.owner !== undefined ? ` (owned by ${g.owner})` : ""}${g.installDir !== undefined ? ` — ${g.installDir}` : " — install dir not found"}`); + lines.push(` versions disk ${g.diskVersion ?? "?"} registry[${g.updateTag}] ${g.registryVersion ?? "unreachable"}`); + lines.push(` last check ${g.lastCheckTime !== undefined ? fmtTime(g.lastCheckTime) : "never"}`); + lines.push(` verdict ${verdictText(g.verdict, { oldVersion: g.diskVersion, registryVersion: g.registryVersion })}${g.reason !== undefined ? ` — ${g.reason}` : ""}`); + if (g.advisory?.active !== undefined) lines.push(` advisory ⚠️ ${describeAdvisory(g.advisory.active, g.advisory.error)}`); + else if (g.advisory?.error !== undefined) lines.push(` advisory check failed (${g.advisory.error}) — status unknown`); else lines.push(` advisory none`); lines.push(""); lines.push("lanes"); @@ -507,25 +305,16 @@ export function renderDoctorReport(report: DoctorReport): string { const head = ` ${lane.agent.padEnd(12)} ${verdictText(lane.verdict, { oldVersion: lane.copyVersion, registryVersion: lane.registryVersion }).padEnd(34)} ${lane.kind}`; lines.push(head); lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.detail}`); - if (lane.channel !== undefined && lane.installed) - lines.push( - ` ${"".padEnd(12)} ${"".padEnd(34)} updates via: ${lane.channel}`, - ); - if (lane.reason !== undefined) - lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.reason}`); - for (const w of lane.warnings ?? []) - lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ⚠️ ${w}`); + if (lane.channel !== undefined && lane.installed) lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} updates via: ${lane.channel}`); + if (lane.reason !== undefined) lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ${lane.reason}`); + for (const w of lane.warnings ?? []) lines.push(` ${"".padEnd(12)} ${"".padEnd(34)} ⚠️ ${w}`); } lines.push(""); lines.push("codex model route"); lines.push(` state ${report.codexIntegration.state}`); lines.push(` route ${report.codexIntegration.route}`); - lines.push( - ` proxy ${report.codexIntegration.proxyHealthy ? "healthy" : "not verified"}`, - ); - lines.push( - ` evidence ${report.codexIntegration.observedCodexRequest ? "Codex request observed" : "no Codex model request observed"}`, - ); + lines.push(` proxy ${report.codexIntegration.proxyHealthy ? "healthy" : "not verified"}`); + lines.push(` evidence ${report.codexIntegration.observedCodexRequest ? "Codex request observed" : "no Codex model request observed"}`); lines.push(` detail ${report.codexIntegration.detail}`); lines.push(""); lines.push("CC Switch"); @@ -545,32 +334,15 @@ export function renderDoctorReport(report: DoctorReport): string { lines.push(" none registered"); } else { for (const p of report.processes) { - const state = p.alive - ? p.staleCopy - ? "STALE COPY" - : "running" - : "zombie (process gone, marker left behind)"; - lines.push( - ` pid ${String(p.pid).padEnd(7)} port ${String(p.port).padEnd(6)} ${p.origin} ${state}`, - ); - if (p.runningFrom !== undefined) - lines.push( - ` ${"".padEnd(12)} runs from ${p.runningFrom}${p.staleCopy ? " (not the current install dir)" : ""}`, - ); + const state = p.alive ? (p.staleCopy ? "STALE COPY" : "running") : "zombie (process gone, marker left behind)"; + lines.push(` pid ${String(p.pid).padEnd(7)} port ${String(p.port).padEnd(6)} ${p.origin} ${state}`); + if (p.runningFrom !== undefined) lines.push(` ${"".padEnd(12)} runs from ${p.runningFrom}${p.staleCopy ? " (not the current install dir)" : ""}`); } } - const counts: Record = { - ok: 0, - stale: 0, - frozen: 0, - broken: 0, - absent: 0, - }; + const counts: Record = { ok: 0, stale: 0, frozen: 0, broken: 0, absent: 0 }; for (const l of report.lanes) counts[l.verdict]++; const zombies = report.processes.filter((p) => !p.alive).length; lines.push(""); - lines.push( - `summary: ${counts.ok} ok, ${counts.stale} stale, ${counts.frozen} frozen, ${counts.broken} broken, ${counts.absent} absent; processes: ${report.processes.length - zombies} live, ${zombies} zombie`, - ); + lines.push(`summary: ${counts.ok} ok, ${counts.stale} stale, ${counts.frozen} frozen, ${counts.broken} broken, ${counts.absent} absent; processes: ${report.processes.length - zombies} live, ${zombies} zombie`); return lines.join("\n") + "\n"; } diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 701af3f3fa..f28dca5bcf 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -6,14 +6,6 @@ // pi ~/.pi/agent/settings.json packages: [] // omp ~/.omp/agent/config.yml extensions: [/dist/agent/omp-native.js] // claude `claude mcp add` (user scope; writes ~/.claude.json) -// opencode /opencode.json{c}|config.json (highest-precedence existing; #927) -// mcp.bili + native plugin dir + compaction.auto=false -// (plugin entry #925: bare "billion-context" for npm installs — opencode -// loads it via exports["./server"] and manages install/upgrade itself; -// local shim dir for checkout/dev installs, which are not portable) -// dsh no file of its own — drives dsh's own plugin channel per profile -// (`dsh plugin --profile add|remove`, #966); profile copies -// follow global self-updates via dsh-channel.refreshDshProfileBundles // codex ~/.codex/config.toml [mcp_servers.bili] (stdio MCP) + the // bili-owned model route (top-level `openai_base_url`, or the active // provider's `base_url` under CC Switch Direct; sidecar-recorded @@ -22,6 +14,14 @@ // to ~/.codex/skills/bili/SKILL.md. MCP, route, hook and skill are // reported SEPARATELY: MCP proves tools, never that model traffic is // compressed. +// opencode /opencode.json{c}|config.json (highest-precedence existing; #927) +// mcp.bili + native plugin dir + compaction.auto=false +// (plugin entry #925: bare "billion-context" for npm installs — opencode +// loads it via exports["./server"] and manages install/upgrade itself; +// local shim dir for checkout/dev installs, which are not portable) +// dsh no file of its own — drives dsh's own plugin channel per profile +// (`dsh plugin --profile add|remove`, #966); profile copies +// follow global self-updates via dsh-channel.refreshDshProfileBundles // kimi $KIMI_CODE_HOME/plugins/managed/billion-context/kimi.plugin.json // + installed.json record (stdio MCP + SessionStart hook; config.toml // routing happens per-session, see src/kimi/) @@ -42,68 +42,21 @@ import os from "node:os"; import crypto from "node:crypto"; import { execFileSync, spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; -import { - applyEdits, - modify as jsoncModify, - parse as jsoncParse, - type ParseError, -} from "jsonc-parser"; -import { - parseCodexToml, - resolveDshHome, - resolveHermesHome, - resolveKimiHome, - resolvePiHome, -} from "./client-config.js"; +import { applyEdits, modify as jsoncModify, parse as jsoncParse, type ParseError } from "jsonc-parser"; +import { parseCodexToml, resolveDshHome, resolveHermesHome, resolveKimiHome, resolvePiHome } from "./client-config.js"; import { resolveClaudeNativePort } from "./config.js"; import { lanePreferredPort, readProxyInstanceFile } from "./instance.js"; -import { - DSH_PACKAGE, - dshBundleInstalled, - dshHasLegacyManagedBlock, - dshProfileDependsOnBili, - dshProfileDepSpec, - dshProfileDirs, - isRegistryDepSpec, - planDshSpawn, - refreshDshProfileBundles, - runDshPlugin, - stripLegacyManagedBlock, -} from "./dsh-channel.js"; +import { DSH_PACKAGE, dshBundleInstalled, dshHasLegacyManagedBlock, dshProfileDependsOnBili, dshProfileDepSpec, dshProfileDirs, isRegistryDepSpec, planDshSpawn, refreshDshProfileBundles, runDshPlugin, stripLegacyManagedBlock } from "./dsh-channel.js"; import { piNpmCopyRoot } from "./pi-channel.js"; import { clearOwnerLaneBackoff, fetchRegistryVersion } from "./update.js"; import { detectCcSwitch } from "./codex-integration/cc-switch.js"; -import { - assertCodexConfigLoads, - codexHooksEnabledNote, - findBiliCodexHook, - planCodexHook, - stripCodexHook, -} from "./codex-integration/hooks.js"; -import { - codexSkillFile, - codexSkillStatus, - installCodexSkill, - removeCodexSkill, -} from "./codex-integration/skill.js"; -import { - codexRouteOrigin, - desiredCodexRoute, - planCodexRoute, - readCodexRoute, - readCodexRouteRecord, - removeCodexRouteRecord, - restoreCodexRoute, - codexRouteRecordPath, - writeCodexRouteRecord, -} from "./codex-integration/route.js"; +import { assertCodexConfigLoads, codexHooksEnabledNote, findBiliCodexHook, planCodexHook, stripCodexHook } from "./codex-integration/hooks.js"; +import { codexSkillFile, codexSkillStatus, installCodexSkill, removeCodexSkill } from "./codex-integration/skill.js"; +import { codexRouteOrigin, desiredCodexRoute, planCodexRoute, readCodexRoute, readCodexRouteRecord, removeCodexRouteRecord, restoreCodexRoute, codexRouteRecordPath, writeCodexRouteRecord } from "./codex-integration/route.js"; import { restoreKimiBackup, unrouteKimi } from "./kimi/native.js"; import { inspectZcodeRouting, resolveZcodeDataDir } from "./zcode/json-edit.js"; import { restoreZcodeBackup, unrouteZcode } from "./zcode/native.js"; -import { - installProxyService, - removeProxyService, -} from "./proxy-service/service.js"; +import { installProxyService, removeProxyService } from "./proxy-service/service.js"; /** Build a SessionStart hook command line that parses in every shell the * supported agents run hooks through. Two Windows traps, both measured on @@ -140,22 +93,10 @@ export function portableHookCommand(exe: string, args: string[] = []): string { const quoteArg = (p: string): string => (/\s/.test(p) ? `"${p}"` : p); const head = fwd(exe); const tail = args.map((a) => quoteArg(fwd(a))); - return /\s/.test(head) - ? [`& "${head}"`, ...tail].join(" ") - : [head, ...tail].join(" "); -} - -export const PLUGIN_AGENTS = [ - "pi", - "omp", - "claude", - "codex", - "opencode", - "dsh", - "kimi", - "hermes", - "zcode", -] as const; + return /\s/.test(head) ? [`& "${head}"`, ...tail].join(" ") : [head, ...tail].join(" "); +} + +export const PLUGIN_AGENTS = ["pi", "omp", "claude", "codex", "opencode", "dsh", "kimi", "hermes", "zcode"] as const; export type PluginAgent = (typeof PLUGIN_AGENTS)[number]; export function selfPackageRoot(): string { @@ -165,9 +106,7 @@ export function selfPackageRoot(): string { } function homeFile(rel: string, envOverride?: string): string { - const raw = ( - envOverride !== undefined ? process.env[envOverride] : undefined - )?.trim(); + const raw = (envOverride !== undefined ? process.env[envOverride] : undefined)?.trim(); const base = raw && raw.length > 0 ? raw : os.homedir(); return path.join(base, rel); } @@ -225,14 +164,10 @@ function readJson(file: string): Record { try { parsed = JSON.parse(text); } catch (err) { - throw new Error( - `${file}: not valid JSON (${err instanceof Error ? err.message : String(err)}) — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`, - ); + throw new Error(`${file}: not valid JSON (${err instanceof Error ? err.message : String(err)}) — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`); } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { - throw new Error( - `${file}: expected a JSON object at top level, refusing to overwrite`, - ); + throw new Error(`${file}: expected a JSON object at top level, refusing to overwrite`); } return parsed as Record; } @@ -243,9 +178,7 @@ function writeJson(file: string, data: unknown): void { function requireDistFile(file: string): void { if (!fs.existsSync(file)) { - process.stderr.write( - `bili plugin: warning: ${file} does not exist yet (run \`npm run build\` in ${selfPackageRoot()}) — the entry will be dead until built\n`, - ); + process.stderr.write(`bili plugin: warning: ${file} does not exist yet (run \`npm run build\` in ${selfPackageRoot()}) — the entry will be dead until built\n`); } } @@ -262,12 +195,10 @@ function piSettingsFile(): string { // plugin moved into billion-context itself). install() replaces every match // so exactly one bili plugin is live after `bili plugin install pi`. export function isPiEntry(entry: string, root: string): boolean { - return ( - entry === root || - /^npm:billion-context(-pi)?(@|$)/.test(entry) || - /(^|[/\\])node_modules[/\\]billion-context(-pi)?([/\\]|$)/.test(entry) || - /(^|[/\\])billion-context(-pi)?$/.test(entry) - ); + return entry === root + || /^npm:billion-context(-pi)?(@|$)/.test(entry) + || /(^|[/\\])node_modules[/\\]billion-context(-pi)?([\/\\]|$)/.test(entry) + || /(^|[/\\])billion-context(-pi)?$/.test(entry); } // Entries that load THIS package's pi plugin (billion-context proper). @@ -276,12 +207,10 @@ export function isPiEntry(entry: string, root: string): boolean { // BILLION_CONTEXT_PROXY — so treating it as "installed" wrongly suppressed // the launcher's `-e` fallback and left pi with no plugin at all. export function isBiliPiEntry(entry: string, root: string): boolean { - return ( - entry === root || - /^npm:billion-context(@|$)/.test(entry) || - /(^|[/\\])node_modules[/\\]billion-context([/\\]|$)/.test(entry) || - /(^|[/\\])billion-context$/.test(entry) - ); + return entry === root + || /^npm:billion-context(@|$)/.test(entry) + || /(^|[/\\])node_modules[/\\]billion-context([\/\\]|$)/.test(entry) + || /(^|[/\\])billion-context$/.test(entry); } // #925 pi form of the npm-standard entry: for npm installs (package root @@ -327,15 +256,11 @@ function piInstall(): string { // idea their config changed. Project-scope reminder mirrors the opencode // installer's LOCAL-scope note: a `pi install -l` entry lives in // /.pi/settings.json, which this global strip never touches. - const note = - removed.length > 0 - ? `\npi: replaced existing entries: ${removed.join(", ")}` + - "\npi: also check /.pi/settings.json — a project-scope billion-context-pi entry (pi install -l) lives there, not in this global settings" - : ""; - const form = - entry === PI_NPM_ENTRY - ? " (pi-managed — pi installs it; the proxy self-refreshes it via `pi update --extension npm:billion-context`, or run that manually)" + const note = removed.length > 0 + ? `\npi: replaced existing entries: ${removed.join(", ")}` + + "\npi: also check /.pi/settings.json — a project-scope billion-context-pi entry (pi install -l) lives there, not in this global settings" : ""; + const form = entry === PI_NPM_ENTRY ? " (pi-managed — pi installs it; the proxy self-refreshes it via `pi update --extension npm:billion-context`, or run that manually)" : ""; return `pi: installed -> ${file} packages += ${entry}${form}${note}`; } @@ -357,9 +282,7 @@ function piStatus(): string { const list = piPackageStrings(readJson(piSettingsFile()).packages); // Any entry that loads THIS package's plugin counts (npm: form or abs // root); the legacy billion-context-pi package deliberately does not. - return list.some((p) => isBiliPiEntry(p, root) || p === piEntryFor(root)) - ? "installed" - : "not installed"; + return list.some((p) => isBiliPiEntry(p, root) || p === piEntryFor(root)) ? "installed" : "not installed"; } // — omp ——————————————————————————————————————————————————————————————— @@ -423,12 +346,7 @@ function ompExtensionPath(): string { } function ompEntryValue(line: string): string { - return line - .replace(/#.*$/, "") - .trim() - .replace(/^-\s*/, "") - .replace(/^["']|["']$/g, "") - .trim(); + return line.replace(/#.*$/, "").trim().replace(/^-\s*/, "").replace(/^["']|["']$/g, "").trim(); } // A bili omp entry that actually loads: matches our entry shape AND the target @@ -443,9 +361,7 @@ function ompRemove(): string { const text = fs.readFileSync(file, "utf8"); const lines = text.split("\n"); const drop = new Set( - ompExtensionItemLines(text).filter((i) => - OMP_ENTRY_RE.test(ompEntryValue(lines[i]!)), - ), + ompExtensionItemLines(text).filter((i) => OMP_ENTRY_RE.test(ompEntryValue(lines[i]!))), ); if (drop.size === 0) return `omp: not installed (${file})`; const cleaned = lines.filter((_, i) => !drop.has(i)).join("\n"); @@ -463,7 +379,7 @@ function ompInstall(): string { // Any other bili entry — pre-#957 thin dist/agent/omp.js installs or stale // duplicates — is dropped and replaced by the insert below, so an old // install upgrades to native mode on re-install. - const replaced: string[] = []; + let replaced: string[] = []; { const lines = text.split("\n"); const ours = new Set(); @@ -473,23 +389,15 @@ function ompInstall(): string { ours.add(i); if (v !== entry) replaced.push(v); } - if ( - ours.size === 1 && - [...ours].every((i) => ompEntryValue(lines[i]!) === entry) - ) { + if (ours.size === 1 && [...ours].every((i) => ompEntryValue(lines[i]!) === entry)) { return `omp: already installed (${file})`; } if (ours.size > 0) text = lines.filter((_, i) => !ours.has(i)).join("\n"); } const keyCount = (text.match(/^extensions:/gm) ?? []).length; - if (keyCount > 1) - throw new Error( - `${file}: multiple \`extensions:\` keys — fix the file first, refusing to edit`, - ); + if (keyCount > 1) throw new Error(`${file}: multiple \`extensions:\` keys — fix the file first, refusing to edit`); if (/^extensions:\s*\S/m.test(text) && !/^extensions:\s*$/m.test(text)) { - throw new Error( - `${file}: \`extensions:\` uses flow style or an inline value; convert it to a block list first, refusing to edit`, - ); + throw new Error(`${file}: \`extensions:\` uses flow style or an inline value; convert it to a block list first, refusing to edit`); } let out: string; const extMatch = /^extensions:\s*$/m.exec(text); @@ -513,13 +421,9 @@ function ompInstall(): string { out += `extensions:\n - ${entry}\n`; } const outLines = out.split("\n"); - const occurrences = ompExtensionItemLines(out).filter( - (i) => ompEntryValue(outLines[i]!) === entry, - ).length; + const occurrences = ompExtensionItemLines(out).filter((i) => ompEntryValue(outLines[i]!) === entry).length; if (occurrences !== 1) { - throw new Error( - `${file}: edit would leave ${occurrences} copies of the entry — aborting without writing`, - ); + throw new Error(`${file}: edit would leave ${occurrences} copies of the entry — aborting without writing`); } backupBeforeWrite(file); fs.writeFileSync(file, out); @@ -555,9 +459,7 @@ export function ompPluginLoadedFrom(ompHome: string): boolean { try { const text = fs.readFileSync(path.join(ompHome, "config.yml"), "utf8"); const lines = text.split("\n"); - return ompExtensionItemLines(text).some((i) => - ompEntryLoadable(ompEntryValue(lines[i]!)), - ); + return ompExtensionItemLines(text).some((i) => ompEntryLoadable(ompEntryValue(lines[i]!))); } catch { return false; } @@ -575,9 +477,7 @@ function claudeMcpJson(): string { * whole ~/.claude directory when it is set). The #964 managed block lives * here — env.ANTHROPIC_BASE_URL / env.DISABLE_AUTO_COMPACT / * hooks.SessionStart. */ -export function claudeSettingsFile( - env: NodeJS.ProcessEnv = process.env, -): string { +export function claudeSettingsFile(env: NodeJS.ProcessEnv = process.env): string { const raw = env.CLAUDE_CONFIG_DIR?.trim(); const base = raw && raw.length > 0 ? raw : path.join(os.homedir(), ".claude"); return path.join(base, "settings.json"); @@ -599,14 +499,8 @@ Arguments: $ARGUMENTS /** /commands/acp-cache.md (claude replaces the * whole directory when CLAUDE_CONFIG_DIR is set — same rule as settings.json). */ -export function claudeAcpCacheCommandFile( - env: NodeJS.ProcessEnv = process.env, -): string { - return path.join( - path.dirname(claudeSettingsFile(env)), - "commands", - "acp-cache.md", - ); +export function claudeAcpCacheCommandFile(env: NodeJS.ProcessEnv = process.env): string { + return path.join(path.dirname(claudeSettingsFile(env)), "commands", "acp-cache.md"); } /** True for an ANTHROPIC_BASE_URL value written by a bili managed block: @@ -624,14 +518,7 @@ export function isBiliClaudeBaseUrl(value: unknown): boolean { * install locations only (portable installs exist), so callers treat a hit * as an advisory input and a miss as absence-of-evidence, never an error. * Injectable for tests. */ -export function claudeDesktopPresent( - opts: { - platform?: string; - localAppData?: string; - home?: string; - appRoots?: string[]; - } = {}, -): boolean { +export function claudeDesktopPresent(opts: { platform?: string; localAppData?: string; home?: string; appRoots?: string[] } = {}): boolean { const platform = opts.platform ?? process.platform; const home = opts.home ?? os.homedir(); if (platform === "win32") { @@ -641,16 +528,12 @@ export function claudeDesktopPresent( } if (platform === "darwin") { const roots = opts.appRoots ?? ["/Applications"]; - return [...roots, path.join(home, "Applications")].some((r) => - fs.existsSync(path.join(r, "Claude.app")), - ); + return [...roots, path.join(home, "Applications")].some((r) => fs.existsSync(path.join(r, "Claude.app"))); } return false; } -export function claudeNativeBaseUrl( - env: NodeJS.ProcessEnv = process.env, -): string { +export function claudeNativeBaseUrl(env: NodeJS.ProcessEnv = process.env): string { const origin = `http://127.0.0.1:${resolveClaudeNativePort(env) ?? lanePreferredPort("claude", env)}`; return claudeNativeBaseUrlForOrigin(origin, undefined, env); } @@ -661,19 +544,13 @@ export function claudeNativeBaseUrl( * resolution (BILI_CLAUDE_UPSTREAM > https://api.anthropic.com) — pass the * UNWRAPPED value of the current settings URL to preserve a relay an * earlier install baked in. */ -export function claudeNativeBaseUrlForOrigin( - origin: string, - upstream: string | undefined, - env: NodeJS.ProcessEnv = process.env, -): string { +export function claudeNativeBaseUrlForOrigin(origin: string, upstream: string | undefined, env: NodeJS.ProcessEnv = process.env): string { const relay = env.BILI_CLAUDE_UPSTREAM?.trim(); - const base = ( - upstream !== undefined && upstream.length > 0 + const base = (upstream !== undefined && upstream.length > 0 ? upstream : relay && relay.length > 0 ? relay - : "https://api.anthropic.com" - ).replace(/\/+$/, ""); + : "https://api.anthropic.com").replace(/\/+$/, ""); const prefix = origin.replace(/\/+$/, "") + "/bili/"; return base.startsWith(prefix) ? base : prefix + base; } @@ -681,9 +558,7 @@ export function claudeNativeBaseUrlForOrigin( /** The inverse of the wrap: strip a bili wrapper (any loopback port) from a * base URL. Returns undefined for anything not written by us. */ export function unwrapBiliBaseUrl(value: string): string | undefined { - const m = /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/(https?:\/\/.+)$/.exec( - value, - ); + const m = /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/(https?:\/\/.+)$/.exec(value); return m ? m[1] : undefined; } @@ -695,27 +570,14 @@ export function unwrapBiliBaseUrl(value: string): string | undefined { * install). Also upserts the SessionStart hook, keeping a stale command * fresh across upgrades. Returns the change notes for the hook's log; * never throws, and writes only when the file actually changes. */ -export function repinClaudeManagedBaseUrl( - origin: string, - env: NodeJS.ProcessEnv = process.env, -): string[] { +export function repinClaudeManagedBaseUrl(origin: string, env: NodeJS.ProcessEnv = process.env): string[] { const file = claudeSettingsFile(env); const settings = readJson(file); - const cur = (settings.env as Record | undefined) - ?.ANTHROPIC_BASE_URL; - const baseUrl = claudeNativeBaseUrlForOrigin( - origin, - typeof cur === "string" ? unwrapBiliBaseUrl(cur) : undefined, - env, - ); + const cur = (settings.env as Record | undefined)?.ANTHROPIC_BASE_URL; + const baseUrl = claudeNativeBaseUrlForOrigin(origin, typeof cur === "string" ? unwrapBiliBaseUrl(cur) : undefined, env); // #1902: bare `node`, PATH-resolved by whichever client shell runs the hook. - const hookCommand = portableHookCommand("node", [ - path.join(selfPackageRoot(), "dist", "claude-native-bootstrap.js"), - ]); - const { data, notes } = applyClaudeManagedBlock(settings, { - baseUrl, - hookCommand, - }); + const hookCommand = portableHookCommand("node", [path.join(selfPackageRoot(), "dist", "claude-native-bootstrap.js")]); + const { data, notes } = applyClaudeManagedBlock(settings, { baseUrl, hookCommand }); if (JSON.stringify(data) !== JSON.stringify(settings)) writeJson(file, data); return notes; } @@ -724,19 +586,10 @@ export function repinClaudeManagedBaseUrl( * Never clobbers user keys: a foreign ANTHROPIC_BASE_URL or a non-"1" * DISABLE_AUTO_COMPACT is reported and skipped, not overwritten. Returns the * mutated copy plus human notes. Exported for tests. */ -export function applyClaudeManagedBlock( - settings: Record, - opts: { baseUrl: string; hookCommand: string }, -): { data: Record; notes: string[] } { +export function applyClaudeManagedBlock(settings: Record, opts: { baseUrl: string; hookCommand: string }): { data: Record; notes: string[] } { const data = structuredClone(settings); const notes: string[] = []; - const env = ( - data.env !== null && - typeof data.env === "object" && - !Array.isArray(data.env) - ? data.env - : {} - ) as Record; + const env = (data.env !== null && typeof data.env === "object" && !Array.isArray(data.env) ? data.env : {}) as Record; const cur = env.ANTHROPIC_BASE_URL; if (cur === undefined || cur === null || isBiliClaudeBaseUrl(cur)) { if (cur !== opts.baseUrl) { @@ -744,39 +597,23 @@ export function applyClaudeManagedBlock( notes.push("env.ANTHROPIC_BASE_URL pinned to the bili proxy"); } } else { - notes.push( - `env.ANTHROPIC_BASE_URL left untouched (foreign value ${JSON.stringify(cur)} — unset it or set BILI_CLAUDE_UPSTREAM, then reinstall)`, - ); + notes.push(`env.ANTHROPIC_BASE_URL left untouched (foreign value ${JSON.stringify(cur)} — unset it or set BILI_CLAUDE_UPSTREAM, then reinstall)`); } const dac = env.DISABLE_AUTO_COMPACT; if (dac === undefined || dac === null || dac === "1") { if (dac !== "1") { env.DISABLE_AUTO_COMPACT = "1"; - notes.push( - "env.DISABLE_AUTO_COMPACT=1 (bili owns compression; manual /compact survives)", - ); + notes.push("env.DISABLE_AUTO_COMPACT=1 (bili owns compression; manual /compact survives)"); } } else { - notes.push( - `env.DISABLE_AUTO_COMPACT left untouched (foreign value ${JSON.stringify(dac)})`, - ); + notes.push(`env.DISABLE_AUTO_COMPACT left untouched (foreign value ${JSON.stringify(dac)})`); } if (Object.keys(env).length > 0) data.env = env; - const hooks = ( - data.hooks !== null && - typeof data.hooks === "object" && - !Array.isArray(data.hooks) - ? data.hooks - : {} - ) as Record; - const sessionStart = Array.isArray(hooks.SessionStart) - ? hooks.SessionStart - : []; + const hooks = (data.hooks !== null && typeof data.hooks === "object" && !Array.isArray(data.hooks) ? data.hooks : {}) as Record; + const sessionStart = Array.isArray(hooks.SessionStart) ? hooks.SessionStart : []; if (!sessionStart.some(isOursSessionStartEntry)) { - sessionStart.push({ - hooks: [{ type: "command", command: opts.hookCommand }], - }); + sessionStart.push({ hooks: [{ type: "command", command: opts.hookCommand }] }); hooks.SessionStart = sessionStart; data.hooks = hooks; notes.push("hooks.SessionStart += bili proxy bootstrap"); @@ -790,10 +627,7 @@ export function applyClaudeManagedBlock( /** A hook command naming our bootstrap script. Match on the script name * rather than the whole string: the emitted form changes across releases. */ function isOurHookCommand(command: unknown): command is string { - return ( - typeof command === "string" && - /claude-native-bootstrap\.(?:js|mjs|ts)["']?$/.test(command) - ); + return typeof command === "string" && /claude-native-bootstrap\.(?:js|mjs|ts)["']?$/.test(command); } /** Rewrite every hook command we own to `command`, in place; true if any @@ -801,10 +635,7 @@ function isOurHookCommand(command: unknown): command is string { * so without this a settings file written by an older release keeps its old * command forever — and a command a client shell cannot run hangs every * session with no log to say why. */ -function refreshOurHookCommands( - sessionStart: unknown[], - command: string, -): boolean { +function refreshOurHookCommands(sessionStart: unknown[], command: string): boolean { let changed = false; for (const entry of sessionStart) { if (!isOursSessionStartEntry(entry)) continue; @@ -823,36 +654,19 @@ function refreshOurHookCommands( /** A SessionStart entry we wrote: any hook command naming our bootstrap * script (path may differ across installs/upgrades). */ export function isOursSessionStartEntry(entry: unknown): boolean { - const hooks = - entry !== null && typeof entry === "object" && !Array.isArray(entry) - ? (entry as { hooks?: unknown }).hooks - : undefined; + const hooks = (entry !== null && typeof entry === "object" && !Array.isArray(entry) ? (entry as { hooks?: unknown }).hooks : undefined); if (!Array.isArray(hooks)) return false; - return hooks.some( - (h) => - h !== null && - typeof h === "object" && - isOurHookCommand((h as { command?: unknown }).command), - ); + return hooks.some((h) => h !== null && typeof h === "object" && isOurHookCommand((h as { command?: unknown }).command)); } /** Pure strip of the managed block (remove path) — returns the cleaned copy * and what was removed. DISABLE_AUTO_COMPACT is dropped only when it is the * value we wrote ("1"); a .bili-bak with a pre-install value restores it in * the caller. Exported for tests. */ -export function stripClaudeManagedBlock(settings: Record): { - data: Record; - removed: string[]; -} { +export function stripClaudeManagedBlock(settings: Record): { data: Record; removed: string[] } { const data = structuredClone(settings); const removed: string[] = []; - const env = ( - data.env !== null && - typeof data.env === "object" && - !Array.isArray(data.env) - ? data.env - : undefined - ) as Record | undefined; + const env = (data.env !== null && typeof data.env === "object" && !Array.isArray(data.env) ? data.env : undefined) as Record | undefined; if (env !== undefined) { if (isBiliClaudeBaseUrl(env.ANTHROPIC_BASE_URL)) { delete env.ANTHROPIC_BASE_URL; @@ -864,17 +678,9 @@ export function stripClaudeManagedBlock(settings: Record): { } if (Object.keys(env).length === 0) delete data.env; } - const hooks = ( - data.hooks !== null && - typeof data.hooks === "object" && - !Array.isArray(data.hooks) - ? data.hooks - : undefined - ) as Record | undefined; + const hooks = (data.hooks !== null && typeof data.hooks === "object" && !Array.isArray(data.hooks) ? data.hooks : undefined) as Record | undefined; if (hooks !== undefined && Array.isArray(hooks.SessionStart)) { - const kept = (hooks.SessionStart as unknown[]).filter( - (e) => !isOursSessionStartEntry(e), - ); + const kept = (hooks.SessionStart as unknown[]).filter((e) => !isOursSessionStartEntry(e)); if (kept.length !== (hooks.SessionStart as unknown[]).length) { removed.push("hooks.SessionStart entry"); if (kept.length > 0) hooks.SessionStart = kept; @@ -888,14 +694,10 @@ export function stripClaudeManagedBlock(settings: Record): { /** True when the managed settings block (the static ANTHROPIC_BASE_URL) is * present — the `bili claude` launcher consults this to override the static * URL with its own ephemeral proxy (coexistence, #964 item 5). */ -export function claudeNativeInstalled( - env: NodeJS.ProcessEnv = process.env, -): boolean { +export function claudeNativeInstalled(env: NodeJS.ProcessEnv = process.env): boolean { try { const data = readJson(claudeSettingsFile(env)); - return isBiliClaudeBaseUrl( - (data.env as Record | undefined)?.ANTHROPIC_BASE_URL, - ); + return isBiliClaudeBaseUrl((data.env as Record | undefined)?.ANTHROPIC_BASE_URL); } catch { return false; } @@ -908,18 +710,9 @@ export function claudeNativeInstalled( function runClaudeCli(claude: string, args: string[]): void { if (process.platform === "win32" && /\.(cmd|bat)$/i.test(claude)) { const q = (s: string) => `"${s.replaceAll("%", "%%")}"`; - execFileSync([claude, ...args].map(q).join(" "), { - shell: true, - stdio: ["ignore", "pipe", "pipe"], - timeout: CLAUDE_EXEC_TIMEOUT_MS, - windowsHide: true, - }); + execFileSync([claude, ...args].map(q).join(" "), { shell: true, stdio: ["ignore", "pipe", "pipe"], timeout: CLAUDE_EXEC_TIMEOUT_MS, windowsHide: true }); } else { - execFileSync(claude, args, { - stdio: ["ignore", "pipe", "pipe"], - timeout: CLAUDE_EXEC_TIMEOUT_MS, - windowsHide: true, - }); + execFileSync(claude, args, { stdio: ["ignore", "pipe", "pipe"], timeout: CLAUDE_EXEC_TIMEOUT_MS, windowsHide: true }); } } @@ -945,14 +738,10 @@ export function resolveClaudeCli( pathext?: string, ): string { if (/[\\/]/.test(claude) || /\.[a-z]+$/i.test(claude)) return claude; - const run = - where ?? (process.platform === "win32" ? defaultWhereRunner : undefined); + const run = where ?? (process.platform === "win32" ? defaultWhereRunner : undefined); if (!run) return claude; try { - const hits = (run(claude).stdout ?? "") - .split(/\r?\n/) - .map((l) => l.trim()) - .filter((l) => l.length > 0); + const hits = (run(claude).stdout ?? "").split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0); if (hits.length === 0) return claude; const exts = (pathext ?? process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") .split(";") @@ -979,20 +768,13 @@ export function resolveClaudeCli( } function defaultWhereRunner(name: string): { stdout: string | null } { - const r = spawnSync("where.exe", [name], { - stdio: ["ignore", "pipe", "ignore"], - timeout: 5000, - encoding: "utf8", - windowsHide: true, - }); + const r = spawnSync("where.exe", [name], { stdio: ["ignore", "pipe", "ignore"], timeout: 5000, encoding: "utf8", windowsHide: true }); return { stdout: r.stdout ?? null }; } function claudeInstall(): string { if (process.env.BILI_NATIVE_CLAUDE === "0") { - throw new Error( - "claude: install refused — BILI_NATIVE_CLAUDE=0 is set (clear it to install the native posture)", - ); + throw new Error("claude: install refused — BILI_NATIVE_CLAUDE=0 is set (clear it to install the native posture)"); } const root = selfPackageRoot(); const mcpJs = path.join(root, "dist", "mcp.js"); @@ -1025,48 +807,25 @@ function claudeInstall(): string { const stableOrigin = `http://127.0.0.1:${nativePort}`; const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); try { - runClaudeCli(claude, [ - "mcp", - "add", - "bili", - "--scope", - "user", - "-e", - `BILI_MCP_PROXY=${stableOrigin}`, - "--", - process.execPath, - mcpJs, - ]); + runClaudeCli(claude, ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${stableOrigin}`, "--", process.execPath, mcpJs]); } catch (err) { - const stderr = - err instanceof Error && "stderr" in err - ? String((err as { stderr?: Buffer | string }).stderr ?? "") - : ""; - throw new Error( - `claude: MCP registration failed (${stderr.trim() || (err instanceof Error ? err.message : String(err))}) — is the claude CLI on PATH? (the managed settings block at ${file} was written; rerun after fixing the CLI to complete the MCP face)`, - ); + const stderr = err instanceof Error && "stderr" in err ? String((err as { stderr?: Buffer | string }).stderr ?? "") : ""; + throw new Error(`claude: MCP registration failed (${stderr.trim() || (err instanceof Error ? err.message : String(err))}) — is the claude CLI on PATH? (the managed settings block at ${file} was written; rerun after fixing the CLI to complete the MCP face)`); } let cmdNote: string; const cmdFile = claudeAcpCacheCommandFile(); try { fs.mkdirSync(path.dirname(cmdFile), { recursive: true }); - const existing = fs.existsSync(cmdFile) - ? fs.readFileSync(cmdFile, "utf8") - : undefined; - if ( - existing === undefined || - existing.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd() - ) { + const existing = fs.existsSync(cmdFile) ? fs.readFileSync(cmdFile, "utf8") : undefined; + if (existing === undefined || existing.trimEnd() === CLAUDE_ACP_CACHE_COMMAND.trimEnd()) { fs.writeFileSync(cmdFile, CLAUDE_ACP_CACHE_COMMAND); cmdNote = `written`; } else { cmdNote = `left untouched (foreign content)`; } } catch (err) { - throw new Error( - `claude: /acp-cache command write failed (${err instanceof Error ? err.message : String(err)}) — the managed settings block at ${file} and the MCP face were written; fix the permissions and rerun`, - ); + throw new Error(`claude: /acp-cache command write failed (${err instanceof Error ? err.message : String(err)}) — the managed settings block at ${file} and the MCP face were written; fix the permissions and rerun`); } return `claude: managed block -> ${file} (${notes.join("; ")}); /acp-cache command -> ${cmdFile} (${cmdNote}); MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin}) — restart claude to activate`; } @@ -1084,17 +843,8 @@ function claudeRemove(): string { if (fs.existsSync(bak)) { const bakData = readJson(bak) as { env?: Record }; const bakDac = bakData.env?.DISABLE_AUTO_COMPACT; - if ( - removed.includes("env.DISABLE_AUTO_COMPACT") && - bakDac !== undefined - ) { - const env = ( - data.env !== null && - typeof data.env === "object" && - !Array.isArray(data.env) - ? data.env - : {} - ) as Record; + if (removed.includes("env.DISABLE_AUTO_COMPACT") && bakDac !== undefined) { + const env = ((data.env !== null && typeof data.env === "object" && !Array.isArray(data.env) ? data.env : {}) as Record); env.DISABLE_AUTO_COMPACT = bakDac; data.env = env; } @@ -1111,9 +861,7 @@ function claudeRemove(): string { runClaudeCli(claude, ["mcp", "remove", "bili", "--scope", "user"]); parts.push("MCP face removed"); } catch (err) { - throw new Error( - `claude: MCP removal failed (${err instanceof Error ? err.message : String(err)})${parts.length > 0 ? ` — ${parts.join("; ")} succeeded first` : ""}`, - ); + throw new Error(`claude: MCP removal failed (${err instanceof Error ? err.message : String(err)})${parts.length > 0 ? ` — ${parts.join("; ")} succeeded first` : ""}`); } } const cmdFile = claudeAcpCacheCommandFile(); @@ -1124,25 +872,17 @@ function claudeRemove(): string { fs.unlinkSync(cmdFile); parts.push("/acp-cache command removed"); } else { - parts.push( - `/acp-cache command left untouched (${cmdFile} holds foreign content)`, - ); + parts.push(`/acp-cache command left untouched (${cmdFile} holds foreign content)`); } } } catch (err) { - parts.push( - `/acp-cache command removal skipped (${err instanceof Error ? err.message : String(err)})`, - ); + parts.push(`/acp-cache command removal skipped (${err instanceof Error ? err.message : String(err)})`); } - return parts.length > 0 - ? `claude: ${parts.join("; ")}` - : `claude: not installed (${file} / ${claudeMcpJson()})`; + return parts.length > 0 ? `claude: ${parts.join("; ")}` : `claude: not installed (${file} / ${claudeMcpJson()})`; } function claudeMcpInstalled(): boolean { - const data = readJson(claudeMcpJson()) as { - mcpServers?: Record; - }; + const data = readJson(claudeMcpJson()) as { mcpServers?: Record }; return isPlainMcpObject(data.mcpServers) && "bili" in data.mcpServers; } @@ -1150,9 +890,7 @@ function claudeStatus(): string { let block = false; try { const data = readJson(claudeSettingsFile()); - block = isBiliClaudeBaseUrl( - (data.env as Record | undefined)?.ANTHROPIC_BASE_URL, - ); + block = isBiliClaudeBaseUrl((data.env as Record | undefined)?.ANTHROPIC_BASE_URL); } catch { block = false; } @@ -1164,10 +902,8 @@ function claudeStatus(): string { } })(); if (block && mcp) return "installed (managed settings block + MCP)"; - if (block) - return "installed (managed settings block; MCP face missing — rerun install)"; - if (mcp) - return "installed (MCP only — legacy companion posture; rerun install for the native block)"; + if (block) return "installed (managed settings block; MCP face missing — rerun install)"; + if (mcp) return "installed (MCP only — legacy companion posture; rerun install for the native block)"; return "not installed"; } @@ -1187,6 +923,10 @@ function codexBlock(): string { return `\n[mcp_servers.bili]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(path.join(selfPackageRoot(), "dist", "mcp.js"))}]\n`; } +function malformedCodexArgs(block: string): boolean { + return /^[ \t]*args[ \t]*=[ \t]*["']/m.test(block); +} + /** Force every line ending in `text` to the convention `reference` already * uses. The individual renderers (codexBlock, codexHookTable) emit `\n`, so * without this a CRLF config — the norm on Windows — would come back with a @@ -1198,10 +938,6 @@ function normalizeCodexEol(text: string, reference: string): string { return reference.includes("\r\n") ? lf.replace(/\n/g, "\r\n") : lf; } -function malformedCodexArgs(block: string): boolean { - return /^[ \t]*args[ \t]*=[ \t]*["']/m.test(block); -} - /** The model-route face of the codex lane (ticket 01). Distinct from the MCP * face above and reported separately: `[mcp_servers.bili]` proves TOOLS, * never that model traffic reaches bili. Ownership is content-based @@ -1218,11 +954,7 @@ function codexRouteSync( } { const recordPath = codexRouteRecordPath(file); const previous = readCodexRouteRecord(recordPath); - const defaultHomeConfig = - path.resolve(file).toLowerCase() === - path - .resolve(path.join(os.homedir(), ".codex", "config.toml")) - .toLowerCase(); + const defaultHomeConfig = path.resolve(file).toLowerCase() === path.resolve(path.join(os.homedir(), ".codex", "config.toml")).toLowerCase(); const ccSwitchMode = defaultHomeConfig ? detectCcSwitch().mode : "unknown"; const plan = planCodexRoute(text, { origin: codexRouteOrigin(process.env), @@ -1230,45 +962,19 @@ function codexRouteSync( ownedRecord: previous, ccSwitchMode, }); - if (plan.action === "keep") - return { - text, - note: `model route: ${plan.note}`, - conflicted: false, - record: previous, - }; - if (plan.action === "conflict") - return { - text, - note: `model route: ${plan.note}`, - conflicted: true, - record: previous, - }; + if (plan.action === "keep") return { text, note: `model route: ${plan.note}`, conflicted: false, record: previous }; + if (plan.action === "conflict") return { text, note: `model route: ${plan.note}`, conflicted: true, record: previous }; const value = plan.value!; const route = value.slice(value.indexOf("/bili/") + "/bili/".length); const target = plan.target ?? { kind: "top-level" as const }; const previousTarget = previous?.target ?? { kind: "top-level" as const }; - const targetMatches = - previousTarget.kind === target.kind && - (target.kind === "top-level" || - (previousTarget.kind === "provider" && - previousTarget.provider === target.provider)); - const previousValue = targetMatches - ? (previous?.previousValue ?? null) - : target.kind === "provider" - ? (parseCodexToml(text).providers?.[target.provider]?.baseUrl ?? null) - : (parseCodexToml(text).openaiBaseUrl ?? null); + const targetMatches = previousTarget.kind === target.kind && (target.kind === "top-level" || (previousTarget.kind === "provider" && previousTarget.provider === target.provider)); + const previousValue = targetMatches ? (previous?.previousValue ?? null) : target.kind === "provider" ? (parseCodexToml(text).providers?.[target.provider]?.baseUrl ?? null) : (parseCodexToml(text).openaiBaseUrl ?? null); return { text: plan.text, note: `model route: ${plan.note}`, conflicted: false, - record: { - schemaVersion: 1, - writtenValue: value, - previousValue, - upstream: route, - target, - }, + record: { schemaVersion: 1, writtenValue: value, previousValue, upstream: route, target }, }; } @@ -1284,50 +990,28 @@ function codexHookSync( const root = selfPackageRoot(); const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); if (!fs.existsSync(hookScript)) { - warn( - `codex: hook script missing at ${hookScript} — skipping the SessionStart hook face (rebuild bili)`, - ); - return { - text, - note: "hook: skipped (dist/codex/bootstrap-hook.js missing)", - changed: false, - }; + warn(`codex: hook script missing at ${hookScript} — skipping the SessionStart hook face (rebuild bili)`); + return { text, note: "hook: skipped (dist/codex/bootstrap-hook.js missing)", changed: false }; } const command = portableHookCommand("node", [hookScript]); const plan = planCodexHook(text, command); const shape = assertCodexConfigLoads(plan.text); if (shape !== undefined) { warn(`codex: ${shape} — SessionStart hook NOT written`); - return { - text, - note: `hook: skipped (${shape})`, - changed: false, - }; + return { text, note: `hook: skipped (${shape})`, changed: false }; } const featureNote = codexHooksEnabledNote(plan.text); if (featureNote !== "" && plan.action !== "keep") - warn( - `codex: SessionStart hook written, but hook execution is not enabled — ${featureNote}`, - ); - const note = - featureNote === "" - ? `hook: ${plan.note}` - : `hook: ${plan.note} — ${featureNote}`; - return { - text: plan.text, - note, - changed: plan.action !== "keep", - }; + warn(`codex: SessionStart hook written, but hook execution is not enabled — ${featureNote}`); + const note = featureNote === "" ? `hook: ${plan.note}` : `hook: ${plan.note} — ${featureNote}`; + return { text: plan.text, note, changed: plan.action !== "keep" }; } /** The ACP-skill face of the codex lane (ticket 08): `/skills/bili/ * SKILL.md`, Codex's own discovered-skill extension point. Reported as a * THIRD face next to mcp/hook, because a skill changes what the model does, * not whether traffic is compressed. */ -function codexSkillSync(warn: (message: string) => void): { - note: string; - changed: boolean; -} { +function codexSkillSync(warn: (message: string) => void): { note: string; changed: boolean } { const result = installCodexSkill(process.env); if (result.state === "foreign") warn(`codex: ${result.note}`); return { note: `skill: ${result.note}`, changed: result.written }; @@ -1347,14 +1031,9 @@ function codexSkillSync(warn: (message: string) => void): { * caller degrades to a printed hint and the user starts the proxy by hand. * That keeps this hook from turning a successful config install into a * reported failure. */ -async function serviceSync( - action: "install" | "remove", -): Promise<{ note: string; warning?: string }> { +async function serviceSync(action: "install" | "remove"): Promise<{ note: string; warning?: string }> { try { - const result = - action === "install" - ? await installProxyService() - : await removeProxyService(); + const result = action === "install" ? await installProxyService() : await removeProxyService(); if (result.ok) return { note: @@ -1364,22 +1043,12 @@ async function serviceSync( ? "service: registered for logon + started" : "service: removed", }; - if (result.action === "already-absent") - return { note: "service: none registered" }; + if (result.action === "already-absent") return { note: "service: none registered" }; if (result.action === "unsupported") - return { - note: "service: not applicable", - warning: `${result.message}; start the proxy yourself with \`bili start\``, - }; - return { - note: "service: NOT registered", - warning: `${result.message}; start the proxy yourself with \`bili start\``, - }; + return { note: "service: not applicable", warning: `${result.message}; start the proxy yourself with \`bili start\`` }; + return { note: "service: NOT registered", warning: `${result.message}; start the proxy yourself with \`bili start\`` }; } catch (error) { - return { - note: "service: NOT registered", - warning: `service registration failed (${error instanceof Error ? error.message : String(error)}); start the proxy yourself with \`bili start\``, - }; + return { note: "service: NOT registered", warning: `service registration failed (${error instanceof Error ? error.message : String(error)}); start the proxy yourself with \`bili start\`` }; } } @@ -1390,9 +1059,7 @@ async function serviceSync( export async function codexInstallWithService(): Promise { const base = codexInstall(); const service = await serviceSync("install"); - return service.warning !== undefined - ? `${base}; ${service.note}\n ! ${service.warning}` - : `${base}; ${service.note}`; + return service.warning !== undefined ? `${base}; ${service.note}\n ! ${service.warning}` : `${base}; ${service.note}`; } /** `bili plugin remove codex`: config faces plus service teardown, so an @@ -1400,9 +1067,7 @@ export async function codexInstallWithService(): Promise { export async function codexRemoveWithService(): Promise { const base = codexRemove(); const service = await serviceSync("remove"); - return service.warning !== undefined - ? `${base}; ${service.note}\n ! ${service.warning}` - : `${base}; ${service.note}`; + return service.warning !== undefined ? `${base}; ${service.note}\n ! ${service.warning}` : `${base}; ${service.note}`; } function codexInstall(): string { @@ -1421,31 +1086,18 @@ function codexInstall(): string { // table and lets the block run to EOF, deleting everything after it. const after = text.slice(existing.index); const firstNewline = after.indexOf("\n"); - const nextTable = - firstNewline < 0 - ? -1 - : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); - const blockEnd = - nextTable >= 0 - ? existing.index + firstNewline + 1 + nextTable - : text.length; + const nextTable = firstNewline < 0 ? -1 : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); + const blockEnd = nextTable >= 0 ? existing.index + firstNewline + 1 + nextTable : text.length; const block = text.slice(existing.index, blockEnd); const canonical = codexBlock().replace(/^\n/, ""); if (block.trimEnd() === canonical.trimEnd()) { mcpNote = "mcp: already installed"; } else { - next = - text.slice(0, existing.index) + - canonical + - text.slice(existing.index + block.length); + next = text.slice(0, existing.index) + canonical + text.slice(existing.index + block.length); mcpNote = `mcp: refreshed [mcp_servers.bili]${malformedCodexArgs(block) ? " (repaired args: was not an array)" : ""}`; - } + } } else { - fs.mkdirSync(path.dirname(file), { recursive: true }); - next = - text + - (text.endsWith("\n") || text.length === 0 ? "" : "\n") + - codexBlock(); + next = text + (text.endsWith("\n") || text.length === 0 ? "" : "\n") + codexBlock(); mcpNote = "mcp: installed [mcp_servers.bili]"; } const route = codexRouteSync(next, file); @@ -1457,36 +1109,23 @@ function codexInstall(): string { // against the file we started from. Without this a CRLF config (the norm on // Windows) came back with a mixed-ending bili block spliced in. const finalText = normalizeCodexEol(next, text); - if ( - finalText === text && - existing !== null && - mcpNote === "mcp: already installed" && - !hook.changed && - !skill.changed - ) { + if (finalText === text && existing !== null && mcpNote === "mcp: already installed" && !hook.changed && !skill.changed) { return `codex: already installed (${file}) — ${mcpNote}; ${route.note}; ${hook.note}; ${skill.note}`; } writeConfigText(file, finalText); - if (route.record !== undefined) - writeCodexRouteRecord(codexRouteRecordPath(file), route.record); + if (route.record !== undefined) writeCodexRouteRecord(codexRouteRecordPath(file), route.record); const conflictNote = route.conflicted ? " (NOT routed — see note)" : ""; const detail = `${mcpNote}; ${route.note}${conflictNote}; ${hook.note}; ${skill.note}`; - const tail = - warnings.length > 0 - ? `\n${warnings.map((w) => ` ! ${w}`).join("\n")}` - : ""; - if (mcpNote.startsWith("mcp: refreshed")) - return `codex: refreshed [mcp_servers.bili] -> ${file} — ${detail}${tail}`; - if (mcpNote.startsWith("mcp: installed")) - return `codex: installed -> ${file} — ${detail}${tail}`; + const tail = warnings.length > 0 ? `\n${warnings.map((w) => ` ! ${w}`).join("\n")}` : ""; + if (mcpNote.startsWith("mcp: refreshed")) return `codex: refreshed [mcp_servers.bili] -> ${file} — ${detail}${tail}`; + if (mcpNote.startsWith("mcp: installed")) return `codex: installed -> ${file} — ${detail}${tail}`; return `codex: refreshed -> ${file} — ${detail}${tail}`; } function codexRemove(): string { const file = codexToml(); const skill = removeCodexSkill(process.env); - if (!fs.existsSync(file)) - return `codex: not installed (${file}) — skill: ${skill.note}`; + if (!fs.existsSync(file)) return `codex: not installed (${file}) — skill: ${skill.note}`; const text = fs.readFileSync(file, "utf8"); const routeRecordPath = codexRouteRecordPath(file); const routeRecord = readCodexRouteRecord(routeRecordPath); @@ -1497,13 +1136,9 @@ function codexRemove(): string { const m = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(stripped); return m === null ? -1 : m.index; })(); - const faces = [ - hook.removed ? "hook removed" : "no hook", - `skill: ${skill.removed ? "removed" : skill.note}`, - ]; + const faces = [hook.removed ? "hook removed" : "no hook", `skill: ${skill.removed ? "removed" : skill.note}`]; if (start < 0) { - if (stripped === text) - return `codex: not installed (${file}) — ${faces.join("; ")}`; + if (stripped === text) return `codex: not installed (${file}) — ${faces.join("; ")}`; writeConfigText(file, stripped); removeCodexRouteRecord(routeRecordPath); return `codex: model route restored from ${file} (no MCP block present) — ${faces.join("; ")}`; @@ -1511,13 +1146,9 @@ function codexRemove(): string { const lineStart = stripped.lastIndexOf("\n", start - 1) + 1; const after = stripped.slice(start); const firstNewline = after.indexOf("\n"); - const nextTable = - firstNewline < 0 ? -1 : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); - const end = - nextTable >= 0 ? start + firstNewline + 1 + nextTable : stripped.length; - const cleaned = ( - stripped.slice(0, lineStart).replace(/\n+$/, "\n") + stripped.slice(end) - ).replace(/^\n+/, ""); + const nextTable = firstNewline < 0 ? -1 : after.slice(firstNewline + 1).search(/^[ \t]*\[/m); + const end = nextTable >= 0 ? start + firstNewline + 1 + nextTable : stripped.length; + const cleaned = (stripped.slice(0, lineStart).replace(/\n+$/, "\n") + stripped.slice(end)).replace(/^\n+/, ""); writeConfigText(file, cleaned); removeCodexRouteRecord(routeRecordPath); return `codex: removed from ${file} — ${faces.join("; ")}`; @@ -1529,31 +1160,12 @@ function codexStatus(): string { const mcp = /^\[mcp_servers\.bili\]\s*$/m.test(text); const owned = readCodexRouteRecord(codexRouteRecordPath(file)); const route = readCodexRoute(text, owned); - const routeText = - route.conflict !== undefined - ? `route blocked (${route.conflict.kind})` - : route.routed - ? route.value === desiredCodexRoute(text, codexRouteOrigin(process.env)) - ? "route installed" - : `route drifted (${route.value})` - : "route not installed"; + const routeText = route.conflict !== undefined ? `route blocked (${route.conflict.kind})` : route.routed ? (route.value === desiredCodexRoute(text, codexRouteOrigin(process.env)) ? "route installed" : `route drifted (${route.value})`) : "route not installed"; const hookInstalled = findBiliCodexHook(text) !== undefined; - const hookText = hookInstalled - ? codexHooksEnabledNote(text) === "" - ? "hook installed" - : `hook installed but disabled (${codexHooksEnabledNote(text)})` - : "hook not installed"; + const hookText = hookInstalled ? (codexHooksEnabledNote(text) === "" ? "hook installed" : `hook installed but disabled (${codexHooksEnabledNote(text)})`) : "hook not installed"; const skillState = codexSkillStatus(process.env); - const skillText = - skillState === "installed" - ? "skill installed" - : skillState === "outdated" - ? "skill outdated (rerun install)" - : skillState === "foreign" - ? "skill not ours (left untouched)" - : "skill not installed"; - if (!mcp && !route.routed && !hookInstalled && skillState !== "installed") - return "not installed"; + const skillText = skillState === "installed" ? "skill installed" : skillState === "outdated" ? "skill outdated (rerun install)" : skillState === "foreign" ? "skill not ours (left untouched)" : "skill not installed"; + if (!mcp && !route.routed && !hookInstalled && skillState !== "installed") return "not installed"; return `${mcp ? "mcp installed" : "mcp missing"}; ${routeText}; ${hookText}; ${skillText}`; } @@ -1584,38 +1196,21 @@ export function detectOpencodeMajor(): number { // Windows: npm global shims are .cmd/.bat — execFileSync cannot spawn // those directly (EINVAL), so route through the shell with explicit // quoting. Plain exes and POSIX shebang scripts go straight through. - const viaShell = - process.platform === "win32" && /\.(cmd|bat)$/i.test(command); + const viaShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(command); const out = viaShell - ? execFileSync(`"${command}" --version`, { - shell: true, - timeout: 5000, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }) - : execFileSync(command, ["--version"], { - timeout: 5000, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }); + ? execFileSync(`"${command}" --version`, { shell: true, timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }) + : execFileSync(command, ["--version"], { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }); const m = /(\d+)\s*\./.exec(out); if (m) major = parseInt(m[1], 10); - } catch (error) { - // Version probing is advisory; the caller falls back to the conservative major. - void error; - } + } catch {} ocMajorCache.set(command, major); return major; } function pluginEntries(data: Record, key: string): string[] { const v = data[key]; - if (Array.isArray(v)) - return v.filter((x): x is string => typeof x === "string"); - if (v !== null && typeof v === "object") - return Object.keys(v as Record); + if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string"); + if (v !== null && typeof v === "object") return Object.keys(v as Record); return []; } @@ -1628,10 +1223,7 @@ function opencodeTargetFile(): string { const raw = process.env.OPENCODE_CONFIG?.trim(); if (raw && raw.length > 0) return raw; const xdg = process.env.XDG_CONFIG_HOME?.trim(); - const dir = - xdg && xdg.length > 0 - ? path.join(xdg, "opencode") - : path.join(os.homedir(), ".config", "opencode"); + const dir = xdg && xdg.length > 0 ? path.join(xdg, "opencode") : path.join(os.homedir(), ".config", "opencode"); for (const name of ["opencode.jsonc", "opencode.json", "config.json"]) { const p = path.join(dir, name); if (fs.existsSync(p)) return p; @@ -1667,48 +1259,30 @@ function readOriginalText(file: string): string { // stringify round-trip would wash the comments away on write-back. Tolerance // is bounded: ANY diagnostic beyond comments/trailing commas means the file // is broken, and a broken config is never overwritten (§7.3). -function parseOpencodeConfig( - text: string, - file: string, -): Record { +function parseOpencodeConfig(text: string, file: string): Record { const errors: ParseError[] = []; const parsed = jsoncParse(text, errors, { allowTrailingComma: true }); if (errors.length > 0 || parsed === undefined) { const first = errors[0]; const detail = first ? ` (offset ${first.offset})` : ""; - throw new Error( - `${file}: not valid JSON${detail} — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`, - ); + throw new Error(`${file}: not valid JSON${detail} — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`); } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { - throw new Error( - `${file}: expected a JSON object at top level, refusing to overwrite`, - ); + throw new Error(`${file}: expected a JSON object at top level, refusing to overwrite`); } return parsed as Record; } -function loadOpencodeConfig(file: string): { - original: string; - data: Record; -} { +function loadOpencodeConfig(file: string): { original: string; data: Record } { const original = readOriginalText(file); - return { - original, - data: original === "" ? {} : parseOpencodeConfig(original, file), - }; + return { original, data: original === "" ? {} : parseOpencodeConfig(original, file) }; } // Write back preserving everything bili did not touch: a missing or plain-JSON // target is serialized whole (the historical behavior); a JSONC target gets // surgical top-level-key edits so comments and formatting elsewhere survive // byte-for-byte (#927). A no-op run (nothing touched) leaves the file alone. -function writeOpencodeConfig( - file: string, - original: string, - data: Record, - touched: ReadonlySet, -): void { +function writeOpencodeConfig(file: string, original: string, data: Record, touched: ReadonlySet): void { if (touched.size === 0) return; if (original === "") { writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); @@ -1718,22 +1292,14 @@ function writeOpencodeConfig( try { JSON.parse(original); strict = true; - } catch (error) { - // JSONC is expected here; preserve it with targeted edits instead. - void error; - } + } catch {} if (strict) { writeConfigText(file, JSON.stringify(data, null, 2) + "\n"); return; } let text = original; for (const key of touched) { - text = applyEdits( - text, - jsoncModify(text, [key], data[key], { - formattingOptions: { tabSize: 2, insertSpaces: true }, - }), - ); + text = applyEdits(text, jsoncModify(text, [key], data[key], { formattingOptions: { tabSize: 2, insertSpaces: true } })); } writeConfigText(file, text); } @@ -1746,8 +1312,7 @@ function writeOpencodeConfig( // #927: strip from BOTH key spellings — a 2.x host may carry acp entries under // `plugins`, an older v1 install under `plugin`. function isLegacyOpencodeAcpEntry(entry: string): boolean { - if (entry === "opencode-acp" || entry.startsWith("opencode-acp@")) - return true; + if (entry === "opencode-acp" || entry.startsWith("opencode-acp@")) return true; if (entry.startsWith("npm:")) { const rest = entry.slice(4); return rest === "opencode-acp" || rest.startsWith("opencode-acp@"); @@ -1756,16 +1321,10 @@ function isLegacyOpencodeAcpEntry(entry: string): boolean { const segments = normalized.split("/").filter((s) => s.length > 0); // Any path segment naming the package identifies an acp install — covers // dir specs, /index.js, and deeper entry paths like dist/index.js. - return segments.some( - (s) => s === "opencode-acp" || s.startsWith("opencode-acp@"), - ); + return segments.some((s) => s === "opencode-acp" || s.startsWith("opencode-acp@")); } -function stripLegacyOpencodeAcp( - data: Record, - notes: string[], - touched: Set, -): void { +function stripLegacyOpencodeAcp(data: Record, notes: string[], touched: Set): void { const removed: string[] = []; for (const key of PLUGIN_KEYS) { const v = data[key]; @@ -1801,12 +1360,8 @@ function stripLegacyOpencodeAcp( } } if (removed.length > 0) { - notes.push( - `replaced opencode-acp plugin entries (${removed.join(", ")}) — single compression owner; restore from the .bili-bak backup if that was intended`, - ); - notes.push( - "also check /.opencode/opencode.json — a LOCAL-scope opencode-acp install (opencode plugin opencode-acp) lives there, not in this global config", - ); + notes.push(`replaced opencode-acp plugin entries (${removed.join(", ")}) — single compression owner; restore from the .bili-bak backup if that was intended`); + notes.push("also check /.opencode/opencode.json — a LOCAL-scope opencode-acp install (opencode plugin opencode-acp) lives there, not in this global config"); } } @@ -1822,8 +1377,7 @@ export function isNpmInstallForm(root: string): boolean { export const OPENCODE_NPM_ENTRY = "billion-context"; -const DEV_FORM_NOTE = - "dev form: machine-local shim, not portable across machines — an npm install writes the bare package name instead"; +const DEV_FORM_NOTE = "dev form: machine-local shim, not portable across machines — an npm install writes the bare package name instead"; // #925: pick + apply the plugin entry for this install form. Replaces any // existing entry of either form (single owner), returns note(s). #927: the @@ -1835,40 +1389,25 @@ const DEV_FORM_NOTE = // scalars) are preserved verbatim in form and position. A strings-only // projection must never be written back, and "plugin present" must mean // the key was left untouched (no rewrite of the surrounding file either). -export function applyOpencodePluginEntry(args: { - data: Record; - root: string; - shimDir: string; - agentJs: string; - key?: "plugin" | "plugins"; - touched?: Set; -}): string[] { +export function applyOpencodePluginEntry(args: { data: Record; root: string; shimDir: string; agentJs: string; key?: "plugin" | "plugins"; touched?: Set }): string[] { const { data, root, shimDir, agentJs } = args; const key = args.key ?? "plugin"; const touched = args.touched ?? new Set(); const ours = [OPENCODE_NPM_ENTRY, shimDir]; const npmForm = isNpmInstallForm(root); const entry = npmForm ? OPENCODE_NPM_ENTRY : shimDir; - const isOurs = (x: unknown): boolean => - typeof x === "string" && ours.includes(x); + const isOurs = (x: unknown): boolean => typeof x === "string" && ours.includes(x); const raw = data[key]; const oursIn = (): string[] => { if (Array.isArray(raw)) return raw.filter((x): x is string => isOurs(x)); - if (raw !== null && typeof raw === "object") - return Object.keys(raw as Record).filter((k) => - isOurs(k), - ); + if (raw !== null && typeof raw === "object") return Object.keys(raw as Record).filter((k) => isOurs(k)); return []; }; const replaced = oursIn(); - if (npmForm && replaced.includes(shimDir)) - fs.rmSync(shimDir, { recursive: true, force: true }); + if (npmForm && replaced.includes(shimDir)) fs.rmSync(shimDir, { recursive: true, force: true }); if (!npmForm) { fs.mkdirSync(shimDir, { recursive: true }); - fs.writeFileSync( - path.join(shimDir, "index.js"), - `export { default } from ${JSON.stringify(agentJs)};\n`, - ); + fs.writeFileSync(path.join(shimDir, "index.js"), `export { default } from ${JSON.stringify(agentJs)};\n`); } // Exactly our one entry, already the right form — nothing to migrate: // leave the key (and the file) untouched. @@ -1886,15 +1425,10 @@ export function applyOpencodePluginEntry(args: { touched.add(key); if (npmForm) { if (replaced.length === 0) return [`plugin -> ${OPENCODE_NPM_ENTRY}`]; - return [ - `plugin -> ${OPENCODE_NPM_ENTRY} (replaced ${replaced.join(", ")})`, - ]; + return [`plugin -> ${OPENCODE_NPM_ENTRY} (replaced ${replaced.join(", ")})`]; } if (replaced.length === 0) return [`plugin -> ${shimDir}`, DEV_FORM_NOTE]; - return [ - `plugin -> ${shimDir} (replaced ${replaced.join(", ")})`, - DEV_FORM_NOTE, - ]; + return [`plugin -> ${shimDir} (replaced ${replaced.join(", ")})`, DEV_FORM_NOTE]; } function opencodeInstall(withMcp = false): string { @@ -1916,13 +1450,9 @@ function opencodeInstall(withMcp = false): string { delete rawMcp.bili; if (Object.keys(rawMcp).length === 0) delete data.mcp; touched.add("mcp"); - notes.push( - "mcp.bili removed (stale second tool face — the native plugin provides the bili tools; install with --with-mcp to keep an MCP face)", - ); + notes.push("mcp.bili removed (stale second tool face — the native plugin provides the bili tools; install with --with-mcp to keep an MCP face)"); } else { - notes.push( - "mcp.bili not written (the native plugin provides the bili tools; --with-mcp adds an MCP face)", - ); + notes.push("mcp.bili not written (the native plugin provides the bili tools; --with-mcp adds an MCP face)"); } } else { try { @@ -1937,43 +1467,26 @@ function opencodeInstall(withMcp = false): string { const bili = mcp.bili; if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { const env = (bili as Record).environment; - const envObj = - env !== null && typeof env === "object" && !Array.isArray(env) - ? (env as Record) - : undefined; + const envObj = env !== null && typeof env === "object" && !Array.isArray(env) ? (env as Record) : undefined; if (envObj?.BILI_MCP_PROXY !== undefined && explicit === undefined) { delete envObj.BILI_MCP_PROXY; - if (Object.keys(envObj).length === 0) - delete (bili as Record).environment; + if (Object.keys(envObj).length === 0) delete (bili as Record).environment; touched.add("mcp"); - notes.push( - "mcp.bili present (stale BILI_MCP_PROXY pin removed — live discovery takes over)", - ); + notes.push("mcp.bili present (stale BILI_MCP_PROXY pin removed — live discovery takes over)"); } else { notes.push("mcp.bili present"); } } else { - const entry: Record = { - type: "local", - command: [process.execPath, mcpJs], - enabled: true, - }; - if (explicit !== undefined) - entry.environment = { BILI_MCP_PROXY: explicit }; + const entry: Record = { type: "local", command: [process.execPath, mcpJs], enabled: true }; + if (explicit !== undefined) entry.environment = { BILI_MCP_PROXY: explicit }; mcp.bili = entry; data.mcp = mcp; touched.add("mcp"); - notes.push( - explicit !== undefined - ? `mcp.bili written (BILI_MCP_PROXY=${explicit})` - : "mcp.bili written (no origin pin — live discovery via instance file)", - ); + notes.push(explicit !== undefined ? `mcp.bili written (BILI_MCP_PROXY=${explicit})` : "mcp.bili written (no origin pin — live discovery via instance file)"); } } } catch (err) { - notes.push( - `mcp.bili skipped (${err instanceof Error ? err.message : String(err)})`, - ); + notes.push(`mcp.bili skipped (${err instanceof Error ? err.message : String(err)})`); } } @@ -1988,16 +1501,7 @@ function opencodeInstall(withMcp = false): string { // below snapshots the original config to .bili-bak (first write only). stripLegacyOpencodeAcp(data, notes, touched); // #927 entry key for this host + #925 entry form for this install form. - notes.push( - ...applyOpencodePluginEntry({ - data, - root, - shimDir: opencodePluginDir(file), - agentJs, - key: pickPluginKey(detectOpencodeMajor()), - touched, - }), - ); + notes.push(...applyOpencodePluginEntry({ data, root, shimDir: opencodePluginDir(file), agentJs, key: pickPluginKey(detectOpencodeMajor()), touched })); // Single compression owner: with the native plugin installed, ACP owns // compression — disable host auto-compaction (merge-preserving; the key is @@ -2005,12 +1509,7 @@ function opencodeInstall(withMcp = false): string { // remove. #927: skip when the target already says auto:false — the user // wrote it themselves, so one file carries the fact exactly once. const curCompaction = data.compaction; - const curObj = - curCompaction !== null && - typeof curCompaction === "object" && - !Array.isArray(curCompaction) - ? (curCompaction as Record) - : undefined; + const curObj = curCompaction !== null && typeof curCompaction === "object" && !Array.isArray(curCompaction) ? curCompaction as Record : undefined; if (curObj?.auto === false) { notes.push("compaction.auto already disabled"); } else { @@ -2097,9 +1596,7 @@ function opencodeRemove(): string { } writeOpencodeConfig(file, original, data, touched); - return notes.length > 0 - ? `opencode: removed from ${file} (${notes.join("; ")})` - : `opencode: not installed (${file})`; + return notes.length > 0 ? `opencode: removed from ${file} (${notes.join("; ")})` : `opencode: not installed (${file})`; } function opencodeStatus(): string { @@ -2107,12 +1604,8 @@ function opencodeStatus(): string { const { data } = loadOpencodeConfig(file); const mcp = data.mcp; const dir = opencodePluginDir(file); - const listed = PLUGIN_KEYS.some((k) => - pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY || p === dir), - ); - return (isPlainMcpObject(mcp) && "bili" in mcp) || listed - ? "installed" - : "not installed"; + const listed = PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY || p === dir)); + return (isPlainMcpObject(mcp) && "bili" in mcp) || listed ? "installed" : "not installed"; } // — dsh ———————————————————————————————————————————————————————————————— @@ -2133,8 +1626,7 @@ function dshInstall(): string { const dirs = dshProfileDirs(); const notes: string[] = []; for (const dir of dirs) { - if (stripLegacyManagedBlock(dir)) - notes.push(`${path.basename(dir)}: legacy managed block stripped`); + if (stripLegacyManagedBlock(dir)) notes.push(`${path.basename(dir)}: legacy managed block stripped`); } const spec = isNpmInstallForm(root) ? DSH_PACKAGE : path.resolve(root); for (const dir of dirs) { @@ -2158,8 +1650,7 @@ function dshRemove(): string { notes.push(`${name}: legacy managed block stripped`); } } - if (touched.size === 0) - return "nothing to remove — no dsh profile carries billion-context"; + if (touched.size === 0) return "nothing to remove — no dsh profile carries billion-context"; return `removed bili from ${touched.size} dsh profile(s) under ${path.join(resolveDshHome(process.env), "profiles")} (${notes.join("; ")}) — restart dsh to finish`; } @@ -2167,14 +1658,10 @@ function dshStatus(): string { const dirs = dshProfileDirs(); const bundle = dirs.filter((dir) => dshBundleInstalled(dir)); const withBlock = dirs.filter((dir) => dshHasLegacyManagedBlock(dir)); - if (bundle.length === dirs.length && dirs.length > 0) - return `installed (dsh bundle in all ${dirs.length} profiles)`; - if (bundle.length > 0) - return `installed as a dsh bundle in ${bundle.length}/${dirs.length} profiles`; - if (withBlock.length === dirs.length && dirs.length > 0) - return "installed (legacy managed block — rerun 'bili plugin install dsh' to migrate to the dsh bundle channel)"; - if (withBlock.length > 0) - return `legacy managed block in ${withBlock.length}/${dirs.length} profiles — rerun 'bili plugin install dsh' to migrate`; + if (bundle.length === dirs.length && dirs.length > 0) return `installed (dsh bundle in all ${dirs.length} profiles)`; + if (bundle.length > 0) return `installed as a dsh bundle in ${bundle.length}/${dirs.length} profiles`; + if (withBlock.length === dirs.length && dirs.length > 0) return "installed (legacy managed block — rerun 'bili plugin install dsh' to migrate to the dsh bundle channel)"; + if (withBlock.length > 0) return `legacy managed block in ${withBlock.length}/${dirs.length} profiles — rerun 'bili plugin install dsh' to migrate`; return "not installed"; } @@ -2184,18 +1671,14 @@ function dshStatus(): string { * rejects duplicate loader entry ids across layers, so a second * `id: bili-native` insert would hard-fail dsh boot whenever the persistent * install is present. */ -export function dshNativeInstalled( - env: NodeJS.ProcessEnv = process.env, -): boolean { +export function dshNativeInstalled(env: NodeJS.ProcessEnv = process.env): boolean { let dirs: string[]; try { dirs = dshProfileDirs(env); } catch { return false; } - return dirs.some( - (dir) => dshBundleInstalled(dir) || dshHasLegacyManagedBlock(dir), - ); + return dirs.some((dir) => dshBundleInstalled(dir) || dshHasLegacyManagedBlock(dir)); } // — kimi ———————————————————————————————————————————————————————————————— @@ -2234,35 +1717,22 @@ interface KimiInstalledRecord { /** installed.json is machine-managed (kimi's own store writes it too) but is * not user-authored prose — a corrupt registry is surfaced loudly instead of * being silently re-created (§7.3). */ -function readKimiInstalledRegistry(file: string): { - version: number; - plugins: KimiInstalledRecord[]; -} { +function readKimiInstalledRegistry(file: string): { version: number; plugins: KimiInstalledRecord[] } { let text: string; try { text = fs.readFileSync(file, "utf8"); } catch (err) { - if ((err as { code?: string }).code === "ENOENT") - return { version: 1, plugins: [] }; + if ((err as { code?: string }).code === "ENOENT") return { version: 1, plugins: [] }; throw err; } let parsed: { version?: unknown; plugins?: unknown }; try { parsed = JSON.parse(text) as { version?: unknown; plugins?: unknown }; } catch (err) { - throw new Error( - `${file} is corrupt (invalid JSON) — fix or remove it, then retry`, - { cause: err }, - ); - } - if (!Array.isArray(parsed.plugins)) - throw new Error( - `${file} is corrupt (no plugins array) — fix or remove it, then retry`, - ); - return { - version: typeof parsed.version === "number" ? parsed.version : 1, - plugins: parsed.plugins as KimiInstalledRecord[], - }; + throw new Error(`${file} is corrupt (invalid JSON) — fix or remove it, then retry`, { cause: err }); + } + if (!Array.isArray(parsed.plugins)) throw new Error(`${file} is corrupt (no plugins array) — fix or remove it, then retry`); + return { version: typeof parsed.version === "number" ? parsed.version : 1, plugins: parsed.plugins as KimiInstalledRecord[] }; } function writeJsonAtomic(file: string, data: unknown): void { @@ -2277,58 +1747,29 @@ function writeJsonAtomic(file: string, data: unknown): void { * an old one throws with launcher-mode guidance rather than writing a dead * manifest. */ function detectKimiVersion(env: NodeJS.ProcessEnv = process.env): string { - const candidates: Array<{ cmd: string; viaShell: boolean }> = - process.platform === "win32" + const candidates: Array<{ cmd: string; viaShell: boolean }> = process.platform === "win32" ? [{ cmd: "kimi --version", viaShell: true }] - : [ - { cmd: "kimi", viaShell: false }, - { - cmd: path.join(resolveKimiHome(env), "bin", "kimi"), - viaShell: false, - }, - ]; + : [{ cmd: "kimi", viaShell: false }, { cmd: path.join(resolveKimiHome(env), "bin", "kimi"), viaShell: false }]; let out: string | undefined; for (const c of candidates) { try { out = c.viaShell - ? execFileSync(c.cmd, { - shell: true, - timeout: 5000, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }) - : execFileSync(c.cmd, ["--version"], { - timeout: 5000, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }); + ? execFileSync(c.cmd, { shell: true, timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }) + : execFileSync(c.cmd, ["--version"], { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }); break; } catch {} } - if (out === undefined) - throw new Error( - "kimi CLI not found on PATH or in $KIMI_CODE_HOME/bin — install Kimi Code first (`npm i -g @moonshot-ai/kimi-code`)", - ); + if (out === undefined) throw new Error("kimi CLI not found on PATH or in $KIMI_CODE_HOME/bin — install Kimi Code first (`npm i -g @moonshot-ai/kimi-code`)"); const m = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(out); if (m && parseInt(m[1], 10) < 2) { - throw new Error( - `Kimi Code ${m[0]} is too old for native mode (needs >= 2.0.0) — upgrade with \`npm i -g @moonshot-ai/kimi-code@latest\` and retry; \`bili kimi\` launcher mode still works`, - ); + throw new Error(`Kimi Code ${m[0]} is too old for native mode (needs >= 2.0.0) — upgrade with \`npm i -g @moonshot-ai/kimi-code@latest\` and retry; \`bili kimi\` launcher mode still works`); } return m ? m[0] : out.trim(); } function selfVersion(): string { try { - return ( - ( - JSON.parse( - fs.readFileSync(path.join(selfPackageRoot(), "package.json"), "utf8"), - ) as { version?: string } - ).version ?? "0.0.0" - ); + return (JSON.parse(fs.readFileSync(path.join(selfPackageRoot(), "package.json"), "utf8")) as { version?: string }).version ?? "0.0.0"; } catch { return "0.0.0"; } @@ -2339,22 +1780,8 @@ function kimiPluginManifest(root: string): Record { name: KIMI_PLUGIN_ID, version: selfVersion(), description: "billion-context: ACP context-compression proxy (native mode)", - mcpServers: { - bili: { - command: "node", - args: [path.join(root, "dist", "kimi", "native-mcp.js")], - cwd: "./", - }, - }, - hooks: [ - { - event: "SessionStart", - command: portableHookCommand("node", [ - path.join(root, "dist", "kimi", "bootstrap-hook.js"), - ]), - timeout: 30, - }, - ], + mcpServers: { bili: { command: "node", args: [path.join(root, "dist", "kimi", "native-mcp.js")], cwd: "./" } }, + hooks: [{ event: "SessionStart", command: portableHookCommand("node", [path.join(root, "dist", "kimi", "bootstrap-hook.js")]), timeout: 30 }], }; } @@ -2365,26 +1792,14 @@ function kimiInstall(): string { const version = detectKimiVersion(); const dir = kimiManagedDir(); fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync( - path.join(dir, "kimi.plugin.json"), - `${JSON.stringify(kimiPluginManifest(root), null, 2)}\n`, - ); + fs.writeFileSync(path.join(dir, "kimi.plugin.json"), `${JSON.stringify(kimiPluginManifest(root), null, 2)}\n`); const file = kimiRegistryFile(); backupBeforeWrite(file); const reg = readKimiInstalledRegistry(file); const now = new Date().toISOString(); const existing = reg.plugins.find((p) => p.id === KIMI_PLUGIN_ID); - const record: KimiInstalledRecord = { - id: KIMI_PLUGIN_ID, - root: dir, - source: "local-path", - enabled: true, - installedAt: existing?.installedAt ?? now, - updatedAt: now, - }; - reg.plugins = existing - ? reg.plugins.map((p) => (p.id === KIMI_PLUGIN_ID ? record : p)) - : [...reg.plugins, record]; + const record: KimiInstalledRecord = { id: KIMI_PLUGIN_ID, root: dir, source: "local-path", enabled: true, installedAt: existing?.installedAt ?? now, updatedAt: now }; + reg.plugins = existing ? reg.plugins.map((p) => (p.id === KIMI_PLUGIN_ID ? record : p)) : [...reg.plugins, record]; writeJsonAtomic(file, reg); return `wrote the billion-context plugin into ${dir} (kimi ${version}) — start a new Kimi Code session to activate`; } @@ -2400,34 +1815,22 @@ function kimiRemove(): string { try { const reg = readKimiInstalledRegistry(kimiRegistryFile()); const rest = reg.plugins.filter((p) => p.id !== KIMI_PLUGIN_ID); - if (rest.length !== reg.plugins.length) - writeJsonAtomic(kimiRegistryFile(), { - version: reg.version, - plugins: rest, - }); + if (rest.length !== reg.plugins.length) writeJsonAtomic(kimiRegistryFile(), { version: reg.version, plugins: rest }); } catch {} const restored = restoreKimiBackup({ log: (msg) => notes.push(msg) }); - if (restored.restored) - notes.push("restored config.toml from the pre-install snapshot"); + if (restored.restored) notes.push("restored config.toml from the pre-install snapshot"); else unrouteKimi({ log: (msg) => notes.push(msg) }); - return removed - ? `removed the billion-context plugin${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new Kimi Code session to finish` - : "not installed"; + return removed ? `removed the billion-context plugin${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new Kimi Code session to finish` : "not installed"; } function kimiStatus(): string { - const manifestOk = fs.existsSync( - path.join(kimiManagedDir(), "kimi.plugin.json"), - ); + const manifestOk = fs.existsSync(path.join(kimiManagedDir(), "kimi.plugin.json")); let registered = false; try { - registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some( - (p) => p.id === KIMI_PLUGIN_ID, - ); + registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some((p) => p.id === KIMI_PLUGIN_ID); } catch {} if (manifestOk && registered) return "installed"; - if (manifestOk || registered) - return "partially installed — rerun 'bili plugin install kimi' to fix"; + if (manifestOk || registered) return "partially installed — rerun 'bili plugin install kimi' to fix"; return "not installed"; } @@ -2441,8 +1844,7 @@ function kimiStatus(): string { const HERMES_PLUGIN_ID = "billion-context"; // cmd.exe's canonical "command missing" line (its exit code is not reliably // 9009 when spawned via CreateProcess — CI-verified). -const CMD_NOT_FOUND_RE = - /is not recognized as an internal or external command/i; +const CMD_NOT_FOUND_RE = /is not recognized as an internal or external command/i; function hermesPluginDir(): string { return path.join(resolveHermesHome(process.env), "plugins", HERMES_PLUGIN_ID); @@ -2453,9 +1855,7 @@ interface HermesSidecar { nodePath: string; } -function runHermesCli( - args: string[], -): { ok: true } | { ok: false; reason: string } { +function runHermesCli(args: string[]): { ok: true } | { ok: false; reason: string } { try { // #679 spawn rules: on Windows a bare `hermes` name or a .cmd shim needs the // comspec wrap — a plain execFileSync("hermes") ENOENTs there. planDshSpawn @@ -2468,66 +1868,35 @@ function runHermesCli( windowsVerbatimArguments: plan.windowsVerbatimArguments, windowsHide: true, }); - if (res.error) - return { - ok: false, - reason: - (res.error as NodeJS.ErrnoException).code === "ENOENT" - ? "not-found" - : String(res.error), - }; + if (res.error) return { ok: false, reason: (res.error as NodeJS.ErrnoException).code === "ENOENT" ? "not-found" : String(res.error) }; if (res.status === 0) return { ok: true }; - if ( - process.platform === "win32" && - (res.status === 9009 || CMD_NOT_FOUND_RE.test(res.stderr ?? "")) - ) - return { ok: false, reason: "not-found" }; + if (process.platform === "win32" && (res.status === 9009 || CMD_NOT_FOUND_RE.test(res.stderr ?? ""))) return { ok: false, reason: "not-found" }; const detail = (res.stderr ?? "").trim(); return { ok: false, reason: detail || `exit ${res.status}` }; } catch (err) { - return { - ok: false, - reason: err instanceof Error ? err.message : String(err), - }; + return { ok: false, reason: err instanceof Error ? err.message : String(err) }; } } function hermesInstallCore(): void { const root = selfPackageRoot(); - const initSrc = fs.readFileSync( - path.join(root, "hermes-plugin", "__init__.py"), - "utf8", - ); - const yamlSrc = fs.readFileSync( - path.join(root, "hermes-plugin", "plugin.yaml"), - "utf8", - ); + const initSrc = fs.readFileSync(path.join(root, "hermes-plugin", "__init__.py"), "utf8"); + const yamlSrc = fs.readFileSync(path.join(root, "hermes-plugin", "plugin.yaml"), "utf8"); requireDistFile(path.join(root, "dist", "index.js")); const dir = hermesPluginDir(); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, "__init__.py"), initSrc); - fs.writeFileSync( - path.join(dir, "plugin.yaml"), - yamlSrc.replace(/^version:.*/m, `version: "${selfVersion()}"`), - ); - const sidecar: HermesSidecar = { - proxyScript: path.join(root, "dist", "index.js"), - nodePath: process.execPath, - }; - fs.writeFileSync( - path.join(dir, "bili.json"), - `${JSON.stringify(sidecar, null, 2)}\n`, - ); + fs.writeFileSync(path.join(dir, "plugin.yaml"), yamlSrc.replace(/^version:.*/m, `version: "${selfVersion()}"`)); + const sidecar: HermesSidecar = { proxyScript: path.join(root, "dist", "index.js"), nodePath: process.execPath }; + fs.writeFileSync(path.join(dir, "bili.json"), `${JSON.stringify(sidecar, null, 2)}\n`); } function hermesInstall(): string { hermesInstallCore(); const dir = hermesPluginDir(); const enable = runHermesCli(["plugins", "enable", HERMES_PLUGIN_ID]); - if (enable.ok) - return `wrote the billion-context plugin into ${dir} and enabled it — start a new hermes session to activate`; - const hint = - enable.reason === "not-found" + if (enable.ok) return `wrote the billion-context plugin into ${dir} and enabled it — start a new hermes session to activate`; + const hint = enable.reason === "not-found" ? "the hermes CLI was not found on PATH — enable it manually: hermes plugins enable billion-context" : `enabling via the hermes CLI failed (${enable.reason}) — enable it manually: hermes plugins enable billion-context`; return `wrote the billion-context plugin into ${dir}; ${hint}`; @@ -2545,10 +1914,7 @@ function hermesRemove(): string { function hermesStatus(): string { const dir = hermesPluginDir(); - return fs.existsSync(path.join(dir, "__init__.py")) && - fs.existsSync(path.join(dir, "bili.json")) - ? "installed" - : "not installed"; + return fs.existsSync(path.join(dir, "__init__.py")) && fs.existsSync(path.join(dir, "bili.json")) ? "installed" : "not installed"; } // — dispatch ———————————————————————————————————————————————————————————— @@ -2566,40 +1932,29 @@ function zcodeUserConfigFile(): string { } function zcodeAsPlain(value: unknown): Record | undefined { - return value !== null && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : undefined; + return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record) : undefined; } function zcodeArgsMatch(args: unknown, re: RegExp): boolean { - return ( - Array.isArray(args) && args.some((a) => typeof a === "string" && re.test(a)) - ); + return Array.isArray(args) && args.some((a) => typeof a === "string" && re.test(a)); } function isOursZcodeHookEntry(entry: unknown): boolean { const hooks = zcodeAsPlain(entry)?.hooks; if (!Array.isArray(hooks)) return false; - return hooks.some((h) => - zcodeArgsMatch(zcodeAsPlain(h)?.args, ZCODE_HOOK_ENTRY_RE), - ); + return hooks.some((h) => zcodeArgsMatch(zcodeAsPlain(h)?.args, ZCODE_HOOK_ENTRY_RE)); } function isOursZcodeMcpServer(server: unknown): boolean { const s = zcodeAsPlain(server); - return ( - !!s && s.type === "stdio" && zcodeArgsMatch(s.args, ZCODE_MCP_ENTRY_RE) - ); + return !!s && s.type === "stdio" && zcodeArgsMatch(s.args, ZCODE_MCP_ENTRY_RE); } /** Managed-block apply for ~/.zcode/cli/config.json (#1145). Pure over the * parsed doc: enables hooks, upserts our SessionStart entry, and owns ONLY * mcp.servers.bili when it already points at our dist — a user's own "bili" * server throws instead of being clobbered (§7.3). */ -function applyZcodeManagedConfig( - doc: Record, - opts: { hookEntry: string; mcpEntry: string }, -): { data: Record; notes: string[] } { +function applyZcodeManagedConfig(doc: Record, opts: { hookEntry: string; mcpEntry: string }): { data: Record; notes: string[] } { const data = structuredClone(doc); const notes: string[] = []; const hooks = zcodeAsPlain(data.hooks) ?? {}; @@ -2608,24 +1963,17 @@ function applyZcodeManagedConfig( notes.push("enabled hooks (hooks.enabled was off)"); } const events = zcodeAsPlain(hooks.events) ?? {}; - const sessionStart = Array.isArray(events.SessionStart) - ? [...(events.SessionStart as unknown[])] - : []; + const sessionStart = Array.isArray(events.SessionStart) ? [...(events.SessionStart as unknown[])] : []; const kept = sessionStart.filter((e) => !isOursZcodeHookEntry(e)); - if (kept.length !== sessionStart.length) - notes.push("replaced a previous bili SessionStart entry"); - kept.push({ - hooks: [{ type: "process", command: "node", args: [opts.hookEntry] }], - }); + if (kept.length !== sessionStart.length) notes.push("replaced a previous bili SessionStart entry"); + kept.push({ hooks: [{ type: "process", command: "node", args: [opts.hookEntry] }] }); events.SessionStart = kept; hooks.events = events; data.hooks = hooks; const mcp = zcodeAsPlain(data.mcp) ?? {}; const servers = zcodeAsPlain(mcp.servers) ?? {}; if (servers.bili !== undefined && !isOursZcodeMcpServer(servers.bili)) { - throw new Error( - `${zcodeUserConfigFile()} already defines mcp.servers.bili owned by something else — rename or remove it first; refusing to overwrite`, - ); + throw new Error(`${zcodeUserConfigFile()} already defines mcp.servers.bili owned by something else — rename or remove it first; refusing to overwrite`); } servers.bili = { type: "stdio", command: "node", args: [opts.mcpEntry] }; mcp.servers = servers; @@ -2633,19 +1981,14 @@ function applyZcodeManagedConfig( return { data, notes }; } -function stripZcodeManagedConfig(doc: Record): { - data: Record; - removed: string[]; -} { +function stripZcodeManagedConfig(doc: Record): { data: Record; removed: string[] } { const data = structuredClone(doc); const removed: string[] = []; const hooks = zcodeAsPlain(data.hooks); if (hooks) { const events = zcodeAsPlain(hooks.events); if (events && Array.isArray(events.SessionStart)) { - const kept = (events.SessionStart as unknown[]).filter( - (e) => !isOursZcodeHookEntry(e), - ); + const kept = (events.SessionStart as unknown[]).filter((e) => !isOursZcodeHookEntry(e)); if (kept.length !== (events.SessionStart as unknown[]).length) { removed.push("hooks.events.SessionStart entry"); if (kept.length > 0) events.SessionStart = kept; @@ -2658,11 +2001,7 @@ function stripZcodeManagedConfig(doc: Record): { const mcp = zcodeAsPlain(data.mcp); if (mcp) { const servers = zcodeAsPlain(mcp.servers); - if ( - servers && - servers.bili !== undefined && - isOursZcodeMcpServer(servers.bili) - ) { + if (servers && servers.bili !== undefined && isOursZcodeMcpServer(servers.bili)) { removed.push("mcp.servers.bili"); delete servers.bili; if (Object.keys(servers).length === 0) delete mcp.servers; @@ -2679,10 +2018,7 @@ function zcodeInstall(): string { requireDistFile(hookEntry); requireDistFile(mcpEntry); const file = zcodeUserConfigFile(); - const { data, notes } = applyZcodeManagedConfig(readJson(file), { - hookEntry, - mcpEntry, - }); + const { data, notes } = applyZcodeManagedConfig(readJson(file), { hookEntry, mcpEntry }); writeJson(file, data); return `wrote the billion-context hook+MCP into ${file}${notes.length > 0 ? ` (${notes.join("; ")})` : ""} — start a new ZCode session to activate`; } @@ -2698,10 +2034,7 @@ function zcodeRemove(): string { // are the reason it is on (never drop a user-owned switch). let bak: Record | undefined; try { - bak = JSON.parse(fs.readFileSync(`${file}.bili-bak`, "utf8")) as Record< - string, - unknown - >; + bak = JSON.parse(fs.readFileSync(`${file}.bili-bak`, "utf8")) as Record; } catch {} const hooks = zcodeAsPlain(data.hooks); if (hooks && Object.keys(hooks).length === 1 && hooks.enabled === true) { @@ -2715,9 +2048,7 @@ function zcodeRemove(): string { } catch {} const restored = restoreZcodeBackup({ log: (msg) => notes.push(msg) }); if (!restored.restored) unrouteZcode({ log: () => {} }); - return notes.length > 0 - ? `removed the billion-context zcode lane (${notes.join("; ")}) — start a new ZCode session to finish` - : "not installed"; + return notes.length > 0 ? `removed the billion-context zcode lane (${notes.join("; ")}) — start a new ZCode session to finish` : "not installed"; } function zcodeStatus(): string { @@ -2725,26 +2056,14 @@ function zcodeStatus(): string { let hasMcp = false; try { const doc = readJson(zcodeUserConfigFile()); - const sessionStart = zcodeAsPlain( - zcodeAsPlain(doc.hooks)?.events, - )?.SessionStart; - hasHook = - Array.isArray(sessionStart) && - (sessionStart as unknown[]).some(isOursZcodeHookEntry); - hasMcp = isOursZcodeMcpServer( - zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili, - ); + const sessionStart = zcodeAsPlain(zcodeAsPlain(doc.hooks)?.events)?.SessionStart; + hasHook = Array.isArray(sessionStart) && (sessionStart as unknown[]).some(isOursZcodeHookEntry); + hasMcp = isOursZcodeMcpServer(zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili); } catch {} - let status = - hasHook && hasMcp - ? "installed" - : hasHook || hasMcp - ? "partially installed — rerun 'bili plugin install zcode' to fix" - : "not installed"; + let status = hasHook && hasMcp ? "installed" : hasHook || hasMcp ? "partially installed — rerun 'bili plugin install zcode' to fix" : "not installed"; try { const routed = inspectZcodeRouting(resolveZcodeDataDir(process.env)); - if (routed && routed.wrapped.length > 0) - status += ` (routing ${routed.kind} store: ${routed.wrapped.map((w) => w.id).join(", ")})`; + if (routed && routed.wrapped.length > 0) status += ` (routing ${routed.kind} store: ${routed.wrapped.map((w) => w.id).join(", ")})`; } catch {} return status; } @@ -2762,13 +2081,7 @@ interface LanePresence { targets: string[]; form: "npm" | "local-path" | "managed-block" | "none"; copyVersion?: string; - profiles?: Array<{ - name: string; - spec?: string; - pinned: boolean; - bundleInstalled: boolean; - copyVersion?: string; - }>; + profiles?: Array<{ name: string; spec?: string; pinned: boolean; bundleInstalled: boolean; copyVersion?: string }>; } function laneAbsent(): LanePresence { @@ -2777,11 +2090,7 @@ function laneAbsent(): LanePresence { function pkgVersionAt(rootDir: string): string | undefined { try { - const v = ( - JSON.parse( - fs.readFileSync(path.join(rootDir, "package.json"), "utf8"), - ) as { version?: unknown } - ).version; + const v = (JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8")) as { version?: unknown }).version; return typeof v === "string" ? v : undefined; } catch { return undefined; @@ -2833,13 +2142,8 @@ function compareSpecSlots(a: string, b: string): number { * reads/updates this INNER copy only — it never edits opencode's outer * package.json/package-lock.json nor deletes its cache, so drift between the * outer lockfile and the inner package version is expected and left alone. */ -export function opencodeCacheCopyRoot( - env: NodeJS.ProcessEnv = process.env, -): string | undefined { - const xdgCache = - env.XDG_CACHE_HOME && env.XDG_CACHE_HOME.trim().length > 0 - ? env.XDG_CACHE_HOME - : path.join(os.homedir(), ".cache"); +export function opencodeCacheCopyRoot(env: NodeJS.ProcessEnv = process.env): string | undefined { + const xdgCache = env.XDG_CACHE_HOME && env.XDG_CACHE_HOME.trim().length > 0 ? env.XDG_CACHE_HOME : path.join(os.homedir(), ".cache"); const npm = path.join(xdgCache, "opencode", "npm"); let slots: string[]; try { @@ -2847,10 +2151,7 @@ export function opencodeCacheCopyRoot( } catch { return undefined; } - for (const slot of slots - .filter((s) => s.startsWith("billion-context@")) - .sort(compareSpecSlots) - .reverse()) { + for (const slot of slots.filter((s) => s.startsWith("billion-context@")).sort(compareSpecSlots).reverse()) { let stamps: string[]; try { stamps = fs.readdirSync(path.join(npm, slot)); @@ -2905,9 +2206,7 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { return laneAbsent(); } const lines = text.split("\n"); - const values = ompExtensionItemLines(text) - .map((i) => ompEntryValue(lines[i]!)) - .filter((v) => OMP_ENTRY_RE.test(v)); + const values = ompExtensionItemLines(text).map((i) => ompEntryValue(lines[i]!)).filter((v) => OMP_ENTRY_RE.test(v)); if (values.length === 0) return laneAbsent(); const targets = values.filter((v) => path.isAbsolute(v)); const first = targets[0]; @@ -2916,42 +2215,31 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { pointers: values, targets, form: "local-path", - copyVersion: - first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, + copyVersion: first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, }; } if (agent === "claude") { const out = laneAbsent(); try { const data = readJson(claudeSettingsFile()); - const baseUrl = (data.env as Record | undefined) - ?.ANTHROPIC_BASE_URL; + const baseUrl = (data.env as Record | undefined)?.ANTHROPIC_BASE_URL; if (typeof baseUrl === "string" && isBiliClaudeBaseUrl(baseUrl)) { out.installed = true; out.pointers.push(`env.ANTHROPIC_BASE_URL=${baseUrl}`); } } catch {} try { - const mcpData = readJson(claudeMcpJson()) as { - mcpServers?: Record; - }; + const mcpData = readJson(claudeMcpJson()) as { mcpServers?: Record }; const bili = mcpData.mcpServers?.bili; if (bili !== null && typeof bili === "object" && !Array.isArray(bili)) { const s = bili as Record; out.installed = true; - const args = Array.isArray(s.args) - ? (s.args as unknown[]).map(String) - : []; - out.pointers.push( - [s.command, ...args] - .filter((x) => typeof x === "string" && x.length > 0) - .join(" "), - ); + const args = Array.isArray(s.args) ? (s.args as unknown[]).map(String) : []; + out.pointers.push([s.command, ...args].filter((x) => typeof x === "string" && x.length > 0).join(" ")); const script = args[0]; if (script !== undefined && path.isAbsolute(script)) { out.targets.push(script); - out.copyVersion = - out.copyVersion ?? pkgVersionAt(rootFromDistFile(script)); + out.copyVersion = out.copyVersion ?? pkgVersionAt(rootFromDistFile(script)); } } } catch {} @@ -2969,14 +2257,11 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { const start = text.indexOf("[mcp_servers.bili]"); const rest = text.slice(start); const nextSection = /^\[[^\]\n]+\]/m.exec(rest.slice(1)); - const block = - nextSection !== null ? rest.slice(0, 1 + nextSection.index) : rest; + const block = nextSection !== null ? rest.slice(0, 1 + nextSection.index) : rest; const unquote = (raw: string): string => { try { const parsed: unknown = JSON.parse(raw); - return typeof parsed === "string" - ? parsed - : raw.replace(/^["']|["']$/g, ""); + return typeof parsed === "string" ? parsed : raw.replace(/^["']|["']$/g, ""); } catch { return raw.replace(/^["']|["']$/g, ""); } @@ -2987,26 +2272,19 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { let args: string[] = []; if (argsMatch?.[1]) { try { - args = (JSON.parse(`[${argsMatch[1]}]`) as unknown[]).filter( - (x): x is string => typeof x === "string", - ); + args = (JSON.parse(`[${argsMatch[1]}]`) as unknown[]).filter((x): x is string => typeof x === "string"); } catch { - args = [...argsMatch[1].matchAll(/["']([^"']*)["']/g)].map( - (m) => m[1]!, - ); + args = [...argsMatch[1].matchAll(/["']([^"']*)["']/g)].map((m) => m[1]!); } } const targets = args.filter((a) => path.isAbsolute(a) && /\.js$/.test(a)); const first = targets[0]; const out: LanePresence = { installed: true, - pointers: [ - `[mcp_servers.bili] command=${command || "?"} args=[${args.join(", ")}]`, - ], + pointers: [`[mcp_servers.bili] command=${command || "?"} args=[${args.join(", ")}]`], targets, form: "managed-block", - copyVersion: - first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, + copyVersion: first !== undefined ? pkgVersionAt(rootFromDistFile(first)) : undefined, }; // Ticket 08 faces, reported next to (never instead of) the MCP block: a // session hook and the ACP skill are separate integration surfaces, so a @@ -3015,38 +2293,22 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { if (hookCommand !== undefined) { out.pointers.push(`hooks.SessionStart: ${hookCommand}`); const hookDisabled = codexHooksEnabledNote(text); - if (hookDisabled !== "") - out.pointers.push(`hooks disabled — ${hookDisabled}`); + if (hookDisabled !== "") out.pointers.push(`hooks disabled — ${hookDisabled}`); } else { out.pointers.push("hooks.SessionStart: not installed"); } const skillState = codexSkillStatus(process.env); - out.pointers.push( - skillState === "installed" - ? `skill: ${codexSkillFile(process.env)}` - : skillState === "outdated" - ? "skill: outdated (rerun install)" - : skillState === "foreign" - ? "skill: not owned by bili (left untouched)" - : "skill: not installed", - ); + out.pointers.push(skillState === "installed" ? `skill: ${codexSkillFile(process.env)}` : skillState === "outdated" ? "skill: outdated (rerun install)" : skillState === "foreign" ? "skill: not owned by bili (left untouched)" : "skill: not installed"); return out; } if (agent === "opencode") { const file = opencodeTargetFile(); const { data } = loadOpencodeConfig(file); const dir = opencodePluginDir(file); - const listed = PLUGIN_KEYS.flatMap((k) => pluginEntries(data, k)).filter( - (p) => p === OPENCODE_NPM_ENTRY || p === dir, - ); + const listed = PLUGIN_KEYS.flatMap((k) => pluginEntries(data, k)).filter((p) => p === OPENCODE_NPM_ENTRY || p === dir); const hasMcp = isPlainMcpObject(data.mcp) && "bili" in data.mcp; if (listed.length === 0 && !hasMcp) return laneAbsent(); - const out: LanePresence = { - installed: true, - pointers: [...listed], - targets: [], - form: "none", - }; + const out: LanePresence = { installed: true, pointers: [...listed], targets: [], form: "none" }; if (hasMcp) out.pointers.push("mcp.bili"); if (listed.includes(OPENCODE_NPM_ENTRY)) { out.form = "npm"; @@ -3076,17 +2338,13 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { const spec = dshProfileDepSpec(dir); const bundled = dshBundleInstalled(dir); if (spec === undefined && !bundled) return []; - return [ - { + return [{ name: path.basename(dir), spec, pinned: spec !== undefined && !isRegistryDepSpec(spec), bundleInstalled: bundled, - copyVersion: bundled - ? pkgVersionAt(path.join(dir, "node_modules", DSH_PACKAGE)) - : undefined, - }, - ]; + copyVersion: bundled ? pkgVersionAt(path.join(dir, "node_modules", DSH_PACKAGE)) : undefined, + }]; }); if (profiles.length === 0) return laneAbsent(); return { @@ -3102,44 +2360,24 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { const manifestOk = fs.existsSync(manifestFile); let registered = false; try { - registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some( - (p) => p.id === KIMI_PLUGIN_ID, - ); + registered = readKimiInstalledRegistry(kimiRegistryFile()).plugins.some((p) => p.id === KIMI_PLUGIN_ID); } catch {} if (!manifestOk && !registered) return laneAbsent(); - const out: LanePresence = { - installed: manifestOk && registered, - pointers: [], - targets: [], - form: "local-path", - }; - if (!out.installed) - out.pointers.push( - manifestOk - ? "manifest present but registry record missing" - : "registry record present but manifest missing", - ); + const out: LanePresence = { installed: manifestOk && registered, pointers: [], targets: [], form: "local-path" }; + if (!out.installed) out.pointers.push(manifestOk ? "manifest present but registry record missing" : "registry record present but manifest missing"); try { - const man = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as Record< - string, - unknown - >; + const man = JSON.parse(fs.readFileSync(manifestFile, "utf8")) as Record; if (typeof man.version === "string") out.copyVersion = man.version; const mcpArgs = zcodeAsPlain(zcodeAsPlain(man.mcpServers)?.bili)?.args; - for (const a of Array.isArray(mcpArgs) - ? (mcpArgs as unknown[]).map(String) - : []) { + for (const a of Array.isArray(mcpArgs) ? (mcpArgs as unknown[]).map(String) : []) { if (path.isAbsolute(a)) out.targets.push(a); } const hookCmd = Array.isArray(man.hooks) - ? (man.hooks as unknown[]) - .map((h) => zcodeAsPlain(h)?.command) - .find((c): c is string => typeof c === "string") + ? (man.hooks as unknown[]).map((h) => zcodeAsPlain(h)?.command).find((c): c is string => typeof c === "string") : undefined; if (hookCmd !== undefined) { const script = hookCmd.trim().split(/\s+/).pop(); - if (script !== undefined && path.isAbsolute(script)) - out.targets.push(script); + if (script !== undefined && path.isAbsolute(script)) out.targets.push(script); } } catch {} return out; @@ -3147,21 +2385,10 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { if (agent === "hermes") { const dir = hermesPluginDir(); if (!fs.existsSync(path.join(dir, "__init__.py"))) return laneAbsent(); - const out: LanePresence = { - installed: true, - pointers: [dir], - targets: [], - form: "local-path", - }; + const out: LanePresence = { installed: true, pointers: [dir], targets: [], form: "local-path" }; try { - const sidecar = JSON.parse( - fs.readFileSync(path.join(dir, "bili.json"), "utf8"), - ) as HermesSidecar; - if ( - typeof sidecar.proxyScript === "string" && - sidecar.proxyScript.length > 0 - ) - out.targets.push(sidecar.proxyScript); + const sidecar = JSON.parse(fs.readFileSync(path.join(dir, "bili.json"), "utf8")) as HermesSidecar; + if (typeof sidecar.proxyScript === "string" && sidecar.proxyScript.length > 0) out.targets.push(sidecar.proxyScript); } catch {} try { const yaml = fs.readFileSync(path.join(dir, "plugin.yaml"), "utf8"); @@ -3172,31 +2399,15 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { } // zcode const doc = readJson(zcodeUserConfigFile()); - const sessionStart = zcodeAsPlain( - zcodeAsPlain(doc.hooks)?.events, - )?.SessionStart; - const hasHook = - Array.isArray(sessionStart) && - (sessionStart as unknown[]).some(isOursZcodeHookEntry); + const sessionStart = zcodeAsPlain(zcodeAsPlain(doc.hooks)?.events)?.SessionStart; + const hasHook = Array.isArray(sessionStart) && (sessionStart as unknown[]).some(isOursZcodeHookEntry); const mcpBili = zcodeAsPlain(zcodeAsPlain(doc.mcp)?.servers)?.bili; const hasMcp = isOursZcodeMcpServer(mcpBili); if (!hasHook && !hasMcp) return laneAbsent(); - const out: LanePresence = { - installed: hasHook && hasMcp, - pointers: [], - targets: [], - form: "managed-block", - }; - if (!out.installed) - out.pointers.push( - hasHook - ? "hook present, MCP face missing" - : "MCP face present, hook missing", - ); + const out: LanePresence = { installed: hasHook && hasMcp, pointers: [], targets: [], form: "managed-block" }; + if (!out.installed) out.pointers.push(hasHook ? "hook present, MCP face missing" : "MCP face present, hook missing"); const collectArgs = (args: unknown): void => { - for (const a of Array.isArray(args) - ? (args as unknown[]).map(String) - : []) { + for (const a of Array.isArray(args) ? (args as unknown[]).map(String) : []) { if (path.isAbsolute(a) && /\.(js|ts)$/.test(a)) out.targets.push(a); } }; @@ -3204,14 +2415,12 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { for (const e of sessionStart as unknown[]) { if (!isOursZcodeHookEntry(e)) continue; const hooks = zcodeAsPlain(e)?.hooks; - if (Array.isArray(hooks)) - for (const h of hooks as unknown[]) collectArgs(zcodeAsPlain(h)?.args); + if (Array.isArray(hooks)) for (const h of hooks as unknown[]) collectArgs(zcodeAsPlain(h)?.args); } } if (hasMcp) collectArgs(zcodeAsPlain(mcpBili)?.args); const first = out.targets[0]; - if (first !== undefined) - out.copyVersion = pkgVersionAt(rootFromDistFile(first)); + if (first !== undefined) out.copyVersion = pkgVersionAt(rootFromDistFile(first)); return out; } @@ -3219,47 +2428,12 @@ export function isPluginAgent(value: string): value is PluginAgent { return (PLUGIN_AGENTS as readonly string[]).includes(value); } -export function pluginInstall( - agent: PluginAgent, - opts: { withMcp?: boolean } = {}, -): string { - return agent === "pi" - ? piInstall() - : agent === "omp" - ? ompInstall() - : agent === "claude" - ? claudeInstall() - : agent === "codex" - ? codexInstall() - : agent === "dsh" - ? dshInstall() - : agent === "kimi" - ? kimiInstall() - : agent === "hermes" - ? hermesInstall() - : agent === "zcode" - ? zcodeInstall() - : opencodeInstall(opts.withMcp === true); +export function pluginInstall(agent: PluginAgent, opts: { withMcp?: boolean } = {}): string { + return agent === "pi" ? piInstall() : agent === "omp" ? ompInstall() : agent === "claude" ? claudeInstall() : agent === "codex" ? codexInstall() : agent === "dsh" ? dshInstall() : agent === "kimi" ? kimiInstall() : agent === "hermes" ? hermesInstall() : agent === "zcode" ? zcodeInstall() : opencodeInstall(opts.withMcp === true); } export function pluginRemove(agent: PluginAgent): string { - return agent === "pi" - ? piRemove() - : agent === "omp" - ? ompRemove() - : agent === "claude" - ? claudeRemove() - : agent === "codex" - ? codexRemove() - : agent === "dsh" - ? dshRemove() - : agent === "kimi" - ? kimiRemove() - : agent === "hermes" - ? hermesRemove() - : agent === "zcode" - ? zcodeRemove() - : opencodeRemove(); + return agent === "pi" ? piRemove() : agent === "omp" ? ompRemove() : agent === "claude" ? claudeRemove() : agent === "codex" ? codexRemove() : agent === "dsh" ? dshRemove() : agent === "kimi" ? kimiRemove() : agent === "hermes" ? hermesRemove() : agent === "zcode" ? zcodeRemove() : opencodeRemove(); } /** #2155 uninstall guardrail (advisory half): `bili plugin remove ` @@ -3268,32 +2442,19 @@ export function pluginRemove(agent: PluginAgent): string { * but the session binding is sticky). The proxy side self-heals those sessions * (degrade to proxy mode); this note closes the loop for the human. Best-effort: * any failure (no proxy, endpoint down, odd shape) stays silent. */ -export async function warnActivePluginSessions( - agent: PluginAgent, -): Promise { +export async function warnActivePluginSessions(agent: PluginAgent): Promise { try { const inst = readProxyInstanceFile(); if (inst === undefined) return ""; - const res = await fetch( - inst.origin.replace(/\/$/, "") + "/__bili/sessions", - { - signal: AbortSignal.timeout(2500), - headers: { accept: "application/json" }, - }, - ); + const res = await fetch(inst.origin.replace(/\/$/, "") + "/__bili/sessions", { signal: AbortSignal.timeout(2500), headers: { accept: "application/json" } }); if (!res.ok) return ""; - const data = (await res.json()) as { - sessions?: Array>; - }; + const data = (await res.json()) as { sessions?: Array> }; const sessions = Array.isArray(data.sessions) ? data.sessions : []; const cutoff = Date.now() - 10 * 60 * 1000; let live = 0; for (const s of sessions) { const hint = typeof s["clientHint"] === "string" ? s["clientHint"] : ""; - const seen = - typeof s["lastSeen"] === "string" - ? Date.parse(s["lastSeen"]) - : Number.NaN; + const seen = typeof s["lastSeen"] === "string" ? Date.parse(s["lastSeen"]) : Number.NaN; if (hint === agent && Number.isFinite(seen) && seen >= cutoff) live += 1; } if (live === 0) return ""; @@ -3319,13 +2480,7 @@ export interface PluginStatusRow { function laneCopyVersion(presence: LanePresence): string | undefined { if (!presence.installed) return undefined; if (presence.profiles !== undefined) { - const set = [ - ...new Set( - presence.profiles - .map((p) => p.copyVersion) - .filter((v): v is string => v !== undefined), - ), - ]; + const set = [...new Set(presence.profiles.map((p) => p.copyVersion).filter((v): v is string => v !== undefined))]; return set.length > 0 ? set.join(",") : undefined; } return presence.copyVersion; @@ -3351,19 +2506,9 @@ export function pluginStatusAll(): PluginStatusRow[] { copyVersion = undefined; } try { - return { - agent, - status: check(), - channel: UPDATE_CHANNEL[agent], - copyVersion, - }; + return { agent, status: check(), channel: UPDATE_CHANNEL[agent], copyVersion }; } catch (err) { - return { - agent, - status: `error: ${err instanceof Error ? err.message : String(err)}`, - channel: UPDATE_CHANNEL[agent], - copyVersion, - }; + return { agent, status: `error: ${err instanceof Error ? err.message : String(err)}`, channel: UPDATE_CHANNEL[agent], copyVersion }; } }); } @@ -3381,12 +2526,10 @@ export const UPDATE_CHANNEL: Record = { omp: "the global bili install (entry points at it)", claude: "the global bili install (hook/MCP point at it)", codex: "the global bili install (the mcp launcher shells out to it)", - opencode: - "the cache copy self-updates in place via its own proxy (#1234); OpenCode v2 'plugin update' is an extra manual channel — reload/restart OpenCode after a disk update to activate", + opencode: "the cache copy self-updates in place via its own proxy (#1234); OpenCode v2 'plugin update' is an extra manual channel — reload/restart OpenCode after a disk update to activate", dsh: "the global bili self-update (profile bundles track it)", kimi: "the global bili install (plugin points at its dist)", - hermes: - "the global bili install (sidecar points at its dist); `bili plugin update hermes` re-copies the plugin", + hermes: "the global bili install (sidecar points at its dist); `bili plugin update hermes` re-copies the plugin", zcode: "the global bili install (hook/MCP point at its dist)", }; @@ -3406,31 +2549,20 @@ export function renderPluginList(rows: PluginStatusRow[]): string { }; }); const wAgent = Math.max("agent".length, ...cells.map((c) => c.agent.length)); - const wVersion = Math.max( - "version".length, - ...cells.map((c) => c.version.length), - ); + const wVersion = Math.max("version".length, ...cells.map((c) => c.version.length)); // Status is unbounded free text (multi-profile summaries, probe errors that // carry file paths) — cap the padded width so one long row cannot stretch // every other row out; an over-long status simply overflows its own row // rather than being truncated. const STATUS_CAP = 52; - const wStatus = Math.min( - STATUS_CAP, - Math.max("status".length, ...cells.map((c) => c.status.length)), - ); + const wStatus = Math.min(STATUS_CAP, Math.max("status".length, ...cells.map((c) => c.status.length))); const padTo = (s: string, w: number): string => s.padEnd(w); const lines: string[] = []; - lines.push( - `${padTo("agent", wAgent)} ${padTo("status", wStatus)} ${padTo("version", wVersion)} updates via`, - ); + lines.push(`${padTo("agent", wAgent)} ${padTo("status", wStatus)} ${padTo("version", wVersion)} updates via`); for (const c of cells) { - const statusCell = - c.status.length > wStatus ? c.status : padTo(c.status, wStatus); + const statusCell = c.status.length > wStatus ? c.status : padTo(c.status, wStatus); const body = `${padTo(c.agent, wAgent)} ${statusCell} ${padTo(c.version, wVersion)}`; - lines.push( - (c.channel === "" ? body : `${body} ${c.channel}`).replace(/\s+$/, ""), - ); + lines.push((c.channel === "" ? body : `${body} ${c.channel}`).replace(/\s+$/, "")); } return `${lines.join("\n")}\n`; } @@ -3460,49 +2592,34 @@ interface PluginUpdateOpts { * through dsh's own plugin channel. * Returns user-facing lines. Network is only touched when a dsh profile * actually depends on bili (version lookup) or globalCheck is provided. */ -export async function pluginUpdate( - agents: readonly PluginAgent[] | undefined, - opts: PluginUpdateOpts, -): Promise { +export async function pluginUpdate(agents: readonly PluginAgent[] | undefined, opts: PluginUpdateOpts): Promise { const log = opts.log ?? (() => {}); const lines: string[] = []; if (opts.globalCheck) { await opts.globalCheck(); - lines.push( - "global bili copy: update check ran (see log above; it skips copies owned by a host)", - ); + lines.push("global bili copy: update check ran (see log above; it skips copies owned by a host)"); } for (const agent of agents ?? PLUGIN_AGENTS) { try { - lines.push(...(await updateLane(agent as PluginAgent, opts, log))); + lines.push(...await updateLane(agent as PluginAgent, opts, log)); } catch (err) { - lines.push( - `${agent}: update failed — ${err instanceof Error ? err.message : String(err)}`, - ); + lines.push(`${agent}: update failed — ${err instanceof Error ? err.message : String(err)}`); } } return lines; } -async function updateLane( - agent: PluginAgent, - opts: PluginUpdateOpts, - log: (level: "info" | "warn", msg: string) => void, -): Promise { +async function updateLane(agent: PluginAgent, opts: PluginUpdateOpts, log: (level: "info" | "warn", msg: string) => void): Promise { if (agent === "pi") { const list = piPackageStrings(readJson(piSettingsFile()).packages); const root = selfPackageRoot(); // #2850: versioned npm specs (@pinned/@latest) are the same pi-managed // copy, not a checkout pointer — route them to the same message. if (list.some((p) => /^npm:billion-context(@|$)/.test(p))) { - return [ - "pi: the plugin copy is pi-managed (npm:billion-context) — `pi update` upgrades it; bili never overwrites it (#991)", - ]; + return ["pi: the plugin copy is pi-managed (npm:billion-context) — `pi update` upgrades it; bili never overwrites it (#991)"]; } if (list.some((p) => isPiEntry(p, root))) { - return [ - "pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes", - ]; + return ["pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; } return ["pi: not installed"]; } @@ -3510,25 +2627,15 @@ async function updateLane( const file = opencodeTargetFile(); const { data } = loadOpencodeConfig(file); const dir = opencodePluginDir(file); - if ( - PLUGIN_KEYS.some((k) => - pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY), - ) - ) { + if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY))) { const root = opencodeCacheCopyRoot(); const ver = root !== undefined ? pkgVersionAt(root) : undefined; const where = root !== undefined ? ` (${root})` : ""; const v = ver !== undefined ? ` v${ver}` : ""; - return [ - `opencode: the cache copy is bili-owned and self-updates in place through its own proxy${where}${v} (#1234) — this command does NOT run opencode's upgrade; OpenCode v2 'plugin update' is an extra manual channel, and reload/restart OpenCode after a disk update to activate it`, - ]; + return [`opencode: the cache copy is bili-owned and self-updates in place through its own proxy${where}${v} (#1234) — this command does NOT run opencode's upgrade; OpenCode v2 'plugin update' is an extra manual channel, and reload/restart OpenCode after a disk update to activate it`]; } - if ( - PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir)) - ) { - return [ - "opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes", - ]; + if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir))) { + return ["opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; } return ["opencode: not installed"]; } @@ -3540,13 +2647,9 @@ async function updateLane( return ["dsh: never initialized on this machine — nothing to update"]; } const targets = dirs.filter((dir) => dshProfileDependsOnBili(dir)); - if (targets.length === 0) - return ["dsh: no profile depends on billion-context — nothing to update"]; + if (targets.length === 0) return ["dsh: no profile depends on billion-context — nothing to update"]; const latest = await fetchRegistryVersion(opts, opts.packageName); - if (!latest) - return [ - "dsh: could not resolve the latest version from npm — leaving profile bundles alone", - ]; + if (!latest) return ["dsh: could not resolve the latest version from npm — leaving profile bundles alone"]; const before = targets.length; const { refreshed, failed } = await refreshDshProfileBundles(latest, log); if (failed === 0) { @@ -3555,20 +2658,13 @@ async function updateLane( // wait out the window (up to 6 h). await clearOwnerLaneBackoff("dsh-profile", latest); } - return [ - `dsh: ${refreshed}/${before} profile bundle(s) refreshed to ${latest} through dsh's plugin channel${failed > 0 ? ` (${failed} failed)` : ""} (see log for per-profile results)`, - ]; + return [`dsh: ${refreshed}/${before} profile bundle(s) refreshed to ${latest} through dsh's plugin channel${failed > 0 ? ` (${failed} failed)` : ""} (see log for per-profile results)`]; } if (agent === "hermes") { - if (hermesStatus() !== "installed") - return ["hermes: not installed — nothing to update"]; + if (hermesStatus() !== "installed") return ["hermes: not installed — nothing to update"]; hermesInstallCore(); - return [ - `hermes: re-copied the plugin into ${hermesPluginDir()} (bili ${selfVersion()}) — restart hermes to pick it up`, - ]; + return [`hermes: re-copied the plugin into ${hermesPluginDir()} (bili ${selfVersion()}) — restart hermes to pick it up`]; } const via = UPDATE_CHANNEL[agent]; - return [ - `${agent}: the plugin entry follows the global bili install — it updates together with it (${via})`, - ]; + return [`${agent}: the plugin entry follows the global bili install — it updates together with it (${via})`]; } diff --git a/src/proxy-service/index.ts b/src/proxy-service/index.ts deleted file mode 100644 index a38fcc6eac..0000000000 --- a/src/proxy-service/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -export { - BILI_TASK_NAME, - planTaskDelete, - planTaskDisable, - planTaskEnable, - planTaskEnd, - planTaskQuery, - planTaskRegister, - planTaskRun, - type ProxyTaskOptions, - type TaskCommand, - type TaskRunner, - type TaskRunnerResult, -} from "./task-scheduler.js"; -export { - disableProxyService, - enableProxyService, - installProxyService, - proxyServiceStatus, - removeProxyService, - restartProxyService, - type ProxyServiceConfig, - type ProxyServiceRecord, - type ProxyServiceResult, -} from "./service.js"; From 2b18131f71311c42615bef6975bc95640af40207 Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 00:34:46 +0800 Subject: [PATCH 07/20] fix: proxy service strict-review defects - decode runner output per platform (GBK on Windows schtasks, UTF-8 for systemctl): the hard-wired GBK label garbled Linux error text - report the real active state on the systemd already-installed path instead of a hard-coded "ready" - collapse the double record read in installSystemd - drop the systemdResult wrapper that only forwarded to describeFailure --- src/proxy-service/service.ts | 98 ++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 48 deletions(-) diff --git a/src/proxy-service/service.ts b/src/proxy-service/service.ts index 647adbdfc8..ff3d1692b5 100644 --- a/src/proxy-service/service.ts +++ b/src/proxy-service/service.ts @@ -130,29 +130,33 @@ function recordBackend(record: ServiceRecord): ServiceBackend { return record.backend === "systemd" ? "systemd" : "schtasks"; } -function defaultRunner(command: TaskCommand): Promise { - return new Promise((resolve, reject) => { - import("node:child_process").then(({ spawn }) => { - const child = spawn(command.file, command.args, { - windowsHide: true, - stdio: ["ignore", "pipe", "pipe"], - }); - const stdout: Buffer[] = []; - const stderr: Buffer[] = []; - child.stdout?.on("data", (chunk: Buffer) => stdout.push(chunk)); - child.stderr?.on("data", (chunk: Buffer) => stderr.push(chunk)); - child.once("error", reject); - child.once("close", (code) => { - const decode = (chunks: Buffer[]): string => - new TextDecoder("gbk").decode(Buffer.concat(chunks)); - resolve({ - exitCode: code ?? 1, - stdout: decode(stdout), - stderr: decode(stderr), +/** schtasks on a Chinese Windows prints GBK; systemctl output is UTF-8. A + * single hard-wired label garbles one backend's error text on the other OS. */ +function spawnRunner(platform: NodeJS.Platform): TaskRunner { + const label = platform === "win32" ? "gbk" : "utf8"; + return (command: TaskCommand) => + new Promise((resolve, reject) => { + import("node:child_process").then(({ spawn }) => { + const child = spawn(command.file, command.args, { + windowsHide: true, + stdio: ["ignore", "pipe", "pipe"], + }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + child.stdout?.on("data", (chunk: Buffer) => stdout.push(chunk)); + child.stderr?.on("data", (chunk: Buffer) => stderr.push(chunk)); + child.once("error", reject); + child.once("close", (code) => { + const decode = (chunks: Buffer[]): string => + new TextDecoder(label).decode(Buffer.concat(chunks)); + resolve({ + exitCode: code ?? 1, + stdout: decode(stdout), + stderr: decode(stderr), + }); }); }); }); - }); } function serviceRecordPath(directory = stateDir()): string { @@ -210,6 +214,7 @@ function removeRecord(file: string): void { function resolveConfig(config: ProxyServiceConfig) { const taskName = config.taskName ?? BILI_TASK_NAME; + const platform = config.platform ?? process.platform; const entryPath = config.entryPath ?? process.argv[1] ?? @@ -220,8 +225,8 @@ function resolveConfig(config: ProxyServiceConfig) { entryPath, port: config.port ?? lanePreferredPort("codex"), host: config.host ?? "127.0.0.1", - platform: config.platform ?? process.platform, - runner: config.runner ?? defaultRunner, + platform, + runner: config.runner ?? spawnRunner(platform), stateDirectory: config.stateDirectory ?? stateDir(), unitPath: config.unitPath ?? defaultUnitPath(), }; @@ -725,13 +730,6 @@ export async function enableProxyService( type ResolvedConfig = ReturnType; -function systemdResult( - result: TaskRunnerResult, - action: string, -): ProxyServiceResult { - return describeFailure(action, result); -} - /** Bus reachability preflight shared by every mutating systemd path. Returns a * failure result when `systemctl --user` cannot talk to a user manager, else * undefined. Writing a unit into a machine whose user manager will never load @@ -832,22 +830,26 @@ async function installSystemd(c: ResolvedConfig): Promise { }; } const previous = readRecord(file); - const record = readRecord(file); if ( existing !== undefined && - record !== undefined && - recordBackend(record) === "systemd" && - record.entryPath === c.entryPath && - record.port === c.port && - record.host === c.host && - record.registrationVersion === REGISTRATION_VERSION + previous !== undefined && + recordBackend(previous) === "systemd" && + previous.entryPath === c.entryPath && + previous.port === c.port && + previous.host === c.host && + previous.registrationVersion === REGISTRATION_VERSION ) { + const active = await invoke( + c.runner, + planSystemdIsActive({ unitName: c.taskName }), + ); return { ok: true, action: "already-installed", - state: "ready", - message: - "systemd user unit is already registered with the current bili entry", + state: systemdUnitActive(active) ? "ready" : "disabled", + message: systemdUnitActive(active) + ? "systemd user unit is already registered with the current bili entry" + : "systemd user unit is registered but not running", }; } return writeAndEnableSystemd(c, file, previous); @@ -889,7 +891,7 @@ async function writeAndEnableSystemd( const reload = await invoke(c.runner, planDaemonReload()); if (reload.exitCode !== 0) { restoreUnit(c.unitPath, priorText); - return systemdResult(reload, "reload systemd user manager"); + return describeFailure("reload systemd user manager", reload); } const enable = await invoke( c.runner, @@ -898,7 +900,7 @@ async function writeAndEnableSystemd( if (enable.exitCode !== 0) { restoreUnit(c.unitPath, priorText); await invoke(c.runner, planDaemonReload()); - return systemdResult(enable, "enable systemd user unit"); + return describeFailure("enable systemd user unit", enable); } writeRecord(file, { taskName: c.taskName, @@ -981,13 +983,13 @@ async function removeSystemd(c: ResolvedConfig): Promise { planSystemdDisable({ unitName: c.taskName }), ); if (disable.exitCode !== 0 && !systemdUnitMissing(disable)) - return systemdResult(disable, "disable systemd user unit"); + return describeFailure("disable systemd user unit", disable); const stop = await invoke( c.runner, planSystemdStop({ unitName: c.taskName }), ); if (stop.exitCode !== 0 && !systemdUnitMissing(stop)) - return systemdResult(stop, "stop systemd user unit"); + return describeFailure("stop systemd user unit", stop); try { fs.unlinkSync(c.unitPath); } catch (error) { @@ -1026,7 +1028,7 @@ async function disableSystemd(c: ResolvedConfig): Promise { result.exitCode !== 0 && !/not enabled|already disabled/i.test(`${result.stdout}\n${result.stderr}`) ) - return systemdResult(result, "disable systemd user unit"); + return describeFailure("disable systemd user unit", result); const stop = await invoke( c.runner, planSystemdStop({ unitName: c.taskName }), @@ -1036,7 +1038,7 @@ async function disableSystemd(c: ResolvedConfig): Promise { !systemdUnitMissing(stop) && !/not running/i.test(`${stop.stdout}\n${stop.stderr}`) ) - return systemdResult(stop, "stop systemd user unit"); + return describeFailure("stop systemd user unit", stop); return { ok: true, action: "disabled", @@ -1059,7 +1061,7 @@ async function enableSystemd(c: ResolvedConfig): Promise { planSystemdEnableNow({ unitName: c.taskName }), ); if (result.exitCode !== 0) - return systemdResult(result, "enable systemd user unit"); + return describeFailure("enable systemd user unit", result); return { ok: true, action: "enabled", @@ -1086,13 +1088,13 @@ async function restartSystemd(c: ResolvedConfig): Promise { !/not running/i.test(`${stop.stdout}\n${stop.stderr}`) && !systemdUnitMissing(stop) ) - return systemdResult(stop, "stop systemd user unit"); + return describeFailure("stop systemd user unit", stop); const start = await invoke( c.runner, planSystemdStart({ unitName: c.taskName }), ); if (start.exitCode !== 0) - return systemdResult(start, "start systemd user unit"); + return describeFailure("start systemd user unit", start); return { ok: true, action: "restarted", From 8e392ded3144ae0ae43a8783382c38a606a9907e Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 00:35:17 +0800 Subject: [PATCH 08/20] refactor: remove dead code from codex/proxy-service modules - drop src/proxy-service/index.ts barrel: zero consumers import it - drop planTaskRegister flag-form planner (kept only for tests that asserted a shape production never uses; validation stays covered via renderTaskXml/renderTaskLauncherVbs) - drop unused CodexHookEntry/CodexHookStage types - toml-field: one parseTableHeader helper instead of three divergent inline header regexes; drop consumer-less replaceTable - route.ts: tabs to the repo 4-space style; status.ts: merge duplicate route.js imports --- src/codex-integration/hooks.ts | 10 - src/codex-integration/route.ts | 572 ++++++++++++++-------------- src/codex-integration/status.ts | 7 +- src/codex-integration/toml-field.ts | 61 ++- src/proxy-service/task-scheduler.ts | 27 -- 5 files changed, 317 insertions(+), 360 deletions(-) diff --git a/src/codex-integration/hooks.ts b/src/codex-integration/hooks.ts index f20aa61c79..a9b9d2ea60 100644 --- a/src/codex-integration/hooks.ts +++ b/src/codex-integration/hooks.ts @@ -20,16 +20,6 @@ export const CODEX_HOOKS_TABLE = "hooks.SessionStart"; const FEATURES_TABLE = "features"; const FEATURES_KEY = "hooks"; -/** Codex's stage names it groups hook tables under. Kept in the type so a - * future ticket can add stages without re-typing the entry shape. */ -export type CodexHookStage = "session_start"; - -export interface CodexHookEntry { - kind: CodexHookStage; - command: string; - timeoutSec?: number; -} - /** True for a hook command naming bili's own Codex hook script. Path may differ * across installs/upgrades (checkout vs. global npm), so match the script * name, not the absolute path — same rule as the Claude lane. */ diff --git a/src/codex-integration/route.ts b/src/codex-integration/route.ts index cb42c37325..d2524720cd 100644 --- a/src/codex-integration/route.ts +++ b/src/codex-integration/route.ts @@ -19,12 +19,12 @@ import { parseCodexToml } from "../client-config.js"; import type { CodexConfig } from "../client-config.js"; import { lanePreferredPort } from "../instance.js"; import { - findTableScalar, - findTopLevelScalar, - removeTableScalar, - removeTopLevelScalar, - setTableScalar, - setTopLevelScalar, + findTableScalar, + findTopLevelScalar, + removeTableScalar, + removeTopLevelScalar, + setTableScalar, + setTopLevelScalar, } from "./toml-field.js"; /** The top-level Codex field this module owns. */ @@ -39,24 +39,24 @@ export const CODEX_DEFAULT_UPSTREAM = "https://api.openai.com/v1"; * #1660) and both `127.0.0.1` and `localhost`, because a user may have copied * a documented value by hand. */ const BILI_ROUTE_RE = - /^(http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5})\/bili\/(https?:\/\/.+)$/; + /^(http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5})\/bili\/(https?:\/\/.+)$/; export function isBiliCodexRoute(value: string): boolean { - return BILI_ROUTE_RE.test(value.trim()); + return BILI_ROUTE_RE.test(value.trim()); } /** Inverse of `codexRouteValue`: recover the real upstream. undefined for * anything bili did not write. */ export function unwrapCodexRoute(value: string): string | undefined { - const m = BILI_ROUTE_RE.exec(value.trim()); - return m ? m[2] : undefined; + const m = BILI_ROUTE_RE.exec(value.trim()); + return m ? m[2] : undefined; } /** Build the routed value for a real upstream, preserving any `/bili/` * wrapper the caller already had (so re-planning is idempotent). */ export function codexRouteValue(origin: string, upstream: string): string { - const real = unwrapCodexRoute(upstream) ?? upstream; - return `${origin.replace(/\/+$/, "")}/bili/${real.replace(/\/+$/, "")}`; + const real = unwrapCodexRoute(upstream) ?? upstream; + return `${origin.replace(/\/+$/, "")}/bili/${real.replace(/\/+$/, "")}`; } /** The origin the persistent Codex route should point at. Uses the lane's @@ -65,7 +65,7 @@ export function codexRouteValue(origin: string, upstream: string): string { * ladder and machine reboots — the same stable-origin discipline as every * other lane (#1660). No new config/env surface is introduced for this. */ export function codexRouteOrigin(env: NodeJS.ProcessEnv = process.env): string { - return `http://127.0.0.1:${lanePreferredPort("codex", env)}`; + return `http://127.0.0.1:${lanePreferredPort("codex", env)}`; } /** The upstream Codex would reach WITHOUT bili in the path — the provider the @@ -73,340 +73,340 @@ export function codexRouteOrigin(env: NodeJS.ProcessEnv = process.env): string { * (`model_provider`'s `base_url` > top-level `openai_base_url` > OpenAI * default) but unwraps bili's own value so re-planning never double-wraps. */ export function codexRealUpstream(config: CodexConfig | undefined): string { - const provider = - config?.modelProvider !== undefined - ? config?.providers?.[config.modelProvider]?.baseUrl - : undefined; - if (provider !== undefined && provider !== "") - return unwrapCodexRoute(provider) ?? provider; - const direct = config?.openaiBaseUrl; - if (direct !== undefined && direct !== "") - return unwrapCodexRoute(direct) ?? direct; - return CODEX_DEFAULT_UPSTREAM; + const provider = + config?.modelProvider !== undefined + ? config?.providers?.[config.modelProvider]?.baseUrl + : undefined; + if (provider !== undefined && provider !== "") + return unwrapCodexRoute(provider) ?? provider; + const direct = config?.openaiBaseUrl; + if (direct !== undefined && direct !== "") + return unwrapCodexRoute(direct) ?? direct; + return CODEX_DEFAULT_UPSTREAM; } /** Why the route cannot be (or is not) the effective one. Both are reported, * never silently "fixed": the spec forbids fighting a provider manager. */ export type CodexRouteConflict = - /** A foreign (non-bili) `openai_base_url` is already set. */ - | { kind: "foreign-openai-base-url"; value: string } - /** `model_provider` names a provider with its own `base_url`, so Codex - * ignores the top-level field entirely — writing it would be a no-op. */ - | { kind: "shadowed-by-provider"; provider: string; value: string }; + /** A foreign (non-bili) `openai_base_url` is already set. */ + | { kind: "foreign-openai-base-url"; value: string } + /** `model_provider` names a provider with its own `base_url`, so Codex + * ignores the top-level field entirely — writing it would be a no-op. */ + | { kind: "shadowed-by-provider"; provider: string; value: string }; export interface CodexRoutePlan { - action: "install" | "refresh" | "keep" | "conflict"; - /** The full file text after the action (`keep`/`conflict` return it unchanged). */ - text: string; - /** The routed value bili owns or would own. */ - value?: string; - target?: CodexRouteTarget; - conflict?: CodexRouteConflict; - note: string; + action: "install" | "refresh" | "keep" | "conflict"; + /** The full file text after the action (`keep`/`conflict` return it unchanged). */ + text: string; + /** The routed value bili owns or would own. */ + value?: string; + target?: CodexRouteTarget; + conflict?: CodexRouteConflict; + note: string; } export type CodexRouteTarget = - | { kind: "top-level" } - | { kind: "provider"; provider: string }; + | { kind: "top-level" } + | { kind: "provider"; provider: string }; export interface CodexRouteRecord { - schemaVersion: 1; - writtenValue: string; - previousValue: string | null; - upstream: string; - target?: CodexRouteTarget; + schemaVersion: 1; + writtenValue: string; + previousValue: string | null; + upstream: string; + target?: CodexRouteTarget; } export function codexRouteRecordPath(configFile: string): string { - return `${configFile}.bili-route.json`; + return `${configFile}.bili-route.json`; } export function readCodexRouteRecord( - file: string, + file: string, ): CodexRouteRecord | undefined { - try { - const value: unknown = JSON.parse(fs.readFileSync(file, "utf8")); - if (value === null || typeof value !== "object" || Array.isArray(value)) - return undefined; - const row = value as Record; - if ( - row.schemaVersion !== 1 || - typeof row.writtenValue !== "string" || - !(typeof row.previousValue === "string" || row.previousValue === null) || - typeof row.upstream !== "string" - ) - return undefined; - const target = row.target === undefined - ? { kind: "top-level" as const } - : row.target; - if ( - target === null || - typeof target !== "object" || - !("kind" in target) || - (target.kind !== "top-level" && - (target.kind !== "provider" || !("provider" in target) || typeof target.provider !== "string")) - ) return undefined; - return { - schemaVersion: 1, - writtenValue: row.writtenValue, - previousValue: row.previousValue, - upstream: row.upstream, - target: target as CodexRouteTarget, - }; - } catch { - return undefined; - } + try { + const value: unknown = JSON.parse(fs.readFileSync(file, "utf8")); + if (value === null || typeof value !== "object" || Array.isArray(value)) + return undefined; + const row = value as Record; + if ( + row.schemaVersion !== 1 || + typeof row.writtenValue !== "string" || + !(typeof row.previousValue === "string" || row.previousValue === null) || + typeof row.upstream !== "string" + ) + return undefined; + const target = row.target === undefined + ? { kind: "top-level" as const } + : row.target; + if ( + target === null || + typeof target !== "object" || + !("kind" in target) || + (target.kind !== "top-level" && + (target.kind !== "provider" || !("provider" in target) || typeof target.provider !== "string")) + ) return undefined; + return { + schemaVersion: 1, + writtenValue: row.writtenValue, + previousValue: row.previousValue, + upstream: row.upstream, + target: target as CodexRouteTarget, + }; + } catch { + return undefined; + } } export function writeCodexRouteRecord( - file: string, - record: CodexRouteRecord, + file: string, + record: CodexRouteRecord, ): void { - fs.mkdirSync(path.dirname(file), { recursive: true }); - const temporary = `${file}.${process.pid}.tmp`; - fs.writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { - mode: 0o600, - }); - fs.renameSync(temporary, file); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const temporary = `${file}.${process.pid}.tmp`; + fs.writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { + mode: 0o600, + }); + fs.renameSync(temporary, file); } export function removeCodexRouteRecord(file: string): void { - try { - fs.unlinkSync(file); - } catch (error) { - if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) - throw error; - } + try { + fs.unlinkSync(file); + } catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) + throw error; + } } /** Pure planner: decide what (if anything) to do to `text`. Provider-table * routes are allowed only for an explicitly detected CC Switch Direct mode; * Routing/Aggregation/unknown remain untouched. */ export function planCodexRoute( - text: string, - opts: { - origin: string; - config?: CodexConfig; - ownedValue?: string; - ownedRecord?: CodexRouteRecord; - ccSwitchMode?: "direct" | "routing" | "aggregation" | "unknown"; - }, + text: string, + opts: { + origin: string; + config?: CodexConfig; + ownedValue?: string; + ownedRecord?: CodexRouteRecord; + ccSwitchMode?: "direct" | "routing" | "aggregation" | "unknown"; + }, ): CodexRoutePlan { - const config = opts.config ?? parseCodexToml(text); - const provider = config.modelProvider; - const providerBase = provider ? config.providers?.[provider]?.baseUrl : undefined; - const record = opts.ownedRecord; - const recordedTarget = record?.target ?? { kind: "top-level" as const }; - const activeTarget: CodexRouteTarget = - provider && providerBase ? { kind: "provider", provider } : { kind: "top-level" }; - if ( - record && - (recordedTarget.kind !== activeTarget.kind || - (recordedTarget.kind === "provider" && - activeTarget.kind === "provider" && - recordedTarget.provider !== activeTarget.provider)) - ) { - return { - action: "conflict", - text, - conflict: provider && providerBase - ? { kind: "shadowed-by-provider", provider, value: providerBase } - : { kind: "foreign-openai-base-url", value: "active Codex target changed" }, - note: `Codex's effective route target changed since bili installed it; run bili plugin remove codex before installing the new provider route`, - }; - } - const ownProvider = - recordedTarget.kind === "provider" && - recordedTarget.provider === provider && - record?.writtenValue === providerBase; + const config = opts.config ?? parseCodexToml(text); + const provider = config.modelProvider; + const providerBase = provider ? config.providers?.[provider]?.baseUrl : undefined; + const record = opts.ownedRecord; + const recordedTarget = record?.target ?? { kind: "top-level" as const }; + const activeTarget: CodexRouteTarget = + provider && providerBase ? { kind: "provider", provider } : { kind: "top-level" }; + if ( + record && + (recordedTarget.kind !== activeTarget.kind || + (recordedTarget.kind === "provider" && + activeTarget.kind === "provider" && + recordedTarget.provider !== activeTarget.provider)) + ) { + return { + action: "conflict", + text, + conflict: provider && providerBase + ? { kind: "shadowed-by-provider", provider, value: providerBase } + : { kind: "foreign-openai-base-url", value: "active Codex target changed" }, + note: `Codex's effective route target changed since bili installed it; run bili plugin remove codex before installing the new provider route`, + }; + } + const ownProvider = + recordedTarget.kind === "provider" && + recordedTarget.provider === provider && + record?.writtenValue === providerBase; - if (provider && providerBase) { - const target: CodexRouteTarget = { kind: "provider", provider }; - if ( - record && recordedTarget.kind === "provider" && - recordedTarget.provider === provider && providerBase !== record.writtenValue - ) { - return { - action: "conflict", - text, - conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, - note: `provider ${provider} base_url changed after bili installed it; likely a CC Switch rewrite, so it was left untouched`, - }; - } - if (ownProvider && opts.ccSwitchMode !== "direct") { - return { - action: "conflict", - text, - conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, - note: `CC Switch is no longer confirmed in Direct mode; existing bili route was left untouched`, - }; - } - if (ownProvider) { - const value = codexRouteValue(opts.origin, record!.upstream); - if (providerBase === value) - return { action: "keep", text, value, target, note: `CC Switch Direct provider ${provider} already routes through bili` }; - return { - action: "refresh", - text: setTableScalar(text, `model_providers.${provider}`, "base_url", value), - value, - target, - note: `CC Switch Direct provider ${provider} route refreshed -> ${value}`, - }; - } - if (isBiliCodexRoute(providerBase)) { - return { - action: "conflict", - text, - conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, - note: `provider ${provider} already has a bili-shaped base_url without matching ownership evidence — left untouched`, - }; - } - if (opts.ccSwitchMode !== "direct") { - return { - action: "conflict", - text, - conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, - note: `model_provider = "${provider}" declares base_url ${providerBase}; only detected CC Switch Direct mode may route this provider`, - }; - } - const value = codexRouteValue(opts.origin, providerBase); - return { - action: "install", - text: setTableScalar(text, `model_providers.${provider}`, "base_url", value), - value, - target, - note: `CC Switch Direct provider ${provider} routed through bili -> ${value}; CC Switch may rewrite it when provider or mode changes`, - }; - } + if (provider && providerBase) { + const target: CodexRouteTarget = { kind: "provider", provider }; + if ( + record && recordedTarget.kind === "provider" && + recordedTarget.provider === provider && providerBase !== record.writtenValue + ) { + return { + action: "conflict", + text, + conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, + note: `provider ${provider} base_url changed after bili installed it; likely a CC Switch rewrite, so it was left untouched`, + }; + } + if (ownProvider && opts.ccSwitchMode !== "direct") { + return { + action: "conflict", + text, + conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, + note: `CC Switch is no longer confirmed in Direct mode; existing bili route was left untouched`, + }; + } + if (ownProvider) { + const value = codexRouteValue(opts.origin, record!.upstream); + if (providerBase === value) + return { action: "keep", text, value, target, note: `CC Switch Direct provider ${provider} already routes through bili` }; + return { + action: "refresh", + text: setTableScalar(text, `model_providers.${provider}`, "base_url", value), + value, + target, + note: `CC Switch Direct provider ${provider} route refreshed -> ${value}`, + }; + } + if (isBiliCodexRoute(providerBase)) { + return { + action: "conflict", + text, + conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, + note: `provider ${provider} already has a bili-shaped base_url without matching ownership evidence — left untouched`, + }; + } + if (opts.ccSwitchMode !== "direct") { + return { + action: "conflict", + text, + conflict: { kind: "shadowed-by-provider", provider, value: providerBase }, + note: `model_provider = "${provider}" declares base_url ${providerBase}; only detected CC Switch Direct mode may route this provider`, + }; + } + const value = codexRouteValue(opts.origin, providerBase); + return { + action: "install", + text: setTableScalar(text, `model_providers.${provider}`, "base_url", value), + value, + target, + note: `CC Switch Direct provider ${provider} routed through bili -> ${value}; CC Switch may rewrite it when provider or mode changes`, + }; + } - const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); - const ownTopLevel = - recordedTarget.kind === "top-level" && - ((record?.writtenValue !== undefined && existing?.value === record.writtenValue) || - (opts.ownedValue !== undefined && existing?.value === opts.ownedValue)); - if (existing && !ownTopLevel) { - return { - action: "conflict", - text, - conflict: { kind: "foreign-openai-base-url", value: existing.value }, - note: `${CODEX_ROUTE_KEY} is already set to a non-bili value — left untouched`, - }; - } - const value = codexRouteValue(opts.origin, codexRealUpstream(config)); - if (existing?.value === value) - return { action: "keep", text, value, target: { kind: "top-level" }, note: `${CODEX_ROUTE_KEY} already routed through bili` }; - return { - action: ownTopLevel ? "refresh" : "install", - text: setTopLevelScalar(text, CODEX_ROUTE_KEY, value), - value, - target: { kind: "top-level" }, - note: ownTopLevel - ? `${CODEX_ROUTE_KEY} refreshed -> ${value}` - : `${CODEX_ROUTE_KEY} routed through bili -> ${value}`, - }; + const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); + const ownTopLevel = + recordedTarget.kind === "top-level" && + ((record?.writtenValue !== undefined && existing?.value === record.writtenValue) || + (opts.ownedValue !== undefined && existing?.value === opts.ownedValue)); + if (existing && !ownTopLevel) { + return { + action: "conflict", + text, + conflict: { kind: "foreign-openai-base-url", value: existing.value }, + note: `${CODEX_ROUTE_KEY} is already set to a non-bili value — left untouched`, + }; + } + const value = codexRouteValue(opts.origin, codexRealUpstream(config)); + if (existing?.value === value) + return { action: "keep", text, value, target: { kind: "top-level" }, note: `${CODEX_ROUTE_KEY} already routed through bili` }; + return { + action: ownTopLevel ? "refresh" : "install", + text: setTopLevelScalar(text, CODEX_ROUTE_KEY, value), + value, + target: { kind: "top-level" }, + note: ownTopLevel + ? `${CODEX_ROUTE_KEY} refreshed -> ${value}` + : `${CODEX_ROUTE_KEY} routed through bili -> ${value}`, + }; } /** What bili currently finds in `text` — the read side of ownership, shared by * status reporting and uninstall. */ export interface CodexRouteState { - /** A bili-owned route is present. */ - routed: boolean; - /** The raw field value, when any. */ - value?: string; - /** The real upstream behind a bili-owned route. */ - upstream?: string; - conflict?: CodexRouteConflict; + /** A bili-owned route is present. */ + routed: boolean; + /** The raw field value, when any. */ + value?: string; + /** The real upstream behind a bili-owned route. */ + upstream?: string; + conflict?: CodexRouteConflict; } export function readCodexRoute( - text: string, - ownership?: CodexRouteRecord | string, + text: string, + ownership?: CodexRouteRecord | string, ): CodexRouteState { - const config = parseCodexToml(text); - const record = typeof ownership === "string" ? undefined : ownership; - const ownedValue = typeof ownership === "string" ? ownership : record?.writtenValue; - const target = record?.target ?? { kind: "top-level" as const }; - const provider = config.modelProvider; - const providerBase = provider ? config.providers?.[provider]?.baseUrl : undefined; - const out: CodexRouteState = { routed: false }; - if (target.kind === "provider") { - if (provider === target.provider && providerBase !== undefined) { - out.value = providerBase; - if (providerBase === ownedValue && isBiliCodexRoute(providerBase)) { - out.routed = true; - out.upstream = record?.upstream ?? unwrapCodexRoute(providerBase); - } else { - out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; - } - return out; - } - if (target.provider !== provider && provider && providerBase) - out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; - return out; - } - const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); - if (existing !== undefined) { - out.value = existing.value; - if (ownedValue !== undefined && existing.value === ownedValue && isBiliCodexRoute(existing.value)) { - out.routed = true; - out.upstream = record?.upstream ?? unwrapCodexRoute(existing.value); - } else { - out.conflict = { kind: "foreign-openai-base-url", value: existing.value }; - } - } - if (provider && providerBase) - out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; - return out; + const config = parseCodexToml(text); + const record = typeof ownership === "string" ? undefined : ownership; + const ownedValue = typeof ownership === "string" ? ownership : record?.writtenValue; + const target = record?.target ?? { kind: "top-level" as const }; + const provider = config.modelProvider; + const providerBase = provider ? config.providers?.[provider]?.baseUrl : undefined; + const out: CodexRouteState = { routed: false }; + if (target.kind === "provider") { + if (provider === target.provider && providerBase !== undefined) { + out.value = providerBase; + if (providerBase === ownedValue && isBiliCodexRoute(providerBase)) { + out.routed = true; + out.upstream = record?.upstream ?? unwrapCodexRoute(providerBase); + } else { + out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; + } + return out; + } + if (target.provider !== provider && provider && providerBase) + out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; + return out; + } + const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); + if (existing !== undefined) { + out.value = existing.value; + if (ownedValue !== undefined && existing.value === ownedValue && isBiliCodexRoute(existing.value)) { + out.routed = true; + out.upstream = record?.upstream ?? unwrapCodexRoute(existing.value); + } else { + out.conflict = { kind: "foreign-openai-base-url", value: existing.value }; + } + } + if (provider && providerBase) + out.conflict = { kind: "shadowed-by-provider", provider, value: providerBase }; + return out; } /** The route value bili would write right now for `file` — used by status * reporting to tell "configured for THIS origin" from "configured for a * drifted one". */ export function desiredCodexRoute(text: string, origin: string): string { - return codexRouteValue(origin, codexRealUpstream(parseCodexToml(text))); + return codexRouteValue(origin, codexRealUpstream(parseCodexToml(text))); } export function codexRouteFilePath(codexHome: string): string { - return path.join(codexHome, "config.toml"); + return path.join(codexHome, "config.toml"); } export function readCodexRouteFile(file: string): string { - try { - return fs.readFileSync(file, "utf8"); - } catch { - return ""; - } + try { + return fs.readFileSync(file, "utf8"); + } catch { + return ""; + } } /** Remove bili's route field, leaving every other byte alone. Returns the new * text plus whether anything changed. */ export function restoreCodexRoute( - text: string, - record?: CodexRouteRecord, + text: string, + record?: CodexRouteRecord, ): { - text: string; - restored: boolean; - stillOwned: boolean; + text: string; + restored: boolean; + stillOwned: boolean; } { - if (record === undefined) return { text, restored: false, stillOwned: false }; - const target = record.target ?? { kind: "top-level" as const }; - if (target.kind === "provider") { - const table = `model_providers.${target.provider}`; - const existing = findTableScalar(text, table, "base_url"); - if (existing === undefined || existing.value !== record.writtenValue) - return { text, restored: false, stillOwned: false }; - const next = - record.previousValue === null - ? removeTableScalar(text, table, "base_url") - : setTableScalar(text, table, "base_url", record.previousValue); - return { text: next, restored: true, stillOwned: true }; - } - const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); - if (existing === undefined || existing.value !== record.writtenValue) - return { text, restored: false, stillOwned: false }; - const next = - record.previousValue === null - ? removeTopLevelScalar(text, CODEX_ROUTE_KEY) - : setTopLevelScalar(text, CODEX_ROUTE_KEY, record.previousValue); - return { text: next, restored: true, stillOwned: true }; + if (record === undefined) return { text, restored: false, stillOwned: false }; + const target = record.target ?? { kind: "top-level" as const }; + if (target.kind === "provider") { + const table = `model_providers.${target.provider}`; + const existing = findTableScalar(text, table, "base_url"); + if (existing === undefined || existing.value !== record.writtenValue) + return { text, restored: false, stillOwned: false }; + const next = + record.previousValue === null + ? removeTableScalar(text, table, "base_url") + : setTableScalar(text, table, "base_url", record.previousValue); + return { text: next, restored: true, stillOwned: true }; + } + const existing = findTopLevelScalar(text, CODEX_ROUTE_KEY); + if (existing === undefined || existing.value !== record.writtenValue) + return { text, restored: false, stillOwned: false }; + const next = + record.previousValue === null + ? removeTopLevelScalar(text, CODEX_ROUTE_KEY) + : setTopLevelScalar(text, CODEX_ROUTE_KEY, record.previousValue); + return { text: next, restored: true, stillOwned: true }; } diff --git a/src/codex-integration/status.ts b/src/codex-integration/status.ts index c7c47897d3..a132665af9 100644 --- a/src/codex-integration/status.ts +++ b/src/codex-integration/status.ts @@ -1,7 +1,10 @@ import { resolveCodexHome } from "../client-config.js"; import { lanePreferredPort } from "../instance.js"; -import { readCodexRoute, readCodexRouteRecord } from "./route.js"; -import { codexRouteRecordPath } from "./route.js"; +import { + codexRouteRecordPath, + readCodexRoute, + readCodexRouteRecord, +} from "./route.js"; import fs from "node:fs"; import path from "node:path"; diff --git a/src/codex-integration/toml-field.ts b/src/codex-integration/toml-field.ts index 465df9fd10..f7ec7ddf80 100644 --- a/src/codex-integration/toml-field.ts +++ b/src/codex-integration/toml-field.ts @@ -19,6 +19,23 @@ export interface TopLevelScalar { const SCALAR_RE = /^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')\s*(?:#.*)?$/; +/** Any TOML table header, including `[[array-of-tables]]`. In TOML every new + * header ENDS the previous table's scope — an array-of-tables header included. + * Treating only single-bracket headers as boundaries lets an inserted or read + * scalar bleed into a following `[[...]]` element, where Codex's serde drops + * unknown keys silently (the exact failure class this module exists to avoid). */ +function parseTableHeader( + line: string, +): { kind: "table" | "array"; name: string } | undefined { + const m = /^\s*(\[\[?)([^\]]+)(\]\]?)\s*(?:#.*)?$/.exec(line); + if (m === null) return undefined; + const opening = m[1]!; + const closing = m[3]!; + if (opening === "[[" && closing !== "]]") return undefined; + if (opening === "[" && closing !== "]") return undefined; + return { kind: opening === "[[" ? "array" : "table", name: m[2]!.trim() }; +} + function decode(raw: string, quoted: "basic" | "literal"): string { if (quoted === "literal") return raw; try { @@ -125,10 +142,10 @@ export function findTableScalar( let active = false; for (let i = 0; i < lines.length; i++) { const line = lines[i]!.trim(); - const header = /^\[([^\]]+)\]\s*(?:#.*)?$/.exec(line); - if (header) { + const header = parseTableHeader(line); + if (header !== undefined) { if (active) return undefined; - active = header[1]!.trim() === table; + active = header.kind === "table" && header.name === table; continue; } if (!active || line === "" || line.startsWith("#")) continue; @@ -166,13 +183,13 @@ export function setTableScalar( let tableLine = -1; let tableEnd = lines.length; for (let i = 0; i < lines.length; i++) { - const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); - if (!header) continue; + const header = parseTableHeader(lines[i]!); + if (header === undefined) continue; if (tableLine >= 0) { tableEnd = i; break; } - if (header[1]!.trim() === table) tableLine = i; + if (header.kind === "table" && header.name === table) tableLine = i; } if (tableLine < 0) { const prefix = @@ -209,13 +226,13 @@ export function insertTableRaw( let tableLine = -1; let tableEnd = lines.length; for (let i = 0; i < lines.length; i++) { - const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); - if (!header) continue; + const header = parseTableHeader(lines[i]!); + if (header === undefined) continue; if (tableLine >= 0) { tableEnd = i; break; } - if (header[1]!.trim() === table) tableLine = i; + if (header.kind === "table" && header.name === table) tableLine = i; } if (tableLine < 0) { const prefix = @@ -234,32 +251,6 @@ export function insertTableRaw( return lines.join("\n"); } -/** Replace an entire table header line and its scalars with `rendered` (which - * must itself include the `[table]` header). Used for hook tables bili owns - * end-to-end; a table with foreign structure is reported, never clobbered. */ -export function replaceTable( - text: string, - table: string, - rendered: string, -): string { - const lines = text.split("\n"); - let start = -1; - let end = lines.length; - for (let i = 0; i < lines.length; i++) { - const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(lines[i]!); - if (!header) continue; - if (start >= 0) { - end = i; - break; - } - if (header[1]!.trim() === table) start = i; - } - if (start < 0) return text; - const block = rendered.replace(/\n+$/, "").split("\n"); - lines.splice(start, end - start, ...block); - return lines.join("\n"); -} - /** Every region of `text` covered by an exact `[table]` or `[[table]]` header * (until the next header at any level). Lets a caller assert "this table is * ours" before a rewrite, instead of assuming the shape it expects. diff --git a/src/proxy-service/task-scheduler.ts b/src/proxy-service/task-scheduler.ts index 2d07b944d4..dbd086ba1c 100644 --- a/src/proxy-service/task-scheduler.ts +++ b/src/proxy-service/task-scheduler.ts @@ -58,33 +58,6 @@ function checkedOptions(options: ProxyTaskOptions): Required { }; } -/** Build a per-user, at-logon Task Scheduler registration. Paths remain - * separate argv values for the runner; only schtasks' /TR payload is composed - * into a Windows command line, with each executable/path quoted. - * - * Prefer planTaskRegisterXml: this flag form cannot express , and an - * unhidden at-logon task runs the proxy WITH a console window in the user's - * session (#silent-backend). Kept for runners/tests that assert the old shape. */ -export function planTaskRegister(options: ProxyTaskOptions): TaskCommand { - const o = checkedOptions(options); - const run = `"${o.nodePath}" "${o.entryPath}" start --host "${o.host}" --port ${o.port} --no-auto-update`; - return { - file: "schtasks.exe", - args: [ - "/Create", - "/TN", - o.taskName, - "/SC", - "ONLOGON", - "/RL", - "LIMITED", - "/TR", - run, - "/F", - ], - }; -} - function xmlEscape(value: string): string { return value .replace(/&/g, "&") From 58ea96764d25e00f9ec706e0e0eb03b723fbb42e Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 00:35:17 +0800 Subject: [PATCH 09/20] test: re-target proxy-service tests off removed flag-form planner Import from service.ts directly (barrel deleted) and assert launcher command composition through renderTaskLauncherVbs, which exercises the same checkedOptions validation the removed planner used. --- tests/proxy-service.test.ts | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/tests/proxy-service.test.ts b/tests/proxy-service.test.ts index 97c3061428..cb3869c526 100644 --- a/tests/proxy-service.test.ts +++ b/tests/proxy-service.test.ts @@ -10,12 +10,13 @@ import { planTaskEnable, planTaskEnd, planTaskQuery, - planTaskRegister, planTaskRegisterXml, planTaskRun, renderTaskLauncherVbs, renderTaskXml, + type TaskCommand, type TaskRunner, + type TaskRunnerResult, } from "../src/proxy-service/task-scheduler.ts"; import { disableProxyService, @@ -24,9 +25,7 @@ import { proxyServiceStatus, removeProxyService, restartProxyService, - type TaskCommand, - type TaskRunnerResult, -} from "../src/proxy-service/index.ts"; +} from "../src/proxy-service/service.ts"; import { planDaemonReload, planSystemdEnableNow, @@ -45,25 +44,21 @@ const taskRow = 'true'; test("Task Scheduler command plans are per-user logon and safely quoted", () => { - const planned = planTaskRegister({ + const vbs = renderTaskLauncherVbs({ + taskName: BILI_TASK_NAME, nodePath: "C:\\Program Files\\nodejs\\node.exe", entryPath: "C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js", port: 18787, host: "127.0.0.1", }); - assert.equal(planned.file, "schtasks.exe"); - assert.deepEqual(planned.args.slice(0, 2), ["/Create", "/TN"]); - assert.ok(planned.args.includes("ONLOGON")); - assert.ok(planned.args.includes("LIMITED")); - const taskRun = planned.args[planned.args.indexOf("/TR") + 1]!; - assert.ok(taskRun.includes('"C:\\Program Files\\nodejs\\node.exe"')); + assert.ok(vbs.includes('"C:\\Program Files\\nodejs\\node.exe"')); assert.ok( - taskRun.includes( + vbs.includes( '"C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js"', ), ); - assert.ok(taskRun.includes("--port 18787")); + assert.ok(vbs.includes("--port 18787")); assert.equal( planTaskQuery().args.join(" "), `/Query /TN ${BILI_TASK_NAME} /XML`, @@ -75,19 +70,23 @@ test("Task Scheduler command plans are per-user logon and safely quoted", () => assert.ok(planTaskDelete().args.includes("/F")); assert.throws( () => - planTaskRegister({ + renderTaskLauncherVbs({ + taskName: BILI_TASK_NAME, nodePath: "node.exe", entryPath: "C:\\bili.js", port: 8787, + host: "127.0.0.1", }), /absolute/, ); assert.throws( () => - planTaskRegister({ + renderTaskLauncherVbs({ + taskName: BILI_TASK_NAME, nodePath: "C:\\node.exe", entryPath: "C:\\bili.js", port: 65536, + host: "127.0.0.1", }), /port/, ); From 22155923f7fd982b96cf3f1efb97a4776f8aaf42 Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 00:43:22 +0800 Subject: [PATCH 10/20] docs: document bili service command and new codex install semantics CLI Reference gains the `bili service ` row (en+zh) and the `bili plugin install codex` example now names the four managed faces plus the auto-start service instead of only the MCP block (#3176). --- CONFIGURATION.md | 3 ++- CONFIGURATION.zh-CN.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index cf2f3435df..ff7a4f106c 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -1860,6 +1860,7 @@ Full command surface (`bili --help` prints an abridged version). Precedence ever | `bili plugin install ` | Install the native-tool plugin / MCP bridge into a host — see [Plugin Mode](#plugin-mode-native-tools) | | `bili plugin remove ` | Remove it again | | `bili plugin list` | Show install status for every host | +| `bili service install\|status\|restart\|enable\|disable\|remove` | Manage the persistent per-user proxy service (Task Scheduler logon task on Windows, systemd user unit on Linux) that zero-touch lanes like codex rely on; JSON output, exit code 1 when the desired state is not reached (#3176) | | `bili mcp` | Run the bili MCP server standalone on stdio | | `bili plugin-register [--origin URL] [--agent name]` | Pre-bind a conversation id to plugin mode (advanced) | | `bili --version` / `bili --help` | Print version / help | @@ -2086,7 +2087,7 @@ bili plugin install pi # add this billion-context install to pi's settings. bili plugin install omp # same for omp (config.yml extensions) bili plugin install claude # register the bili MCP server (claude mcp add, user scope) + write # /commands/acp-cache.md (model-mediated /acp-cache) -bili plugin install codex # append [mcp_servers.bili] to ~/.codex/config.toml +bili plugin install codex # manage codex's MCP+ACP tools / model route / SessionStart hook / ACP skill in ~/.codex/config.toml (+ auto-start proxy service) — see CLIENTS.md (Codex) bili plugin install opencode # self-spawning native plugin (+ tools) in ~/.config/opencode/opencode.json # --with-mcp also adds the mcp.bili MCP face (no origin pin — live discovery) bili plugin list # install status for every supported host diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index e7dbcf71ce..2f4ecf6860 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -1833,6 +1833,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `bili update` | 立即检查并安装新版本(绕过 3 分钟节流) | | `bili plugin install ` | 把原生工具插件 / MCP 桥装进宿主 —— 见[插件模式(原生工具)](#插件模式原生工具) | | `bili plugin remove ` | 卸载 | +| `bili service install\|status\|restart\|enable\|disable\|remove` | 管理常驻的当前用户代理服务(Windows:Task Scheduler 登录任务;Linux:systemd 用户单元),供 codex 等零接触通道使用;JSON 输出,未达预期状态时退出码为 1(#3176) | | `bili plugin list` | 显示每个宿主的安装状态 | | `bili mcp` | 独立运行 bili MCP 服务器(stdio) | | `bili plugin-register [--origin URL] [--agent name]` | 预绑定会话 id 到插件模式(高级用法) | @@ -2060,7 +2061,7 @@ bili plugin install pi # 把本 billion-context 安装加入 pi 的 setting bili plugin install omp # omp 同理(config.yml extensions) bili plugin install claude # 注册 bili MCP 服务器(claude mcp add,user 作用域)+ 写入 # /commands/acp-cache.md(模型中介的 /acp-cache) -bili plugin install codex # 向 ~/.codex/config.toml 追加 [mcp_servers.bili] +bili plugin install codex # 托管 ~/.codex/config.toml 的 MCP+ACP 工具 / 模型路由 / SessionStart hook / ACP skill(并注册自启动代理服务)—— 见 CLIENTS.zh-CN.md(Codex) bili plugin install opencode # 向 ~/.config/opencode/opencode.json 加 mcp.bili bili plugin list # 所有受支持宿主的安装状态 bili plugin remove pi # 撤销(原文件一次性备份为 *.bili-bak) From 1af27f14c62c8cdfec810be4a6d119e59bcb7074 Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 00:58:37 +0800 Subject: [PATCH 11/20] fix: remove dead exports flagged by the unused-exports gate Delete three functions with zero consumers (route codexRouteFilePath / readCodexRouteFile, systemd planSystemdEnable) and strip the export modifier from module-internal types/helpers across the new codex integration and proxy-service modules. Behavior unchanged. --- src/codex-integration/cc-switch.ts | 2 +- src/codex-integration/hooks.ts | 4 ++-- src/codex-integration/route.ts | 30 +++++++++-------------------- src/codex-integration/skill.ts | 8 ++++---- src/codex-integration/status.ts | 4 ++-- src/codex-integration/toml-field.ts | 4 ++-- src/proxy-service/service.ts | 6 +++--- src/proxy-service/systemd.ts | 14 ++++---------- src/proxy-service/task-scheduler.ts | 2 +- 9 files changed, 28 insertions(+), 46 deletions(-) diff --git a/src/codex-integration/cc-switch.ts b/src/codex-integration/cc-switch.ts index 10fc82b7d9..be22c2ea74 100644 --- a/src/codex-integration/cc-switch.ts +++ b/src/codex-integration/cc-switch.ts @@ -2,7 +2,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -export type CcSwitchMode = "direct" | "routing" | "aggregation" | "unknown"; +type CcSwitchMode = "direct" | "routing" | "aggregation" | "unknown"; export interface CcSwitchDetection { discovered: boolean; diff --git a/src/codex-integration/hooks.ts b/src/codex-integration/hooks.ts index a9b9d2ea60..9ae5942158 100644 --- a/src/codex-integration/hooks.ts +++ b/src/codex-integration/hooks.ts @@ -14,7 +14,7 @@ import { tableRegions } from "./toml-field.js"; /** The TOML table Codex reads hook entries from. */ -export const CODEX_HOOKS_TABLE = "hooks.SessionStart"; +const CODEX_HOOKS_TABLE = "hooks.SessionStart"; /** `[features] hooks = true` — the master switch for the hook system. */ const FEATURES_TABLE = "features"; @@ -90,7 +90,7 @@ export function codexHooksFeature( return undefined; } -export type CodexHookPlan = +type CodexHookPlan = | { action: "install" | "refresh"; text: string; note: string } | { action: "keep"; text: string; note: string }; diff --git a/src/codex-integration/route.ts b/src/codex-integration/route.ts index d2524720cd..09e7079b3b 100644 --- a/src/codex-integration/route.ts +++ b/src/codex-integration/route.ts @@ -28,11 +28,11 @@ import { } from "./toml-field.js"; /** The top-level Codex field this module owns. */ -export const CODEX_ROUTE_KEY = "openai_base_url"; +const CODEX_ROUTE_KEY = "openai_base_url"; /** Codex's built-in OpenAI default (codex-rs model-provider-info), used when * the user has declared no provider and no base URL. */ -export const CODEX_DEFAULT_UPSTREAM = "https://api.openai.com/v1"; +const CODEX_DEFAULT_UPSTREAM = "https://api.openai.com/v1"; /** `/bili/` — the shape bili itself writes. Accepts * any loopback port (the lane's zone port drifts with the EADDRINUSE ladder, @@ -41,13 +41,13 @@ export const CODEX_DEFAULT_UPSTREAM = "https://api.openai.com/v1"; const BILI_ROUTE_RE = /^(http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5})\/bili\/(https?:\/\/.+)$/; -export function isBiliCodexRoute(value: string): boolean { +function isBiliCodexRoute(value: string): boolean { return BILI_ROUTE_RE.test(value.trim()); } /** Inverse of `codexRouteValue`: recover the real upstream. undefined for * anything bili did not write. */ -export function unwrapCodexRoute(value: string): string | undefined { +function unwrapCodexRoute(value: string): string | undefined { const m = BILI_ROUTE_RE.exec(value.trim()); return m ? m[2] : undefined; } @@ -72,7 +72,7 @@ export function codexRouteOrigin(env: NodeJS.ProcessEnv = process.env): string { * route must wrap. Mirrors launcher.ts `codexUpstreamUrl`'s precedence * (`model_provider`'s `base_url` > top-level `openai_base_url` > OpenAI * default) but unwraps bili's own value so re-planning never double-wraps. */ -export function codexRealUpstream(config: CodexConfig | undefined): string { +function codexRealUpstream(config: CodexConfig | undefined): string { const provider = config?.modelProvider !== undefined ? config?.providers?.[config.modelProvider]?.baseUrl @@ -87,14 +87,14 @@ export function codexRealUpstream(config: CodexConfig | undefined): string { /** Why the route cannot be (or is not) the effective one. Both are reported, * never silently "fixed": the spec forbids fighting a provider manager. */ -export type CodexRouteConflict = +type CodexRouteConflict = /** A foreign (non-bili) `openai_base_url` is already set. */ | { kind: "foreign-openai-base-url"; value: string } /** `model_provider` names a provider with its own `base_url`, so Codex * ignores the top-level field entirely — writing it would be a no-op. */ | { kind: "shadowed-by-provider"; provider: string; value: string }; -export interface CodexRoutePlan { +interface CodexRoutePlan { action: "install" | "refresh" | "keep" | "conflict"; /** The full file text after the action (`keep`/`conflict` return it unchanged). */ text: string; @@ -105,7 +105,7 @@ export interface CodexRoutePlan { note: string; } -export type CodexRouteTarget = +type CodexRouteTarget = | { kind: "top-level" } | { kind: "provider"; provider: string }; @@ -308,7 +308,7 @@ export function planCodexRoute( /** What bili currently finds in `text` — the read side of ownership, shared by * status reporting and uninstall. */ -export interface CodexRouteState { +interface CodexRouteState { /** A bili-owned route is present. */ routed: boolean; /** The raw field value, when any. */ @@ -366,18 +366,6 @@ export function desiredCodexRoute(text: string, origin: string): string { return codexRouteValue(origin, codexRealUpstream(parseCodexToml(text))); } -export function codexRouteFilePath(codexHome: string): string { - return path.join(codexHome, "config.toml"); -} - -export function readCodexRouteFile(file: string): string { - try { - return fs.readFileSync(file, "utf8"); - } catch { - return ""; - } -} - /** Remove bili's route field, leaving every other byte alone. Returns the new * text plus whether anything changed. */ export function restoreCodexRoute( diff --git a/src/codex-integration/skill.ts b/src/codex-integration/skill.ts index dd8e805071..dcaf0b4498 100644 --- a/src/codex-integration/skill.ts +++ b/src/codex-integration/skill.ts @@ -19,13 +19,13 @@ import path from "node:path"; import { resolveCodexHome } from "../client-config.js"; /** Directory name under `/skills`. */ -export const CODEX_SKILL_NAME = "bili"; +const CODEX_SKILL_NAME = "bili"; /** Ownership marker. A skill file carrying this comment is bili's and may be * refreshed in place; a same-named file WITHOUT it belongs to the user (or * another tool) and is never written or deleted — the same content-based rule * the model route and the hook face use. The name alone is not proof. */ -export const CODEX_SKILL_MARKER = +const CODEX_SKILL_MARKER = ""; /** The skill document bili installs. Kept as a constant so `codexSkillStatus` @@ -92,7 +92,7 @@ export function readSkillName(text: string): string | undefined { return name.replace(/^["']|["']$/g, ""); } -export type CodexSkillState = "installed" | "missing" | "outdated" | "foreign"; +type CodexSkillState = "installed" | "missing" | "outdated" | "foreign"; /** Disk state of the skill face. `outdated` means our marker is present but the * bytes differ (an upgrade is due, or the user edited a bili-managed file); @@ -110,7 +110,7 @@ export function codexSkillStatus( return text.includes(CODEX_SKILL_MARKER) ? "outdated" : "foreign"; } -export interface CodexSkillInstall { +interface CodexSkillInstall { state: CodexSkillState | "written"; note: string; written: boolean; diff --git a/src/codex-integration/status.ts b/src/codex-integration/status.ts index a132665af9..9cd428afc0 100644 --- a/src/codex-integration/status.ts +++ b/src/codex-integration/status.ts @@ -8,7 +8,7 @@ import { import fs from "node:fs"; import path from "node:path"; -export type CodexIntegrationState = +type CodexIntegrationState = | "proxy-ready" | "configured" | "verified" @@ -23,7 +23,7 @@ export interface CodexIntegrationReport { detail: string; } -export interface CodexStatusDeps { +interface CodexStatusDeps { env?: NodeJS.ProcessEnv; fetchImpl?: typeof fetch; codexConfigText?: string; diff --git a/src/codex-integration/toml-field.ts b/src/codex-integration/toml-field.ts index f7ec7ddf80..0f37e4d7fe 100644 --- a/src/codex-integration/toml-field.ts +++ b/src/codex-integration/toml-field.ts @@ -7,7 +7,7 @@ // rewrites the rest of the file. /** A located top-level scalar. `line` is a 0-based index into `text.split("\n")`. */ -export interface TopLevelScalar { +interface TopLevelScalar { key: string; value: string; line: number; @@ -129,7 +129,7 @@ export function removeTopLevelScalar(text: string, key: string): string { } /** A located scalar inside an exact TOML table. */ -export interface TableScalar extends TopLevelScalar { +interface TableScalar extends TopLevelScalar { table: string; } diff --git a/src/proxy-service/service.ts b/src/proxy-service/service.ts index ff3d1692b5..ec790a9cb9 100644 --- a/src/proxy-service/service.ts +++ b/src/proxy-service/service.ts @@ -42,7 +42,7 @@ import { const SERVICE_STATE_FILE = "proxy-service.json"; -export interface ProxyServiceConfig { +interface ProxyServiceConfig { taskName?: string; nodePath?: string; entryPath?: string; @@ -56,7 +56,7 @@ export interface ProxyServiceConfig { unitPath?: string; } -export interface ProxyServiceResult { +interface ProxyServiceResult { ok: boolean; action: | "installed" @@ -74,7 +74,7 @@ export interface ProxyServiceResult { output?: string; } -export interface ProxyServiceRecord { +interface ProxyServiceRecord { taskName: string; port: number; host: string; diff --git a/src/proxy-service/systemd.ts b/src/proxy-service/systemd.ts index fe50e48fff..b6761c5eba 100644 --- a/src/proxy-service/systemd.ts +++ b/src/proxy-service/systemd.ts @@ -16,7 +16,7 @@ import path from "node:path"; /** Unit basename. Fixed, like BILI_TASK_NAME: one service per machine. */ export const BILI_SYSTEMD_UNIT = "bili-proxy.service"; -export interface SystemdUnitOptions { +interface SystemdUnitOptions { nodePath: string; entryPath: string; port: number; @@ -95,12 +95,12 @@ export function renderSystemdUnit(options: SystemdUnitOptions): string { ].join("\n"); } -export interface SystemdCommand { +interface SystemdCommand { file: string; args: string[]; } -export interface SystemdQueryOptions { +interface SystemdQueryOptions { unitName?: string; unitPath?: string; } @@ -109,7 +109,7 @@ function unitNameOf(options: SystemdQueryOptions): string { return options.unitName ?? BILI_SYSTEMD_UNIT; } -export function planSystemctl( +function planSystemctl( args: string[], options: SystemdQueryOptions = {}, ): SystemdCommand { @@ -123,12 +123,6 @@ export function planDaemonReload(): SystemdCommand { return { file: "systemctl", args: ["--user", "daemon-reload"] }; } -export function planSystemdEnable( - options: SystemdQueryOptions = {}, -): SystemdCommand { - return planSystemctl(["enable"], options); -} - export function planSystemdStart( options: SystemdQueryOptions = {}, ): SystemdCommand { diff --git a/src/proxy-service/task-scheduler.ts b/src/proxy-service/task-scheduler.ts index dbd086ba1c..d42c62adc6 100644 --- a/src/proxy-service/task-scheduler.ts +++ b/src/proxy-service/task-scheduler.ts @@ -7,7 +7,7 @@ export interface TaskCommand { args: string[]; } -export interface ProxyTaskOptions { +interface ProxyTaskOptions { taskName?: string; nodePath: string; entryPath: string; From 71af23d227b33294457af839066b288a82bae4df Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 00:58:37 +0800 Subject: [PATCH 12/20] docs: document BILI_CODEX_HOOK_ORIGIN in the config reference Add the SessionStart bootstrap-hook probe override (audience: test) to the env-only YAML seed and regenerate the config-docs blocks; add the matching detail-table row in both languages. --- CONFIGURATION.md | 2 ++ CONFIGURATION.zh-CN.md | 2 ++ website/config-reference/env-only.yaml | 8 ++++++++ 3 files changed, 12 insertions(+) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index ff7a4f106c..05d5f12149 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -355,6 +355,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `BILI_MODEL_INFO_RETRY_MS` | number | (built-in) | — | Test hook: retry interval for model-info lookups. | | `BILI_DSH_RETRY_INTERVAL_MS` | number | (built-in) | — | Test hook: retry interval for dsh lane operations. | | `BILI_DSH_RECOVERY_INTERVAL_MS` | number | (built-in) | — | Test hook: recovery sweep interval for the dsh lane. | +| `BILI_CODEX_HOOK_ORIGIN` | string | unset (route origin, then lane discovery) | — | Test hook: explicit proxy origin for the Codex SessionStart bootstrap hook to probe and report to; falls back to the route bili wrote into config.toml, then sticky lane-port discovery. | | `ACP_DUMP_DIR` | string | unset | — | Base directory override for wire dump output (path relocation). | | `BILI_STREAM_STALL_MS` | number | (built-in) | — | Stall-detection timeout for committed upstream streams (no-byte silence before abort). | | `BILI_CLIENT_BIN` | string | unset (PATH lookup) | — | Explicit binary override for the launched client (resolved on PATH). | @@ -1737,6 +1738,7 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_MODEL_INFO_RETRY_MS` | Cooldown (ms) before the dsh native plugin re-resolves the current model's context window after a resolve that failed or returned no window (#1812/#1836): a cached entry without a window is not final — instead of latching headerless for the process lifetime, the next request after this cooldown triggers a retry. Default `30000`; non-numeric or negative values fall back to `30000`. Test hook — shortened by the dsh-native unit test so it never waits wall-clock; leave unset in production. | | `BILI_DSH_RETRY_INTERVAL_MS` | Back-off (ms) between dsh native plugin tool-registration retries (#2082): after a manifest fetch or tool registration fails transiently, the next retry happens no sooner than this cooldown. Default `10000`; non-numeric or non-positive values fall back to `10000`. Test hook — shortened by the dsh-native unit tests so they never wait wall-clock; leave unset in production. | | `BILI_DSH_RECOVERY_INTERVAL_MS` | Interval (ms) of the dsh native plugin's detached recovery timer (#2082): while the tools are down it keeps driving registration retries with zero model traffic — the case where the model already gave up on the missing tools and nothing else re-arms the loop. Defaults to following `BILI_DSH_RETRY_INTERVAL_MS` (`10000`). Test hook — under NODE_TEST_CONTEXT the timer never starts unless this var is set explicitly; leave unset in production. | +| `BILI_CODEX_HOOK_ORIGIN` | Explicit origin for the codex SessionStart bootstrap hook's health probe and runtime report (#3176). Fallback chain when unset: the route bili wrote into `~/.codex/config.toml`, then the sticky lane-port discovery. Attach-only and fail-open — if the probe is not healthy within its deadline the hook exits silently instead of blocking the session. Tests/odd setups; leave unset in production. | | `BILI_ADVISORY_CHECK` | Set to `0` to disable the critical-defect advisory watcher (#1481). Default ON — it runs independently of `ACP_AUTO_UPDATE` so that installs with auto-update off still get force-updated out of a known-broken version range. Fail-open: an unreachable/malformed source only warns, never blocks model traffic. File-config key: `advisoryCheck`. | | `BILI_ADVISORY_URL` | Override for the advisory document URL. Default: the companion package `billion-context-advisories` on the configured registry (`BILI_UPDATE_REGISTRY` aware). File-config key: `advisoryUrl`. | | `BILI_RELEASE_NOTES_CHECK` | Set to `0` to disable the release-notes visibility watcher (#1870). Default ON — pure visibility, silent by default (#1977): fetches the companion release-notes doc and surfaces "CRITICAL update ready — restart to finish" (disk newer than running) or "critical update available" on `acp_status` and the `/acp` panel ONLY when the pending span contains a `critical`-tier entry; routine/recommended releases never surface. Never installs, never restarts; fail-open. File-config key: `releaseNotesCheck`. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 2f4ecf6860..e05359bf6f 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -355,6 +355,7 @@ | `BILI_MODEL_INFO_RETRY_MS` | number | (built-in) | — | 测试钩子:模型信息查询的重试间隔。 | | `BILI_DSH_RETRY_INTERVAL_MS` | number | (built-in) | — | 测试钩子:dsh 车道操作的重试间隔。 | | `BILI_DSH_RECOVERY_INTERVAL_MS` | number | (built-in) | — | 测试钩子:dsh 车道恢复清扫间隔。 | +| `BILI_CODEX_HOOK_ORIGIN` | string | unset (route origin, then lane discovery) | — | 测试钩子:Codex SessionStart 引导 hook 探测/上报的显式代理 origin;未设置时回退到 bili 写入 config.toml 的路由,再到粘性车道端口发现。 | | `ACP_DUMP_DIR` | string | unset | — | 线路转储输出基础目录覆盖(路径重定位)。 | | `BILI_STREAM_STALL_MS` | number | (built-in) | — | 已提交上游流的停滞检测超时(无字节静默多久后中止)。 | | `BILI_CLIENT_BIN` | string | unset (PATH lookup) | — | 被启动客户端二进制的显式覆盖(在 PATH 上解析)。 | @@ -1735,6 +1736,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `BILI_MODEL_INFO_RETRY_MS` | dsh 原生模型窗口解析失败(或解析结果不带窗口)后的重试冷却(毫秒,#1812/#1836):匹配的缓存条目没有 context window 时不视为最终结果 —— 不再让整个进程生命周期 latching 成无 header 状态,而是该冷却过期后由下一个请求触发重新解析。默认 `30000`;非数字或负值回退 `30000`。测试钩子 —— dsh-native 单元测试用它缩短冷却、避免真实等待;生产环境保持 unset。 | | `BILI_DSH_RETRY_INTERVAL_MS` | dsh 原生插件工具注册重试的退避冷却(毫秒,#2082):manifest 拉取或工具注册瞬时失败后,下一次重试不早于该冷却发生。默认 `10000`;非数字或非正值回退 `10000`。测试钩子 —— dsh-native 单元测试用它缩短冷却、避免真实等待;生产环境保持 unset。 | | `BILI_DSH_RECOVERY_INTERVAL_MS` | dsh 原生插件独立恢复定时器的间隔(毫秒,#2082):工具处于 down 状态时,即使零模型流量也持续驱动注册重试 —— 正是模型已放弃缺失工具、其他路径都不会再触发重试的场景。默认跟随 `BILI_DSH_RETRY_INTERVAL_MS`(`10000`)。测试钩子 —— NODE_TEST_CONTEXT 下除非显式设置本变量,否则定时器永不启动;生产环境保持 unset。 | +| `BILI_CODEX_HOOK_ORIGIN` | codex SessionStart 引导 hook 健康探测与运行时上报的显式 origin(#3176)。未设置时的回退链:bili 写入 `~/.codex/config.toml` 的路由,再到粘性车道端口发现。attach-only、fail-open —— 探测未在期限内变健康时 hook 静默退出、不阻塞会话。供测试/特殊配置使用;生产环境保持 unset。 | | `BILI_ADVISORY_CHECK` | 设为 `0` 禁用严重缺陷公告监视器(#1481)。默认开启 —— 它独立于 `ACP_AUTO_UPDATE` 运行,确保关闭了自动更新的安装也能被强制移出已知缺陷版本范围。fail-open:公告源不可达/格式错误只告警,绝不阻断模型流量。文件配置键:`advisoryCheck`。 | | `BILI_ADVISORY_URL` | 公告文档 URL 覆盖。默认:已配置 registry(感知 `BILI_UPDATE_REGISTRY`)上的伴生包 `billion-context-advisories`。文件配置键:`advisoryUrl`。 | | `BILI_RELEASE_NOTES_CHECK` | 设为 `0` 禁用发版说明可见性监视器(#1870)。默认开启 —— 纯可见性,且默认静默(#1977):拉取伴生发版说明文档,仅当待更新跨度内含 `critical` 级条目时,才在 `acp_status` 与 `/acp` 面板提示「CRITICAL 更新已就绪待重启」(磁盘版本新于运行版本)或「存在 critical 更新」;routine/recommended 级发版永不上屏。绝不安装、绝不重启;fail-open。文件配置键:`releaseNotesCheck`。 | diff --git a/website/config-reference/env-only.yaml b/website/config-reference/env-only.yaml index 7b4d0c7b4e..2c304cdd57 100644 --- a/website/config-reference/env-only.yaml +++ b/website/config-reference/env-only.yaml @@ -330,6 +330,14 @@ entries: group: envonly desc_en: "Test hook: recovery sweep interval for the dsh lane." desc_zh: "测试钩子:dsh 车道恢复清扫间隔。" + - key: BILI_CODEX_HOOK_ORIGIN + type: string + default: "unset (route origin, then lane discovery)" + kind: env-only + audience: test + group: envonly + desc_en: "Test hook: explicit proxy origin for the Codex SessionStart bootstrap hook to probe and report to; falls back to the route bili wrote into config.toml, then sticky lane-port discovery." + desc_zh: "测试钩子:Codex SessionStart 引导 hook 探测/上报的显式代理 origin;未设置时回退到 bili 写入 config.toml 的路由,再到粘性车道端口发现。" - key: ACP_DUMP_DIR type: string default: "unset" From 8d731922d7dd14bd901182caba6b1e47a9747a81 Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 01:21:57 +0800 Subject: [PATCH 13/20] test: make codex install-faces test hermetic without a bundle CI's test lanes run the TS sources without bundling, so the four-faces regression could not pass there: it hard-required dist/codex/bootstrap-hook.js. Materialize that single presence-checked file when absent and remove exactly what the test created, keeping the sibling skip-behavior test honest. --- tests/codex-install-faces.test.ts | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/tests/codex-install-faces.test.ts b/tests/codex-install-faces.test.ts index 0079d6835a..71f9dfc169 100644 --- a/tests/codex-install-faces.test.ts +++ b/tests/codex-install-faces.test.ts @@ -40,20 +40,23 @@ test("plugin install codex writes MCP + route + hook + skill, and remove reverts const { pluginInstall, pluginRemove, pluginStatusAll } = await import( "../src/plugin-install.ts" ); + // `dist/` must exist on disk: the installer refuses to register a hook + // whose script is not built. CI's test lanes run the TS sources without + // bundling, so materialize the single file the installer checks for and + // remove exactly what we created. + const root = path.dirname(path.dirname(path.resolve("src/plugin-install.ts"))); + const distDir = path.join(root, "dist"); + const codexDir = path.join(distDir, "codex"); + const hookScript = path.join(codexDir, "bootstrap-hook.js"); + const createdDist = !fs.existsSync(distDir); + const createdCodex = !fs.existsSync(codexDir); + const createdHook = !fs.existsSync(hookScript); + if (createdHook) { + fs.mkdirSync(codexDir, { recursive: true }); + fs.writeFileSync(hookScript, "// test stub: presence only\n"); + } try { await withEnv({ CODEX_HOME: home }, () => { - // `dist/` must exist on disk: the installer refuses to register a - // hook whose script is not built, so simulate a built checkout. - const root = path.dirname( - path.dirname(path.resolve("src/plugin-install.ts")), - ); - const hookScript = path.join(root, "dist", "codex", "bootstrap-hook.js"); - assert.equal( - fs.existsSync(hookScript), - true, - "build before running this test: npm run build", - ); - const message = pluginInstall("codex"); assert.match(message, /^codex: installed/); assert.match(message, /mcp: installed \[mcp_servers\.bili\]/); @@ -112,6 +115,9 @@ test("plugin install codex writes MCP + route + hook + skill, and remove reverts }); } finally { fs.rmSync(home, { recursive: true, force: true }); + if (createdHook) fs.rmSync(hookScript, { force: true }); + if (createdCodex) fs.rmSync(codexDir, { recursive: true, force: true }); + if (createdDist) fs.rmSync(distDir, { recursive: true, force: true }); } }); From 382e6665bff165d79198ea6517d51d364301ec9c Mon Sep 17 00:00:00 2001 From: ework-daemon Date: Sun, 25 Oct 2026 06:45:28 +0800 Subject: [PATCH 14/20] fix(ci): register BILI_CODEX_HOOK_ORIGIN in LIFECYCLE.md ledger MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The codex SessionStart hook (src/codex/bootstrap-hook.ts) reads BILI_CODEX_HOOK_ORIGIN as its probe-target override, but the var was never registered in the lifecycle ledger, so lifecycle-ledger-guard failed on the PR head while master stayed green. Registered under §2.2 (internal spawn channel, next to the analogous BILI_STRICT_PORT host-hook knob). PR #3176 --- LIFECYCLE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/LIFECYCLE.md b/LIFECYCLE.md index 3c72995136..2c6271153b 100644 --- a/LIFECYCLE.md +++ b/LIFECYCLE.md @@ -75,6 +75,7 @@ | `BILI_NON_HTTP_PROVIDERS` | #1392 非 http(s) baseUrl provider 白名单传递 | | `BILI_PROVIDER_REWRITES` | #535 provider 改写 manifest JSON(存在即关 zcode native) | | `BILI_UPGRADE_REPLACEMENT` | #3044 self-restart 替换进程交接标记(UPGRADE_REPLACEMENT_ENV) | +| `BILI_CODEX_HOOK_ORIGIN` | codex SessionStart hook 探测目标覆盖(测试/特殊配置;默认 = codex 车道 origin,#3176) | ### 2.3 网络调优(#2030 迁移家族:env > 文件 network.* > 默认) From 932f6e2d69d797ab958198bbe3cd7bcd1c8f13c2 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 07:42:10 +0800 Subject: [PATCH 15/20] fix(ci): drop leading export from ClientBuildCheck (INTERNAL_ONLY) Inherited unused-exports red from master tip (#4545 train left this type-only declaration exported with zero external references). Same one-line de-export as PR #4606; the type is referenced only within this module. --- src/agent/client-build-note.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/agent/client-build-note.ts b/src/agent/client-build-note.ts index 8ca7e9ddaf..6c08149309 100644 --- a/src/agent/client-build-note.ts +++ b/src/agent/client-build-note.ts @@ -29,7 +29,7 @@ import path from "node:path"; import { isVersionNewer } from "../update.js"; import { logHostEvent } from "./host-log.js"; -export type ClientBuildCheck = { +type ClientBuildCheck = { /** Short human label used in the note text ("dsh", "pi", ...). */ label: string; /** The client's npm id, as shown in the note (@deepseek-ai/dsh, ...). */ From 7f4ca48344f2615122f6f64831e7e5f66e1628df Mon Sep 17 00:00:00 2001 From: Eliver Date: Mon, 9 Nov 2026 10:45:37 +0800 Subject: [PATCH 16/20] feat: warn when dsh's iot-thinking plugin is installed iot-thinking issues its own extra compress/rewrite model call after every reply; both calls share one session lane, so the step keeps waiting seconds to tens of seconds after its first byte (measured: the extra request shape was 44% of one session's requests, p50 ~7s, and vanished when the plugin was disabled). Owners could not see the cause from bili's side. Register a fourth builtin notice (KDD #16 surface, no new channel): - src/notice-store.ts: iot-incompat id + dismissal allowlist - src/notices.ts: probeDshIotThinking scans dsh profile dirs for node_modules/dsh-plugin-iot-thinking (never throws; advisory) - src/web/i18n.ts: en/zh copy - tests: registry id/allowlist rows + hermetic detection/dismissal suite --- src/notice-store.ts | 7 ++++- src/notices.ts | 40 +++++++++++++++++++++++++- src/pck-notice.ts | 4 +-- src/web/i18n.ts | 8 ++++++ tests/iot-incompat-notice.test.ts | 48 +++++++++++++++++++++++++++++++ tests/notice-registry.test.ts | 13 +++++++-- 6 files changed, 113 insertions(+), 7 deletions(-) create mode 100644 tests/iot-incompat-notice.test.ts diff --git a/src/notice-store.ts b/src/notice-store.ts index 9083337185..289452f4c8 100644 --- a/src/notice-store.ts +++ b/src/notice-store.ts @@ -24,8 +24,13 @@ export const PCK_NOTICE_ID = "pck-default-off"; // #5403 watermark fastpath experimental-grey intro (owner ruling 2026-11-02): // own id so dismissal stays independent of pck's. export const WM_FASTPATH_INTRO_ID = "wm-fastpath-intro"; +// Owner report 2026-11-09: dsh's iot-thinking plugin fires one extra +// compress/rewrite request after every model reply, occupying the SAME +// session's proxy lane serially — the step keeps waiting seconds to tens of +// seconds after its first byte. Own id so its dismissal is independent. +export const IOT_INCOMPAT_NOTICE_ID = "iot-incompat"; -const UPGRADE_NOTICE_IDS: ReadonlySet = new Set([PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID]); +const UPGRADE_NOTICE_IDS: ReadonlySet = new Set([PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID, IOT_INCOMPAT_NOTICE_ID]); // #5548 P2: local announcements dismiss as `@` so edited // content re-nags exactly once; the hash shape is the only dynamic form the // store accepts (raw local ids never enter it — those use instance/always). diff --git a/src/notices.ts b/src/notices.ts index 1573e4e44f..db864aa5e8 100644 --- a/src/notices.ts +++ b/src/notices.ts @@ -4,9 +4,12 @@ // other file touches per-notice code again. Display semantics (tone color, // action words) come from the web layer; activity predicates live HERE so the // server-side judgment never scatters back into route handlers. +import fs from "node:fs"; +import path from "node:path"; import { effectivePromptCacheRouting, loadConfigFile } from "./config.js"; +import { dshProfileDirs } from "./dsh-channel.js"; import { featureOverrideAbsent } from "./rollout.js"; -import { PCK_NOTICE_ID, dismissedUpgradeNotices, pckNoticeActive, WM_FASTPATH_INTRO_ID } from "./pck-notice.js"; +import { IOT_INCOMPAT_NOTICE_ID, PCK_NOTICE_ID, dismissedUpgradeNotices, pckNoticeActive, WM_FASTPATH_INTRO_ID } from "./pck-notice.js"; interface NoticeEntry { readonly id: string; @@ -36,8 +39,43 @@ export const NOTICES: readonly NoticeEntry[] = [ !dismissedUpgradeNotices(process.env).has(WM_FASTPATH_INTRO_ID) && featureOverrideAbsent("pluginFullResendWatermark", loadConfigFile().rollout), }, + // Owner report 2026-11-09: dsh's iot-thinking plugin rewrites/hides the + // thinking channel through a SECOND, self-issued model call after every + // reply. Both calls share one session lane, so the step keeps waiting + // after its first byte — the measured gap tracked that rewrite call's own + // latency (p50 ~7s per step) and the extra requests vanished when the + // plugin was disabled (44% of one session's requests were that shape). + // Installed ⇒ warn; presence is the whole predicate, no config knobs. + { + id: IOT_INCOMPAT_NOTICE_ID, + tone: "warn", + keys: { on: "iotcompat.on", desc: "iotcompat.desc", hint: "iotcompat.hint", dismiss: "iotcompat.dismiss_btn" }, + active: () => + !dismissedUpgradeNotices(process.env).has(IOT_INCOMPAT_NOTICE_ID) && + probeDshIotThinking(process.env), + }, ]; +/** Uncached: does ANY dsh profile carry the iot-thinking plugin? Never throws + * (no profiles / unreadable home ⇒ false — an advisory must not fail a page). */ +export function probeDshIotThinking(env: NodeJS.ProcessEnv = process.env): boolean { + let dirs: string[]; + try { + dirs = dshProfileDirs(env); + } catch { + return false; + } + for (const dir of dirs) { + try { + if (fs.existsSync(path.join(dir, "node_modules", "dsh-plugin-iot-thinking", "package.json"))) return true; + } catch { + // unreadable profile: keep scanning the rest + } + } + return false; +} + + /** Currently-visible notices, in registry order. Never throws. */ export function visibleNotices(): Array<{ id: string; tone: "ok" | "warn"; keys: NoticeEntry["keys"] }> { const out: Array<{ id: string; tone: "ok" | "warn"; keys: NoticeEntry["keys"] }> = []; diff --git a/src/pck-notice.ts b/src/pck-notice.ts index 68e81cd2f5..c93d8172c4 100644 --- a/src/pck-notice.ts +++ b/src/pck-notice.ts @@ -27,9 +27,9 @@ import { persistDismissedKey, unifiedReceiptsActive, } from "./notice-store.js"; -import { PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID } from "./notice-store.js"; +import { IOT_INCOMPAT_NOTICE_ID, PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID } from "./notice-store.js"; -export { PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID }; +export { IOT_INCOMPAT_NOTICE_ID, PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID }; const DISMISS_FILE = "upgrade-notices.json"; diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 95ad37ed4d..aa30714195 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -299,6 +299,10 @@ export const MESSAGES: Record> = { "wmfast.desc": "长会话每轮都要把整个历史重新发给代理解析一遍,现在改为增量解析:只解析本轮新增的那部分,优化长会话的解析性能(发给模型的内容不变;有任何疑点,当轮自动回退老路径并重新对齐)。当前版本对约 5% 的安装灰度开启,属实验性功能。", "wmfast.hint": "开关在「配置」页快速配置(大上下文增量解析),也可在 billion-context.json 写 rollout.features.pluginFullResendWatermark: true/false,或设环境变量 BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK=1/0。", "wmfast.dismiss_btn": "我知道了", + "iotcompat.on": "检测到不兼容插件:dsh 的 iot-thinking(会造成额外等待)", + "iotcompat.desc": "该插件在每次模型回复后额外发起一轮自己的压缩/改写请求,占用同一会话的代理通道并串行执行——表现为首字已经回来,这一步还要再等数秒到十几秒;开启压缩时会话内排队更明显。", + "iotcompat.hint": "建议在 dsh 侧关闭或卸载 dsh-plugin-iot-thinking(其 config.json 里 enabled=false,或 dsh plugin --profile remove dsh-plugin-iot-thinking);bili 侧无需改动。", + "iotcompat.dismiss_btn": "我知道了", "notices.dismissed": "已关闭该提示", "notices.dismiss_btn": "我知道了", "ses.title": "会话", @@ -1043,6 +1047,10 @@ export const MESSAGES: Record> = { "pckoff.desc": "Since this version bili no longer adds OpenAI's prompt_cache_key field to requests on its own (previously on by default). If your upstream routes prefix cache by this key (relays such as workbuddy panel/hub, account pools), turn the switch back on — otherwise traffic may route randomly and miss the prefix cache.", "pckoff.hint": "Switch: Configuration page → quick config (promptCache.routing: disabled/auto/enabled), or edit billion-context.json directly; direct official-API users can ignore this notice.", "pckoff.dismiss_btn": "Got it", + "iotcompat.on": "Incompatible plugin detected: dsh's iot-thinking (adds extra waiting)", + "iotcompat.desc": "After every model reply this plugin issues its own extra compress/rewrite request through the SAME session lane, serially — the step keeps waiting for seconds to tens of seconds after its first byte has arrived; the queueing is more visible while compression is active.", + "iotcompat.hint": "Disable or uninstall dsh-plugin-iot-thinking on the dsh side (set enabled=false in its config.json, or run dsh plugin --profile remove dsh-plugin-iot-thinking). Nothing needs to change in bili.", + "iotcompat.dismiss_btn": "Got it", "wmfast.on": "New: incremental parsing for large contexts (incremental-compression bridge feature, experimental)", "wmfast.desc": "Long conversations used to re-send their entire history for parsing on every turn. Now only the new part of each turn is parsed — faster parsing on long sessions (the request sent to the model is unchanged; any doubt falls back to the old path for that turn and re-aligns). This release rolls it out to roughly 5% of installs; it is marked experimental.", "wmfast.hint": "Switch: Configuration page → quick config (incremental parsing for large contexts), or write rollout.features.pluginFullResendWatermark: true/false in billion-context.json, or set BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK=1/0.", diff --git a/tests/iot-incompat-notice.test.ts b/tests/iot-incompat-notice.test.ts new file mode 100644 index 0000000000..9a232c61fc --- /dev/null +++ b/tests/iot-incompat-notice.test.ts @@ -0,0 +1,48 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +// Owner report 2026-11-09: dsh's iot-thinking plugin issues one extra +// compress/rewrite call after every reply; both calls share one session lane, +// so the step waits seconds after its first byte. The registry exposes that as +// a warn notice; detection is a plain "is it installed in any dsh profile". +// Hermetic: fresh DSH_HOME (no profiles), state and config isolated. + +const home = fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-home-")); +process.env.DSH_HOME = home; +process.env.XDG_STATE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-state-")); +process.env.BILI_CONFIG_FILE = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-cfg-")), "absent.json"); + +const { NOTICES, probeDshIotThinking } = await import("../src/notices.ts"); +const { IOT_INCOMPAT_NOTICE_ID, dismissUpgradeNotice } = await import("../src/pck-notice.ts"); + +const entry = () => { + const found = NOTICES.find((n) => n.id === IOT_INCOMPAT_NOTICE_ID); + assert.ok(found, "registry carries the iot-incompat entry"); + return found; +}; + +test("no dsh profiles ⇒ not detected, notice inactive", () => { + assert.equal(probeDshIotThinking(process.env), false); + assert.equal(entry().active(), false); +}); + +test("plugin installed in one profile ⇒ detected, notice active", () => { + const pkg = path.join(home, "profiles", "web", "node_modules", "dsh-plugin-iot-thinking"); + fs.mkdirSync(pkg, { recursive: true }); + fs.writeFileSync(path.join(pkg, "package.json"), JSON.stringify({ name: "dsh-plugin-iot-thinking", version: "0.0.0" })); + assert.equal(probeDshIotThinking(process.env), true); + assert.equal(entry().active(), true); +}); + +test("dismissal hides the notice for later polls", () => { + assert.equal(dismissUpgradeNotice(IOT_INCOMPAT_NOTICE_ID, process.env), true); + assert.equal(entry().active(), false); +}); + +test("a different dsh home without profiles probes clean", () => { + const other = fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-home2-")); + assert.equal(probeDshIotThinking({ ...process.env, DSH_HOME: other }), false); +}); diff --git a/tests/notice-registry.test.ts b/tests/notice-registry.test.ts index 347929a3c8..65c02544f9 100644 --- a/tests/notice-registry.test.ts +++ b/tests/notice-registry.test.ts @@ -12,17 +12,20 @@ import path from "node:path"; const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "notice-reg-state-")); const cfgPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "notice-reg-cfg-")), "absent.json"); +// Hermetic dsh home too: the iot-thinking probe must see NO profiles here, or +// a developer machine that has the plugin installed changes the expectations. +process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "notice-reg-dsh-")); process.env.XDG_STATE_HOME = stateDir; process.env.BILI_CONFIG_FILE = cfgPath; const { NOTICES, visibleNotices } = await import("../src/notices.ts"); -const { PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID, dismissUpgradeNotice } = await import("../src/pck-notice.ts"); +const { IOT_INCOMPAT_NOTICE_ID, PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID, dismissUpgradeNotice } = await import("../src/pck-notice.ts"); const { MESSAGES, LOCALES } = await import("../src/web/i18n.ts"); test("registry: unique ids, valid tones, every key resolves in both locales", () => { const ids = NOTICES.map((n) => n.id); assert.equal(new Set(ids).size, ids.length, "ids must be unique"); - assert.deepEqual([...ids].sort(), [PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID].sort()); + assert.deepEqual([...ids].sort(), [IOT_INCOMPAT_NOTICE_ID, PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID].sort()); for (const n of NOTICES) { assert.ok(n.tone === "ok" || n.tone === "warn", `${n.id} tone`); for (const locale of LOCALES) { @@ -34,12 +37,16 @@ test("registry: unique ids, valid tones, every key resolves in both locales", () } }); -test("visibleNotices: fresh install sees both, registry order", () => { +test("visibleNotices: fresh install sees both, registry order (iot absent ⇒ hidden)", () => { const v = visibleNotices(); assert.deepEqual(v.map((n) => n.id), [PCK_NOTICE_ID, WM_FASTPATH_INTRO_ID]); assert.deepEqual(v.map((n) => n.tone), ["warn", "ok"]); }); +test("iot notice id is a dismissible builtin (no 400 on close)", () => { + assert.equal(dismissUpgradeNotice(IOT_INCOMPAT_NOTICE_ID, process.env), true); +}); + test("visibleNotices: dismissing one hides only that one", () => { assert.equal(dismissUpgradeNotice(WM_FASTPATH_INTRO_ID, process.env), true); const v = visibleNotices(); From 223bd273cd8ef40d9321b93c01d2e047145a3a39 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 9 Nov 2026 11:01:23 +0800 Subject: [PATCH 17/20] fix(ci): register issue5955 takeover test in LIVE_FILES + tolerate documented one-observation loss Byte-identical mirror of in-flight PR #5990, inlined onto this PR branch per #4599 coordination for the inherited red: master commit 48f9e69160 (#5989) added tests/issue5955-wedged-same-lane-takeover.test.ts without registering it in scripts/live-files.mjs, so the SPAWN_RE tripwire (#1248) in scripts/run-ci-tests.mjs killed all 11 test shards at pretest before any test ran. The second hunk tolerates the wedged-ledger's documented worst-case one-observation read-modify-write loss instead of turning an fs-timing hiccup into a CI flake. When #5990 merges to master these hunks dedup cleanly (byte-identical changes merge without conflict). Verified locally: tripwire scan clean (1147 test files / 62 live entries, zero unregistered spawning files); issue5955 suite 18/18 pass. --- scripts/live-files.mjs | 7 +++++++ tests/issue5955-wedged-same-lane-takeover.test.ts | 9 ++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/scripts/live-files.mjs b/scripts/live-files.mjs index 21faf81617..cf260c49ba 100644 --- a/scripts/live-files.mjs +++ b/scripts/live-files.mjs @@ -117,6 +117,13 @@ export const LIVE_FILES = [ // network I/O and binds no port, so no zone band is needed — the entry is for // the tripwire alone, like #3890/#5114 "tests/cache-keepalive.test.ts", + // #5955: the only real child is ONE bare `node -e ""` spawned purely to + // hand back an already-reaped pid (win32 taskkill-then-SIGKILL silence); + // the takeover ladder itself runs on INJECTED deps — no proxy is started, + // no port is bound, no shutdown/kill signal ever reaches the OS. Fixed + // fake origins only, so no zone band is needed — the entry is for the + // tripwire alone, like #3890/#5114/#5666 + "tests/issue5955-wedged-same-lane-takeover.test.ts", ]; /** Band width per live file: the zone ladder drifts +1 per EADDRINUSE retry; diff --git a/tests/issue5955-wedged-same-lane-takeover.test.ts b/tests/issue5955-wedged-same-lane-takeover.test.ts index 314c2c1a1b..1aecf50f48 100644 --- a/tests/issue5955-wedged-same-lane-takeover.test.ts +++ b/tests/issue5955-wedged-same-lane-takeover.test.ts @@ -429,7 +429,14 @@ test("#5955 full path: kill fails → fall through to normal spawn, ledger kept, assert.equal(watchingLines(w).length, 2, "only the pre-escalation cycles logged the watching line"); const entries = readLedger(); assert.equal(Object.keys(entries).length, 1, "surviving occupant keeps its ledger entry for the retry"); - assert.equal(Object.values(entries)[0].observations, 5, "observations accumulate across failed escalations"); + // Five bring-ups, five observations — but the ledger's documented worst case + // is a lost read-modify-write (readWedgedLedger contract: "the worst case + // loses one observation ... which is safe"), so tolerate exactly that one + // loss instead of turning an fs-timing hiccup into a CI flake. Anything + // below 4 means observations are NOT bridging the gap (the patience window + // would restart every cycle and the takeover could never fire). + const observed = Object.values(entries)[0].observations; + assert.ok(observed === 5 || observed === 4, `observations accumulate across failed escalations (got ${observed}, expected 5, or 4 for the documented one-observation loss)`); }); test("#5955 full path: port:0 bring-up resolves the sticky lane port lazily", async () => { From effbe63c60dc1c551dc814fb889e2ad3695d4a35 Mon Sep 17 00:00:00 2001 From: Eliver Date: Mon, 9 Nov 2026 11:35:04 +0800 Subject: [PATCH 18/20] fix: warn about iot-thinking only while it is enabled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Installed-but-disabled is the healthy state: the plugin's extra rewrite call is what produces the post-first-byte wait, and turning it off removes it. Gate the notice on the plugin's own effective switch instead of bare presence (missing/broken config keeps the plugin default, enabled). Verified on the owner's machine: installed=true, enabled=false ⇒ active=false. --- src/notices.ts | 21 +++++++++++++++++++-- src/web/i18n.ts | 4 ++-- tests/iot-incompat-notice.test.ts | 29 +++++++++++++++++++++++++---- 3 files changed, 46 insertions(+), 8 deletions(-) diff --git a/src/notices.ts b/src/notices.ts index db864aa5e8..2db3ba36c4 100644 --- a/src/notices.ts +++ b/src/notices.ts @@ -7,6 +7,7 @@ import fs from "node:fs"; import path from "node:path"; import { effectivePromptCacheRouting, loadConfigFile } from "./config.js"; +import { resolveDshHome } from "./client-config.js"; import { dshProfileDirs } from "./dsh-channel.js"; import { featureOverrideAbsent } from "./rollout.js"; import { IOT_INCOMPAT_NOTICE_ID, PCK_NOTICE_ID, dismissedUpgradeNotices, pckNoticeActive, WM_FASTPATH_INTRO_ID } from "./pck-notice.js"; @@ -45,14 +46,16 @@ export const NOTICES: readonly NoticeEntry[] = [ // after its first byte — the measured gap tracked that rewrite call's own // latency (p50 ~7s per step) and the extra requests vanished when the // plugin was disabled (44% of one session's requests were that shape). - // Installed ⇒ warn; presence is the whole predicate, no config knobs. + // Installed AND not switched off in its own config ⇒ warn (owner ruling + // 2026-11-09: disabling the plugin removes the extra wait, so the notice + // must go away with it and only reappear when it is turned back on). { id: IOT_INCOMPAT_NOTICE_ID, tone: "warn", keys: { on: "iotcompat.on", desc: "iotcompat.desc", hint: "iotcompat.hint", dismiss: "iotcompat.dismiss_btn" }, active: () => !dismissedUpgradeNotices(process.env).has(IOT_INCOMPAT_NOTICE_ID) && - probeDshIotThinking(process.env), + dshIotThinkingActive(process.env), }, ]; @@ -75,6 +78,20 @@ export function probeDshIotThinking(env: NodeJS.ProcessEnv = process.env): boole return false; } +/** Installed AND effective-enabled. The plugin's own default is enabled + * (its config-store seeds enabled: true), so a missing/unreadable config + * keeps the warning; only an explicit enabled: false silences it. */ +export function dshIotThinkingActive(env: NodeJS.ProcessEnv = process.env): boolean { + if (!probeDshIotThinking(env)) return false; + try { + const raw = fs.readFileSync(path.join(resolveDshHome(env), "plugin-data", "iot-thinking", "config.json"), "utf8"); + const doc: unknown = JSON.parse(raw); + if (doc !== null && typeof doc === "object" && (doc as { enabled?: unknown }).enabled === false) return false; + } catch { + // absent/broken config ⇒ plugin runs on its default (enabled) + } + return true; +} /** Currently-visible notices, in registry order. Never throws. */ export function visibleNotices(): Array<{ id: string; tone: "ok" | "warn"; keys: NoticeEntry["keys"] }> { diff --git a/src/web/i18n.ts b/src/web/i18n.ts index aa30714195..1dc3aaffc0 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -301,7 +301,7 @@ export const MESSAGES: Record> = { "wmfast.dismiss_btn": "我知道了", "iotcompat.on": "检测到不兼容插件:dsh 的 iot-thinking(会造成额外等待)", "iotcompat.desc": "该插件在每次模型回复后额外发起一轮自己的压缩/改写请求,占用同一会话的代理通道并串行执行——表现为首字已经回来,这一步还要再等数秒到十几秒;开启压缩时会话内排队更明显。", - "iotcompat.hint": "建议在 dsh 侧关闭或卸载 dsh-plugin-iot-thinking(其 config.json 里 enabled=false,或 dsh plugin --profile remove dsh-plugin-iot-thinking);bili 侧无需改动。", + "iotcompat.hint": "建议在 dsh 侧关闭或卸载 dsh-plugin-iot-thinking(其 config.json 里 enabled=false,或 dsh plugin --profile remove dsh-plugin-iot-thinking);关闭后本提示会自动消失,bili 侧无需改动。", "iotcompat.dismiss_btn": "我知道了", "notices.dismissed": "已关闭该提示", "notices.dismiss_btn": "我知道了", @@ -1049,7 +1049,7 @@ export const MESSAGES: Record> = { "pckoff.dismiss_btn": "Got it", "iotcompat.on": "Incompatible plugin detected: dsh's iot-thinking (adds extra waiting)", "iotcompat.desc": "After every model reply this plugin issues its own extra compress/rewrite request through the SAME session lane, serially — the step keeps waiting for seconds to tens of seconds after its first byte has arrived; the queueing is more visible while compression is active.", - "iotcompat.hint": "Disable or uninstall dsh-plugin-iot-thinking on the dsh side (set enabled=false in its config.json, or run dsh plugin --profile remove dsh-plugin-iot-thinking). Nothing needs to change in bili.", + "iotcompat.hint": "Disable or uninstall dsh-plugin-iot-thinking on the dsh side (set enabled=false in its config.json, or run dsh plugin --profile remove dsh-plugin-iot-thinking); this notice disappears once it is off. Nothing needs to change in bili.", "iotcompat.dismiss_btn": "Got it", "wmfast.on": "New: incremental parsing for large contexts (incremental-compression bridge feature, experimental)", "wmfast.desc": "Long conversations used to re-send their entire history for parsing on every turn. Now only the new part of each turn is parsed — faster parsing on long sessions (the request sent to the model is unchanged; any doubt falls back to the old path for that turn and re-aligns). This release rolls it out to roughly 5% of installs; it is marked experimental.", diff --git a/tests/iot-incompat-notice.test.ts b/tests/iot-incompat-notice.test.ts index 9a232c61fc..45a067be8e 100644 --- a/tests/iot-incompat-notice.test.ts +++ b/tests/iot-incompat-notice.test.ts @@ -7,7 +7,8 @@ import path from "node:path"; // Owner report 2026-11-09: dsh's iot-thinking plugin issues one extra // compress/rewrite call after every reply; both calls share one session lane, // so the step waits seconds after its first byte. The registry exposes that as -// a warn notice; detection is a plain "is it installed in any dsh profile". +// a warn notice, gated on "installed AND still enabled" (disabling the plugin +// removes the wait, so the notice must go away with it). // Hermetic: fresh DSH_HOME (no profiles), state and config isolated. const home = fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-home-")); @@ -15,7 +16,7 @@ process.env.DSH_HOME = home; process.env.XDG_STATE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-state-")); process.env.BILI_CONFIG_FILE = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-cfg-")), "absent.json"); -const { NOTICES, probeDshIotThinking } = await import("../src/notices.ts"); +const { NOTICES, probeDshIotThinking, dshIotThinkingActive } = await import("../src/notices.ts"); const { IOT_INCOMPAT_NOTICE_ID, dismissUpgradeNotice } = await import("../src/pck-notice.ts"); const entry = () => { @@ -23,17 +24,37 @@ const entry = () => { assert.ok(found, "registry carries the iot-incompat entry"); return found; }; +const writeConfig = (doc: unknown): void => { + const dir = path.join(home, "plugin-data", "iot-thinking"); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, "config.json"), JSON.stringify(doc)); +}; test("no dsh profiles ⇒ not detected, notice inactive", () => { assert.equal(probeDshIotThinking(process.env), false); + assert.equal(dshIotThinkingActive(process.env), false); assert.equal(entry().active(), false); }); -test("plugin installed in one profile ⇒ detected, notice active", () => { +test("installed with no config yet ⇒ active (plugin default is enabled)", () => { const pkg = path.join(home, "profiles", "web", "node_modules", "dsh-plugin-iot-thinking"); fs.mkdirSync(pkg, { recursive: true }); - fs.writeFileSync(path.join(pkg, "package.json"), JSON.stringify({ name: "dsh-plugin-iot-thinking", version: "0.0.0" })); + fs.writeFileSync(path.join(pkg, "package.json"), JSON.stringify({ name: "dsh-plugin-iot-thinking", version: "0.2.0" })); + assert.equal(probeDshIotThinking(process.env), true); + assert.equal(dshIotThinkingActive(process.env), true); + assert.equal(entry().active(), true); +}); + +test("explicit enabled:false ⇒ installed but silent", () => { + writeConfig({ enabled: false }); assert.equal(probeDshIotThinking(process.env), true); + assert.equal(dshIotThinkingActive(process.env), false); + assert.equal(entry().active(), false); +}); + +test("turning it back on ⇒ notice returns", () => { + writeConfig({ enabled: true }); + assert.equal(dshIotThinkingActive(process.env), true); assert.equal(entry().active(), true); }); From bab610eea772e7e56a9f6fbca73034ef8319aac9 Mon Sep 17 00:00:00 2001 From: Eliver Date: Mon, 9 Nov 2026 15:48:48 +0800 Subject: [PATCH 19/20] fix(web): show built-in notice banners (missing .show class) --- src/web/client.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/web/client.ts b/src/web/client.ts index 6414556c49..939c3f7c10 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -1682,6 +1682,9 @@ function changelogCatOf(rawLine) { if (!n || typeof n !== "object" || typeof n.id !== "string") continue; const el = document.createElement("div"); el.className = "banner " + (n.tone === "ok" ? "ok" : n.tone === "warn" ? "warn" : ""); + // .banner is display:none until .show — #5548's loop never added it, + // so every merged notice (builtin + file + feed) rendered invisibly. + el.classList.add("show"); el.dataset.id = n.id; nr.appendChild(el); if (n.source !== "builtin") { From c2172abc344fd909d2085b4499a5cec876328391 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 9 Nov 2026 16:06:22 +0800 Subject: [PATCH 20/20] fix(web-i18n): move iot-thinking probe helpers out of src/notices.ts tests/web-i18n.test.ts (#1024 'every referenced key exists in both locales') scans src/notices.ts for quoted dot-qualified identifiers and treats each as a catalog-key reference (the #5345 verbatim-acceptance design). The new iot-incompat notice probe carried the path literals "package.json" and "config.json" inside that scanned file, so the gate failed deterministically on every platform/shard ('referenced key missing from zh catalog: package.json'; 'config.json' was next in line). Relocated probeDshIotThinking + dshIotThinkingActive to src/dsh-channel.ts, next to the dshProfileDirs/resolveDshHome helpers they exclusively use; behavior is byte-identical, zero logic change. The iot-incompat test now imports them from their new home. Verified locally: web-i18n + iot-incompat-notice + notice-registry suites 21/21 pass; unused-export gate clean; tsc --noEmit clean. --- src/dsh-channel.ts | 34 +++++++++++++++++++++++++++ src/notices.ts | 39 +------------------------------ tests/iot-incompat-notice.test.ts | 3 ++- 3 files changed, 37 insertions(+), 39 deletions(-) diff --git a/src/dsh-channel.ts b/src/dsh-channel.ts index 9427c5cb0c..b0fec4d661 100644 --- a/src/dsh-channel.ts +++ b/src/dsh-channel.ts @@ -43,6 +43,40 @@ export function dshProfileDirs(env: NodeJS.ProcessEnv = process.env): string[] { return entries.filter((e) => e.isDirectory() && e.name !== "node_modules").map((e) => path.join(profiles, e.name)); } +/** Uncached: does ANY dsh profile carry the iot-thinking plugin? Never throws + * (no profiles / unreadable home ⇒ false — an advisory must not fail a page). */ +export function probeDshIotThinking(env: NodeJS.ProcessEnv = process.env): boolean { + let dirs: string[]; + try { + dirs = dshProfileDirs(env); + } catch { + return false; + } + for (const dir of dirs) { + try { + if (fs.existsSync(path.join(dir, "node_modules", "dsh-plugin-iot-thinking", "package.json"))) return true; + } catch { + // unreadable profile: keep scanning the rest + } + } + return false; +} + +/** Installed AND effective-enabled. The plugin's own default is enabled + * (its config-store seeds enabled: true), so a missing/unreadable config + * keeps the warning; only an explicit enabled: false silences it. */ +export function dshIotThinkingActive(env: NodeJS.ProcessEnv = process.env): boolean { + if (!probeDshIotThinking(env)) return false; + try { + const raw = fs.readFileSync(path.join(resolveDshHome(env), "plugin-data", "iot-thinking", "config.json"), "utf8"); + const doc: unknown = JSON.parse(raw); + if (doc !== null && typeof doc === "object" && (doc as { enabled?: unknown }).enabled === false) return false; + } catch { + // absent/broken config ⇒ plugin runs on its default (enabled) + } + return true; +} + // — cordis.patch.yml entry parsing (#3838) ———————————————————————————————— interface DshPatchEntry { diff --git a/src/notices.ts b/src/notices.ts index 2db3ba36c4..2b46a9735d 100644 --- a/src/notices.ts +++ b/src/notices.ts @@ -4,11 +4,8 @@ // other file touches per-notice code again. Display semantics (tone color, // action words) come from the web layer; activity predicates live HERE so the // server-side judgment never scatters back into route handlers. -import fs from "node:fs"; -import path from "node:path"; import { effectivePromptCacheRouting, loadConfigFile } from "./config.js"; -import { resolveDshHome } from "./client-config.js"; -import { dshProfileDirs } from "./dsh-channel.js"; +import { dshIotThinkingActive } from "./dsh-channel.js"; import { featureOverrideAbsent } from "./rollout.js"; import { IOT_INCOMPAT_NOTICE_ID, PCK_NOTICE_ID, dismissedUpgradeNotices, pckNoticeActive, WM_FASTPATH_INTRO_ID } from "./pck-notice.js"; @@ -59,40 +56,6 @@ export const NOTICES: readonly NoticeEntry[] = [ }, ]; -/** Uncached: does ANY dsh profile carry the iot-thinking plugin? Never throws - * (no profiles / unreadable home ⇒ false — an advisory must not fail a page). */ -export function probeDshIotThinking(env: NodeJS.ProcessEnv = process.env): boolean { - let dirs: string[]; - try { - dirs = dshProfileDirs(env); - } catch { - return false; - } - for (const dir of dirs) { - try { - if (fs.existsSync(path.join(dir, "node_modules", "dsh-plugin-iot-thinking", "package.json"))) return true; - } catch { - // unreadable profile: keep scanning the rest - } - } - return false; -} - -/** Installed AND effective-enabled. The plugin's own default is enabled - * (its config-store seeds enabled: true), so a missing/unreadable config - * keeps the warning; only an explicit enabled: false silences it. */ -export function dshIotThinkingActive(env: NodeJS.ProcessEnv = process.env): boolean { - if (!probeDshIotThinking(env)) return false; - try { - const raw = fs.readFileSync(path.join(resolveDshHome(env), "plugin-data", "iot-thinking", "config.json"), "utf8"); - const doc: unknown = JSON.parse(raw); - if (doc !== null && typeof doc === "object" && (doc as { enabled?: unknown }).enabled === false) return false; - } catch { - // absent/broken config ⇒ plugin runs on its default (enabled) - } - return true; -} - /** Currently-visible notices, in registry order. Never throws. */ export function visibleNotices(): Array<{ id: string; tone: "ok" | "warn"; keys: NoticeEntry["keys"] }> { const out: Array<{ id: string; tone: "ok" | "warn"; keys: NoticeEntry["keys"] }> = []; diff --git a/tests/iot-incompat-notice.test.ts b/tests/iot-incompat-notice.test.ts index 45a067be8e..9c67f603cb 100644 --- a/tests/iot-incompat-notice.test.ts +++ b/tests/iot-incompat-notice.test.ts @@ -16,7 +16,8 @@ process.env.DSH_HOME = home; process.env.XDG_STATE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-state-")); process.env.BILI_CONFIG_FILE = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "iot-incompat-cfg-")), "absent.json"); -const { NOTICES, probeDshIotThinking, dshIotThinkingActive } = await import("../src/notices.ts"); +const { NOTICES } = await import("../src/notices.ts"); +const { probeDshIotThinking, dshIotThinkingActive } = await import("../src/dsh-channel.ts"); const { IOT_INCOMPAT_NOTICE_ID, dismissUpgradeNotice } = await import("../src/pck-notice.ts"); const entry = () => {