diff --git a/docs/clients.md b/docs/clients.md index 36e45a899e..b47d76eefe 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -479,32 +479,90 @@ 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 | - -**Concurrent sessions (#3203).** Several `bili codex` launches may run at once in the same project directory with the same `CODEX_HOME`: each launch takes its own per-session overlay slot (`-bili-s`, pool of 16) and its own lane proxy, so routing, MCP conversation binding, and compression state never cross between sessions. With the shared-state default (codex ≥ 0.147.0) both sessions' history lands in the ONE live state db in the real home and survives any exit order — see `BILI_CODEX_STATE_MODE` in configuration.md. Older binaries, or `BILI_CODEX_STATE_MODE=legacy`, keep one exclusive overlay per home: the second concurrent launch is refused with `BILI_OVERLAY_BUSY`. - -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 | + +**Concurrent sessions (#3203).** Several `bili codex` launches may run at once in the same project directory with the same `CODEX_HOME`: each launch takes its own per-session overlay slot (`-bili-s`, pool of 16) and its own lane proxy, so routing, MCP conversation binding, and compression state never cross between sessions. With the shared-state default (codex ≥ 0.147.0) both sessions' history lands in the ONE live state db in the real home and survives any exit order — see `BILI_CODEX_STATE_MODE` in CONFIGURATION.md. Older binaries, or `BILI_CODEX_STATE_MODE=legacy`, keep one exclusive overlay per home: the second concurrent launch is refused with `BILI_OVERLAY_BUSY`. + + +**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 persistent per-user proxy service — a Task +Scheduler logon task on Windows, a systemd user unit on Linux; other platforms +report that the service is unsupported and the manual postures still work. +`bili service status|restart|enable|disable|remove` manage it; failed +registration is 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 diff --git a/docs/clients.zh-CN.md b/docs/clients.zh-CN.md index 6b1fc8c5e9..5bd55258a7 100644 --- a/docs/clients.zh-CN.md +++ b/docs/clients.zh-CN.md @@ -117,18 +117,31 @@ 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 代理(#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`) | +| 方式 | 能力 | +| --- | --- | +| `bili codex`(启动器) | 受管 lane 代理与证书 MITM;工具 + 压缩 | +| `bili plugin install codex` | 原生 Codex 模型路由 + ACP 工具 + SessionStart hook + ACP 技能 | + +**并发会话(#3203)。** 同一项目目录、同一 `CODEX_HOME` 下可以同时跑多个 `bili codex`:每次启动各取一个独立的每会话 overlay 槽位(`-bili-s`,池上限 16)和各自的 lane 代理,路由、MCP 会话绑定、压缩状态互不串线。共享状态默认(codex ≥ 0.147.0)下,两个会话的历史都落在真实 home 的同一个活库上,退出顺序不影响保留 —— 见 CONFIGURATION.md 的 `BILI_CODEX_STATE_MODE`。旧版二进制或 `BILI_CODEX_STATE_MODE=legacy` 保持每 home 一个独占 overlay:第二个并发启动会被 `BILI_OVERLAY_BUSY` 拒绝。 + +**四个面各证各的。** 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 只删自己的条目/文件;技能目录里另有用户文件时目录保留。 -**并发会话(#3203)。** 同一项目目录、同一 `CODEX_HOME` 下可以同时跑多个 `bili codex`:每次启动各取一个独立的每会话 overlay 槽位(`-bili-s`,池上限 16)和各自的 lane 代理,路由、MCP 会话绑定、压缩状态互不串线。共享状态默认(codex ≥ 0.147.0)下,两个会话的历史都落在真实 home 的同一个活库上,退出顺序不影响保留 —— 见 configuration.md 的 `BILI_CODEX_STATE_MODE`。旧版二进制或 `BILI_CODEX_STATE_MODE=legacy` 保持每 home 一个独占 overlay:第二个并发启动会被 `BILI_OVERLAY_BUSY` 拒绝。 +`bili service install` 会注册当前用户级的常驻代理服务——Windows 上是 Task Scheduler 登录任务,Linux 上是 systemd 用户单元;其他平台会明确报告服务不受支持,手动方式仍然可用。可用 `bili service status|restart|enable|disable|remove` 管理;注册失败会明确报告。代理关闭时,Codex 配置的 URL 仍是 loopback,请求会在本地端点失败,不会静默回退到上游直连。`bili doctor` 会报告 `proxy-ready`、`configured`、`verified`、`bypassed` 或 `unknown`;只有观测到真实 Codex 模型请求才会标记 `verified`,健康代理或已写配置本身都不能证明已验证。 +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)。 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/docs/configuration.md b/docs/configuration.md index 45bea523e4..bb1f8a0f9e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -434,6 +434,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). | diff --git a/docs/configuration.zh-CN.md b/docs/configuration.zh-CN.md index c6d3c537c9..fc59f69368 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -434,6 +434,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 上解析)。 | diff --git a/docs/lifecycle.md b/docs/lifecycle.md index 45e75b30a2..0516633ec8 100644 --- a/docs/lifecycle.md +++ b/docs/lifecycle.md @@ -54,6 +54,7 @@ | `BILI_OPENCODE_INLINE` | #3278 opencode 移植(#4687) | opencode inline 模式(需手动开启,默认保持旧行为 spawn,owner 决定不改默认):与 pi 同构——不起 proxy 进程,模型 URL 被 V2 route/intercept 改写成伪 origin 后由进程内引擎接住(bun 宿主已验:引擎 boot/dispatch 全绿);`=1/on/yes/TRUE` 或 file 家 `"opencode": {"inline": true}` 显式开启(显式开启压过 attach 目标);`bili opencode-inline` 一键车道 | 同 pi inline 车道节奏 | opt-in(不设置时 attach/spawn 行为与旧版完全一致) | | `BILI_INLINE_DEBUG` | #4669 | 仅 inline 车道:引擎 stderr 日志腿默认静默(stderr 是 pi 的交互终端,日志会挤掉输入框;默认只写 bili.log),设 1 恢复 stderr 输出用于排查 | 随 inline 车道(#3278)走 | 排查逃生口 | | 测试钩子:`BILI_DSH_RECOVERY_INTERVAL_MS` / `BILI_DSH_RETRY_INTERVAL_MS` / `BILI_MODEL_INFO_RETRY_MS` | #2082 等 | 缩短测试/运维节奏(dsh-native.ts;NODE_TEST_CONTEXT 感知,避免生产误缩) | 永久测试设施,随宿主代码走 | 测试钩子 | +| 测试钩子:`BILI_CODEX_HOOK_ORIGIN` | #3176 | 显式覆盖 codex SessionStart bootstrap hook 的探测目标 origin(默认 = bili 写入 `config.toml` 的路由 origin,其次粘性 lane 端口发现);attach-only、fail-open,探测不健康时静默退出 | 永久测试设施,随 codex hook 代码走 | 测试钩子 | | `BILI_COMPRESS_AT_FOLD_POINT` | #5470 | compress-at-fold-point 实验性 opt-in(**默认关**;2026-11-01 真实模型验证通过,owner 决定保持 opt-in):把重放视图中可见的 compress 调用对挪到它自己的折叠点(布局 [已折叠区]–[调用对]–[保护消息]),弱注意力模型不再把历史尾部的工具交换误读成新命令;纯视图变换,关时布局字节级不变;文件键 `compress.compressAtFoldPoint`;含 env-only opt-in 可达性修复(默认短路保持不变) | 更多真实模型积累后转正为默认开(走评审),或按废弃流程删除 | opt-in(默认关) | | `BILI_COMPRESS_AT_FOLD_POINT_CLEAR_THINKING` | #5470 | 依附上一开关:挪位瞬间清紧邻的未签名思考段(默认 off,A 关时无效);strict-echo(#684) 或存在签名思考块(#1658)时整个机制不出手 | 同上 | opt-in(默认 off) | | `BILI_PF_RENDER_WINDOW` / `BILI_PF_RENDER_AUDIT_EVERY` | #5664 v6 render-snapshot plane | 实验性渲染快照车道可调项(默认 OFF,嵌套于 watermarkV6MsgId cohort):W = 稳态轮回放的冻结核数(默认 8);N = 计划全量审计节奏(默认 8);读点 src/server/fastpath-v6-render.ts:50-60 | render 平面转正(rollout 100% 且审计计数归稳)后移 §2 常设面,或随车道退役删除 | opt-in(默认 OFF;仅由显式 rollout 开启) | diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index c3d3a77b0e..7318468785 100644 --- a/src/cache-ledger.ts +++ b/src/cache-ledger.ts @@ -22,6 +22,7 @@ import { isForeignMembership } from "./request-membership.js"; import { billInputUsage } from "./billing.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 @@ -677,7 +678,7 @@ export function credentialFingerprint(headers: Record | undefine } } } - if (cred === undefined) return undefined; + if (cred === undefined || isProxyManagedCredential(cred)) return undefined; return "sha256:" + createHash("sha256").update(cred, "utf8").digest("hex").slice(0, 12); } diff --git a/src/cli.ts b/src/cli.ts index f41bda689d..6d4ce42d5d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -43,7 +43,7 @@ import { startRemoteNoticesWatcher } from "./remote-notices.js"; import { hydrateNoticeReceipts } from "./notice-store.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 { 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 { runSessionsCommand, runStorageGcCommand } from "./storage-maintenance.js"; @@ -52,6 +52,7 @@ import { listResolvedPacks } from "./compress-settings.js"; import { renderJson, renderText, runDiff } from "./acp-cache-diff.js"; import { fixDshLedgers, renderDoctorReport, renderLedgerFixReport, 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 @@ -134,6 +135,9 @@ Usage: dsh's channel, host-owned copies are pointed at their host's updater — never overwritten bili plugin list show install status + installed (on-disk) version for every host + bili service install|status|restart|enable|disable|remove + manage the per-user logon proxy task (Windows Task + Scheduler / systemd --user) bili mcp run the bili MCP server standalone (stdio) bili plugin-register pre-bind a conversation to the plugin mode (--origin URL, --agent name) @@ -205,7 +209,7 @@ Docs: https://github.com/ranxianglei/billion-context `; type Parsed = { - command: "start" | "update" | "doctor" | "help" | "version" | "launch" | "test" | "export" | "plugin-register" | "mcp" | "plugin" | "acp-cache" | "sessions" | "storage" | "pack"; + command: "start" | "update" | "doctor" | "help" | "version" | "launch" | "test" | "export" | "plugin-register" | "mcp" | "plugin" | "acp-cache" | "service" | "sessions" | "storage" | "pack"; client?: ClientName; clientArgs: string[]; mitmDomains: string[]; @@ -216,6 +220,7 @@ type Parsed = { exportJsonl?: boolean; registerConversationId?: string; pluginAction?: "install" | "remove" | "update" | "list"; + serviceAction?: "install" | "status" | "restart" | "enable" | "disable" | "remove"; pluginAgent?: PluginAgent; pluginWithMcp?: boolean; packAction?: "install" | "remove" | "list"; @@ -253,6 +258,7 @@ export function parseArgs(argv: string[]): Parsed { let exportFull = false; let exportJsonl = false; let pluginAction: Parsed["pluginAction"]; + let serviceAction: Parsed["serviceAction"]; let pluginAgent: Parsed["pluginAgent"]; let pluginWithMcp = false; let packAction: Parsed["packAction"]; @@ -485,6 +491,15 @@ export function parseArgs(argv: string[]): Parsed { } 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]; @@ -600,11 +615,11 @@ export function parseArgs(argv: string[]): Parsed { } } - return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce }; + return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, serviceAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce }; } export async function main(): Promise { - const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce } = parseArgs(process.argv.slice(2)); + const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, serviceAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce } = parseArgs(process.argv.slice(2)); if (command === "help") { process.stdout.write(HELP); return; @@ -652,6 +667,20 @@ export async function main(): Promise { 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 @@ -697,7 +726,11 @@ export async function main(): Promise { } if (pluginAction === "install") { try { - console.log(pluginInstall(pluginAgent!, { withMcp: pluginWithMcp })); + 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); @@ -707,7 +740,10 @@ export async function main(): Promise { if (pluginAction === "remove") { try { // #2155: best-effort note about still-open client windows. - const removed = pluginRemove(pluginAgent!); + const removed = + pluginAgent === "codex" + ? await codexRemoveWithService() + : pluginRemove(pluginAgent!); const warn = await warnActivePluginSessions(pluginAgent!); console.log(warn === "" ? removed : removed + "\n" + warn); } catch (error) { diff --git a/src/codex-integration/cc-switch.ts b/src/codex-integration/cc-switch.ts new file mode 100644 index 0000000000..be22c2ea74 --- /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"; + +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..919545aaa9 --- /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..9ae5942158 --- /dev/null +++ b/src/codex-integration/hooks.ts @@ -0,0 +1,332 @@ +// 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. */ +const CODEX_HOOKS_TABLE = "hooks.SessionStart"; + +/** `[features] hooks = true` — the master switch for the hook system. */ +const FEATURES_TABLE = "features"; +const FEATURES_KEY = "hooks"; + +/** 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; +} + +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..09e7079b3b --- /dev/null +++ b/src/codex-integration/route.ts @@ -0,0 +1,400 @@ +// 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. */ +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. */ +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?:\/\/.+)$/; + +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. */ +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. */ +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. */ +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 }; + +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; +} + +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. */ +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))); +} + +/** 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..dcaf0b4498 --- /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`. */ +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. */ +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, ""); +} + +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"; +} + +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..9cd428afc0 --- /dev/null +++ b/src/codex-integration/status.ts @@ -0,0 +1,210 @@ +import { resolveCodexHome } from "../client-config.js"; +import { lanePreferredPort } from "../instance.js"; +import { + codexRouteRecordPath, + readCodexRoute, + readCodexRouteRecord, +} from "./route.js"; +import fs from "node:fs"; +import path from "node:path"; + +type CodexIntegrationState = + | "proxy-ready" + | "configured" + | "verified" + | "bypassed" + | "unknown"; + +export interface CodexIntegrationReport { + state: CodexIntegrationState; + route: "owned" | "foreign" | "absent"; + proxyHealthy: boolean; + observedCodexRequest: boolean; + detail: string; +} + +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..0f37e4d7fe --- /dev/null +++ b/src/codex-integration/toml-field.ts @@ -0,0 +1,279 @@ +// 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")`. */ +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*(?:#.*)?$/; + +/** 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 { + 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. */ +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 = parseTableHeader(line); + if (header !== undefined) { + if (active) return undefined; + active = header.kind === "table" && header.name === 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 = parseTableHeader(lines[i]!); + if (header === undefined) continue; + if (tableLine >= 0) { + tableEnd = i; + break; + } + if (header.kind === "table" && header.name === 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 = parseTableHeader(lines[i]!); + if (header === undefined) continue; + if (tableLine >= 0) { + tableEnd = i; + break; + } + if (header.kind === "table" && header.name === 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"); +} + +/** 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..5429fe35bd --- /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/doctor.ts b/src/doctor.ts index c23cae3c9e..41c48ced2a 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -13,6 +13,9 @@ import { PLUGIN_AGENTS, UPDATE_CHANNEL, claudeDesktopPresent, inspectLanePresenc 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 { dshProfileDirs } from "./dsh-channel.js"; import { convergeDshLedger, dshProfileLedgerFindings, readDshLedgerState, type LedgerChangeDetail, type LedgerFinding } from "./dsh-ledger.js"; @@ -77,6 +80,9 @@ export interface DoctorReport { global: DoctorGlobalInfo; lanes: DoctorLane[]; processes: DoctorProcess[]; + codexIntegration: CodexIntegrationReport; + ccSwitch: CcSwitchDetection; + chatGptDesktop: ChatGptDesktopCapability; /** #3496: set only when `--fix` ran — what the repair pass changed per profile. */ ledgerFixes?: DshLedgerFixRow[]; } @@ -210,7 +216,9 @@ export async function runDoctor(opts: DoctorOpts): Promise { }; }); - 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 }; } /** #3496: the explicit repair pass behind `bili doctor --fix`. Converges every @@ -351,6 +359,25 @@ export function renderDoctorReport(report: DoctorReport): string { 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"); 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/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..2b46a9735d 100644 --- a/src/notices.ts +++ b/src/notices.ts @@ -5,8 +5,9 @@ // action words) come from the web layer; activity predicates live HERE so the // server-side judgment never scatters back into route handlers. import { effectivePromptCacheRouting, loadConfigFile } from "./config.js"; +import { dshIotThinkingActive } 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,6 +37,23 @@ 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 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) && + dshIotThinkingActive(process.env), + }, ]; /** Currently-visible notices, in registry order. Never throws. */ 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/plugin-install.ts b/src/plugin-install.ts index 46e3ac3978..b898d57739 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -6,7 +6,14 @@ // 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] +// 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. // 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 @@ -34,18 +41,23 @@ 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 { fileURLToPath } from "node:url"; import { applyEdits, modify as jsoncModify, parse as jsoncParse, type ParseError } from "jsonc-parser"; -import { resolveDshHome, resolveHermesHome, resolveKimiHome, resolvePiHome, readClaudeSettings } from "./client-config.js"; +import { parseCodexToml, readClaudeSettings, resolveDshHome, resolveHermesHome, resolveKimiHome, resolvePiHome } from "./client-config.js"; import { stripBiliWrappers, vertexBaseUrlForLocation } from "./vertex.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 { 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 @@ -1127,10 +1139,159 @@ 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 + * 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; +} + +/** 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 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 @@ -1141,43 +1302,83 @@ function codexInstall(): string { 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]`; + 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 { + 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 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(text); + const m = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(stripped); 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 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 : text.length; - const cleaned = (text.slice(0, lineStart).replace(/\n+$/, "\n") + text.slice(end)).replace(/^\n+/, ""); + 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); - return `codex: removed from ${file}`; + 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 ———————————————————————————————————————————————————————————— @@ -1736,7 +1937,12 @@ function readKimiInstalledRegistry(file: string): { version: number; plugins: Ki if ((err as { code?: string }).code === "ENOENT") return { version: 1, plugins: [] }; throw err; } - const parsed = JSON.parse(text) as { version?: unknown; plugins?: unknown }; + 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[] }; } @@ -2293,13 +2499,27 @@ export function inspectLanePresence(agent: PluginAgent): LanePresence { } const targets = args.filter((a) => path.isAbsolute(a) && /\.js$/.test(a)); const first = targets[0]; - return { + 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(); diff --git a/src/proxy-service/service.ts b/src/proxy-service/service.ts new file mode 100644 index 0000000000..ec790a9cb9 --- /dev/null +++ b/src/proxy-service/service.ts @@ -0,0 +1,1104 @@ +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"; + +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; +} + +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; +} + +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"; +} + +/** 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 { + 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 platform = config.platform ?? process.platform; + 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, + runner: config.runner ?? spawnRunner(platform), + 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; + +/** 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); + if ( + existing !== undefined && + 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: 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); +} + +/** 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 describeFailure("reload systemd user manager", reload); + } + const enable = await invoke( + c.runner, + planSystemdEnableNow({ unitName: c.taskName }), + ); + if (enable.exitCode !== 0) { + restoreUnit(c.unitPath, priorText); + await invoke(c.runner, planDaemonReload()); + return describeFailure("enable systemd user unit", enable); + } + 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 describeFailure("disable systemd user unit", disable); + const stop = await invoke( + c.runner, + planSystemdStop({ unitName: c.taskName }), + ); + if (stop.exitCode !== 0 && !systemdUnitMissing(stop)) + return describeFailure("stop systemd user unit", stop); + 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 describeFailure("disable systemd user unit", result); + 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 describeFailure("stop systemd user unit", stop); + 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 describeFailure("enable systemd user unit", result); + 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 describeFailure("stop systemd user unit", stop); + const start = await invoke( + c.runner, + planSystemdStart({ unitName: c.taskName }), + ); + if (start.exitCode !== 0) + return describeFailure("start systemd user unit", start); + 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..b6761c5eba --- /dev/null +++ b/src/proxy-service/systemd.ts @@ -0,0 +1,212 @@ +// #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"; + +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"); +} + +interface SystemdCommand { + file: string; + args: string[]; +} + +interface SystemdQueryOptions { + unitName?: string; + unitPath?: string; +} + +function unitNameOf(options: SystemdQueryOptions): string { + return options.unitName ?? BILI_SYSTEMD_UNIT; +} + +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 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..d42c62adc6 --- /dev/null +++ b/src/proxy-service/task-scheduler.ts @@ -0,0 +1,210 @@ +import path from "node:path"; + +export const BILI_TASK_NAME = "Billion Context Proxy"; + +export interface TaskCommand { + file: string; + args: string[]; +} + +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; +} + +/** 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 ( + !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 ?? "", + }; +} + +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/src/server/admin.ts b/src/server/admin.ts index 0f174b5922..51c33d7a31 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -1,4 +1,4 @@ -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"; @@ -21,6 +21,7 @@ import { getUpdateVisibility, updateBannerPayload } from "../update-notes.js"; import { installVersionAction, triggerManualCheck, updateActionsAvailable, updateStateSnapshot } from "./update-actions.js"; import { getUnrecognizedPathStats } from "./observability.js"; import { getStore } from "../persist.js"; +import { isCodexClient } from "../codex-compact.js"; import { BodyTooLargeError, headerValue, readBody } from "../server.js"; import { dismissHostPlugin, visibleHostPluginNotices } from "../host-plugin-notice.js"; import { dismissUpgradeNotice } from "../pck-notice.js"; @@ -1198,6 +1199,9 @@ function sendStats(res: http.ServerResponse): void { 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, 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") { diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 95ad37ed4d..1dc3aaffc0 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); 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.", "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/codex-cc-switch.test.ts b/tests/codex-cc-switch.test.ts new file mode 100644 index 0000000000..39aef7be55 --- /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..b48859d15a --- /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..c0b26b75dc --- /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..71f9dfc169 --- /dev/null +++ b/tests/codex-install-faces.test.ts @@ -0,0 +1,151 @@ +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" + ); + // `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 }, () => { + 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 }); + 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 }); + } +}); + +// 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..11e58e0246 --- /dev/null +++ b/tests/codex-integration-status.test.ts @@ -0,0 +1,229 @@ +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 () => { + // 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({ + 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({ + 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({ + 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; +}) { + 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..1121f6b87c --- /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/doctor.test.ts b/tests/doctor.test.ts index 65c2cc860b..5761c2242d 100644 --- a/tests/doctor.test.ts +++ b/tests/doctor.test.ts @@ -4,19 +4,41 @@ 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 { +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) { + if ( + process.platform === "win32" && + effective.HOME !== undefined && + effective.USERPROFILE === undefined + ) { effective.USERPROFILE = effective.HOME; } const saved: Record = {}; @@ -35,10 +57,13 @@ function withEnv(vars: Record, fn: () => void | Prom return r instanceof Promise ? r.finally(restore) : (restore(), undefined); } -function mockFetch(handler: (url: string) => Response | Promise): (fn: () => Promise) => Promise { +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; + globalThis.fetch = ((url: unknown) => + Promise.resolve(handler(String(url)))) as unknown as typeof fetch; return fn().finally(() => { globalThis.fetch = original; }); @@ -46,72 +71,256 @@ function mockFetch(handler: (url: string) => Response | Promise): (fn: } 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"); + 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: 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({ + 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)"] }, + { + 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/); + 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" } })); + 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; + 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]]; + 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"); + 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}`); + 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)}`); + 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.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 { @@ -119,33 +328,111 @@ test("#2891: runDoctor wires the shadow warning onto the divergent dsh profile l } }); -function syntheticReport(overrides?: { lanes?: DoctorLane[]; processes?: DoctorProcess[] }): DoctorReport { +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" }, + 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({ + 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" }, + { + 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 }, + { + 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\)/); + 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", () => { @@ -158,14 +445,27 @@ test("inspectLanePresence omp: dead entry is a broken lane, live entry resolves 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(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"); + 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 }, () => { @@ -188,9 +488,24 @@ test("inspectLanePresence dsh: local pin flags a frozen dev lane, registry pin r 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" })); + 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); @@ -198,11 +513,29 @@ test("inspectLanePresence dsh: local pin flags a frozen dev lane, registry pin r 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"); + 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"); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: main?.copyVersion, + registryVersion: "999.0.0", + }), + "stale", + ); }); } finally { rmrf(base); @@ -213,23 +546,56 @@ test("#2850: inspectLanePresence pi: npm lane resolves the real copy root for ev 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"); + 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(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"); + 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" })); + 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"]) { + 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`); + 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. @@ -256,8 +622,14 @@ test("#2850: inspectLanePresence pi: absolute-path entry keeps local-path semant 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] })); + 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); @@ -280,30 +652,61 @@ test("#2850: runDoctor pi npm lane verdicts off the real copy and drops the fals 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" } }); + 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" }); + 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}`); - }); + 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" }); + 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/); - }); + assert.match( + pi?.detail ?? "", + /pi materializes the npm copy on next startup/, + ); + }, + ); }); } finally { rmrf(base); @@ -318,15 +721,30 @@ test("inspectLanePresence hermes: baked plugin.yaml version is the freshness sig 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" })); + 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"); + assert.equal( + laneVerdict({ + installed: true, + targetMissing: false, + frozen: false, + copyVersion: p.copyVersion, + registryVersion: "999.0.0", + }), + "stale", + ); }); } finally { rmrf(base); @@ -361,10 +779,17 @@ test("runDoctor: corrupt lane config surfaces as a broken probe row, not absent" 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" } })); + 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({ + await withEnv( + { HOME: path.join(base, "home"), XDG_CONFIG_HOME: path.join(base, "xdg-config"), XDG_DATA_HOME: path.join(base, "xdg-data"), @@ -378,16 +803,25 @@ test("runDoctor: corrupt lane config surfaces as a broken probe row, not absent" CODEX_HOME: undefined, CLAUDE_CONFIG_DIR: undefined, OPENCODE_CONFIG: ocCfg, - }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); + }, + 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.equal( + l.verdict, + "absent", + `${l.agent} should be absent in an empty sandbox`, + ); } assert.match(renderDoctorReport(report), /probe failed/); - }); + }, + ); }); } finally { rmrf(base); @@ -398,52 +832,96 @@ test("#2199: opencode npm lane surfaces the cache copy path + disk version and g 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"); + 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" } }); + 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({ + 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, + 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 () => { + }, + 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 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.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\)/); - }); + 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({ + 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, + 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" }); + }, + 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); @@ -451,12 +929,29 @@ test("#2199: opencode npm lane surfaces the cache copy path + disk version and g }); test("renderDoctorReport: lane warnings render under the lane row without touching the verdict", () => { - const text = renderDoctorReport(syntheticReport({ + 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" }, + { + 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/); }); @@ -465,49 +960,111 @@ test("#2290: claude lane surfaces the last hook-detected routing bypass from the 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" } })); + 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"] })); + 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({ + 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, + 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" }); + }, + 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.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({ + 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, + 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" }); + }, + 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)}`); - }); + assert.ok( + !cl?.warnings?.some((w) => w.includes("routing bypass")), + `corrupt marker must not surface: ${JSON.stringify(cl?.warnings)}`, + ); + }, + ); }); } finally { rmrf(base); @@ -519,11 +1076,15 @@ test("runDoctor: full report against a mocked registry, sandboxed homes", async 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" } }); + 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({ + await withEnv( + { HOME: path.join(base, "home"), XDG_CONFIG_HOME: path.join(base, "xdg-config"), XDG_DATA_HOME: path.join(base, "xdg-data"), @@ -537,14 +1098,30 @@ test("runDoctor: full report against a mocked registry, sandboxed homes", async 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(", ")}`); + }, + 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()); + 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.installed, + false, + `${lane.agent} should be absent in an empty sandbox`, + ); assert.equal(lane.verdict, "absent"); assert.equal(lane.registryVersion, "999.0.0"); } @@ -554,10 +1131,13 @@ test("runDoctor: full report against a mocked registry, sandboxed homes", async } else { assert.ok(["ok", "stale"].includes(report.global.verdict)); } - const parsed = JSON.parse(JSON.stringify(report, null, 2)) as DoctorReport; + 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); @@ -569,7 +1149,8 @@ test("runDoctor: unreachable registry never produces a false-stale verdict", asy const runWithFetch = mockFetch(() => Promise.reject(new Error("ENOTFOUND"))); try { await runWithFetch(async () => { - await withEnv({ + await withEnv( + { HOME: path.join(base, "home"), XDG_CONFIG_HOME: path.join(base, "xdg-config"), XDG_DATA_HOME: path.join(base, "xdg-data"), @@ -583,22 +1164,40 @@ test("runDoctor: unreachable registry never produces a false-stale verdict", asy CODEX_HOME: undefined, CLAUDE_CONFIG_DIR: undefined, OPENCODE_CONFIG: undefined, - }, async () => { - const report = await runDoctor({ packageName: "billion-context", runningVersion: "0.1.143" }); + }, + 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"; @@ -610,28 +1209,54 @@ function doctorSandboxEnv(base: string): Record { 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, + 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 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" } }), + : 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 }); + 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"); + 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.match( + text, + /advisory {6}⚠️ \[bc-2026-001\] .*corrupts tool-call arguments/, + ); assert.ok(text.includes("npm install -g billion-context@99.0.0")); }); }); @@ -646,24 +1271,38 @@ test("#1577: bili doctor reports a clean advisory state as 'none' and a failed s 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" } }), + : 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 }); + 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/); + 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 }); + 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/); + assert.match( + renderDoctorReport(report), + /advisory {6}check failed .*— status unknown/, + ); }); }); } finally { diff --git a/tests/iot-incompat-notice.test.ts b/tests/iot-incompat-notice.test.ts new file mode 100644 index 0000000000..9c67f603cb --- /dev/null +++ b/tests/iot-incompat-notice.test.ts @@ -0,0 +1,70 @@ +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, 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-")); +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 } = 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 = () => { + const found = NOTICES.find((n) => n.id === IOT_INCOMPAT_NOTICE_ID); + 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("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.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); +}); + +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/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 () => { 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(); diff --git a/tests/proxy-service.test.ts b/tests/proxy-service.test.ts new file mode 100644 index 0000000000..cb3869c526 --- /dev/null +++ b/tests/proxy-service.test.ts @@ -0,0 +1,692 @@ +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, + planTaskRegisterXml, + planTaskRun, + renderTaskLauncherVbs, + renderTaskXml, + type TaskCommand, + type TaskRunner, + type TaskRunnerResult, +} from "../src/proxy-service/task-scheduler.ts"; +import { + disableProxyService, + enableProxyService, + installProxyService, + proxyServiceStatus, + removeProxyService, + restartProxyService, +} from "../src/proxy-service/service.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 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.ok(vbs.includes('"C:\\Program Files\\nodejs\\node.exe"')); + assert.ok( + vbs.includes( + '"C:\\Users\\Alice Example\\AppData\\Roaming\\npm\\node_modules\\billion-context\\dist\\index.js"', + ), + ); + assert.ok(vbs.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( + () => + renderTaskLauncherVbs({ + taskName: BILI_TASK_NAME, + nodePath: "node.exe", + entryPath: "C:\\bili.js", + port: 8787, + host: "127.0.0.1", + }), + /absolute/, + ); + assert.throws( + () => + renderTaskLauncherVbs({ + taskName: BILI_TASK_NAME, + nodePath: "C:\\node.exe", + entryPath: "C:\\bili.js", + port: 65536, + host: "127.0.0.1", + }), + /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 }); + } +}); diff --git a/tsup.config.ts b/tsup.config.ts index 0d806a1677..3c3cca9ff5 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -4,7 +4,7 @@ import { defineConfig } from "tsup"; export default [ defineConfig({ - entry: ["src/index.ts", "src/mcp.ts", "src/claude-mcp-entry.ts", "src/claude-native-bootstrap.ts", "src/claude-subagent-hook.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/agent/dsh-compaction-gate.ts", "src/kimi/native-mcp.ts", "src/kimi/bootstrap-hook.ts", "src/zcode/mcp-entry.ts", "src/zcode/bootstrap-hook.ts"], + entry: ["src/index.ts", "src/mcp.ts", "src/claude-mcp-entry.ts", "src/claude-native-bootstrap.ts", "src/claude-subagent-hook.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/agent/dsh-compaction-gate.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", diff --git a/website/config-reference/env-only.yaml b/website/config-reference/env-only.yaml index bcf15edb15..8c00aeceeb 100644 --- a/website/config-reference/env-only.yaml +++ b/website/config-reference/env-only.yaml @@ -458,6 +458,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"