diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 986036e0f5..9bf97b4672 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -513,10 +513,10 @@ Top-level keys that control how the proxy listens and behaves globally. ```jsonc { - "resign": { - "sdk-hmac-sha256": { "passthrough": true }, - "aws4-hmac-sha256": { "passthrough": true } // inert until bili ships its re-signer (#2090) — named once at config load - } + "resign": { + "sdk-hmac-sha256": { "passthrough": true }, + "aws4-hmac-sha256": { "passthrough": true } // inert until bili ships its re-signer (#2090) — named once at config load + } } ``` diff --git a/src/client-config.ts b/src/client-config.ts index db8e9bb2d3..bd7f4381a5 100644 --- a/src/client-config.ts +++ b/src/client-config.ts @@ -818,15 +818,66 @@ export function mergeCodexViews(base: CodexConfig, overlay: CodexConfig): CodexC return out; } +// #2260(E): one TOML key part — bare ([A-Za-z0-9_-]+), basic string with +// escapes ("my key", "ключ"), or literal string ('a-b'). The pre-fix regex +// only accepted \w runs inside quotes, so VALID quoted keys with spaces or +// non-ASCII false-positived as broken and bili refused the whole launch +// (exit 2) where codex itself parses the profile fine. +const TOML_KEY_PART_RE = new RegExp(String.raw`^(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*')(?:\.(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*'))*$`); + +/** One pass over a TOML line outside a multi-line string: net + * array/inline-table bracket delta plus the key-side text (everything up to + * the first `=` at depth 0, trimmed; the whole line when there is no `=`). + * Quote-aware (basic-string escapes, literal strings) and comment-aware + * (`#` outside strings ends the active line) so brackets in values, strings + * or comments never skew the depth count. */ +function scanTomlLine(line: string): { delta: number; key: string } { + let delta = 0; + let dq = false; + let sq = false; + let escaped = false; + let pastEq = false; + let key = ""; + for (const ch of line) { + if (escaped) { + escaped = false; + if (!pastEq) key += ch; + continue; + } + if (dq) { + if (ch === "\\") escaped = true; + else if (ch === "\"") dq = false; + if (!pastEq) key += ch; + continue; + } + if (sq) { + if (ch === "'") sq = false; + if (!pastEq) key += ch; + continue; + } + if (ch === "#") break; + if (ch === "\"") { dq = true; if (!pastEq) key += ch; continue; } + if (ch === "'") { sq = true; if (!pastEq) key += ch; continue; } + if (ch === "=" && !pastEq) { pastEq = true; continue; } + if (ch === "[" || ch === "{") delta += 1; + else if (ch === "]" || ch === "}") delta -= 1; + if (!pastEq) key += ch; + } + return { delta, key: key.trim() }; +} + /** Structural sanity check for a codex TOML file (base or profile): every * non-blank non-comment line must be a table header, an array-of-tables - * header, or `key = …`. Multi-line strings ("""…""" / '''…''') are tracked so - * their bodies do not false-positive. Returns a human-readable problem or - * null. Deliberately NOT a full TOML parser — it only distinguishes - * "structurally broken" (where codex itself hard-fails, verified 0.147) from - * "valid TOML without fields bili reads" (which must pass silently). */ + * header, or `key = …` with a TOML-legal key side. Multi-line strings + * ("""…""" / '''…''') and bracket-opened values (arrays / inline tables + * spanning lines) are tracked so their bodies do not false-positive. Returns + * a human-readable problem or null. Deliberately NOT a full TOML parser — it + * only distinguishes "structurally broken" (where codex itself hard-fails, + * verified 0.147) from "valid TOML without fields bili reads" (which must + * pass silently). */ export function codexTomlProblem(text: string): string | null { let multiline: string | null = null; + let depth = 0; const lines = text.split(/\r?\n/); for (let i = 0; i < lines.length; i += 1) { const line = lines[i]!.trim(); @@ -843,10 +894,21 @@ export function codexTomlProblem(text: string): string | null { if (count % 2 === 1) { opened = d; break; } } if (opened) { multiline = opened; continue; } + const scan = scanTomlLine(line); + if (depth > 0) { + // Inside an array/inline table opened on an earlier line: the body + // is value context, not key context. + depth += scan.delta; + continue; + } if (/^\[[^\[\]]+\]$/.test(line) || /^\[\[[^\[\]]+\]\]$/.test(line)) continue; - if (/^[\w"'][\w."'-]*(\.[\w"'][\w."'-]*)*\s*=/.test(line)) continue; + if (TOML_KEY_PART_RE.test(scan.key)) { + depth = Math.max(0, scan.delta); + continue; + } return `line ${i + 1}: unrecognized structure (${line.slice(0, 60)})`; } + if (depth > 0) return `line ${lines.length}: array/inline table opened above is never closed`; return null; } diff --git a/src/launcher.ts b/src/launcher.ts index 0db8f50b41..582e16ab3a 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -963,14 +963,23 @@ export function buildCodexArgs( // bypasses the proxy. The TARGET itself is already chosen from the merged // effective view (profile + CLI overrides), so appending never hides a // user-selected endpoint behind a stale one. - const args = [...extra]; + // #2260(D): "after the user's argv" means after the user's FLAGS, not + // after their positionals — everything past a `--` is positional to + // codex's parser, so appending there turns the rewrites into prompt text + // and the traffic bypasses the proxy. Insert before the first `--` when + // one exists; all user flag tokens still precede the rewrites, keeping + // last-wins intact. + const rewrites: string[] = []; for (const r of httpRewrites) { - args.push("-c", `${r.key}=${wrapUpstream(origin, r.realUpstream)}`); + rewrites.push("-c", `${r.key}=${wrapUpstream(origin, r.realUpstream)}`); } for (const r of httpsRewrites) { - args.push("-c", `${r.key}=${r.realUpstream}`); + rewrites.push("-c", `${r.key}=${r.realUpstream}`); } - return args; + if (rewrites.length === 0) return [...extra]; + const sep = extra.indexOf("--"); + if (sep === -1) return [...extra, ...rewrites]; + return [...extra.slice(0, sep), ...rewrites, ...extra.slice(sep)]; } /** @@ -4043,12 +4052,45 @@ export async function ensureProxyRunning( : childExit.signal ? `signal ${childExit.signal}` : "unknown reason"; throw new Error(`bili: proxy child exited before becoming healthy (${detail}) (log: ${logPath})`); } + // #2260(A)/#2187: the timeout is the ONE terminal path where the + // spawned child is STILL ALIVE. Abandoning it leaked a detached proxy + // per failed bring-up — dsh plan-time retries re-arm every 10s, so a + // persistently slow host accumulated ~1 zombie per ~70s (each also + // stranding the lane sticky-port ladder). Hard-kill before failing. + killAbandonedChild(child); + console.error( + `bili: killed spawned proxy (pid ${child.pid ?? "?"}) after ${SPAWN_BUDGET_MS}ms without health — it never became ready and would otherwise outlive this failure (log: ${logPath})`, + ); throw new Error(`bili: proxy did not become healthy within ${SPAWN_BUDGET_MS}ms (log: ${logPath})`); } finally { if (claimed) clearStartingMarker(launchToken); } } +/** #2260(A)/#2187: unconditional hard-kill of a spawned-but-abandoned proxy + * child, all platforms. Deliberately NOT stopProxy(): its win32 path returns + * without killing because the #414 design assumes THIS process exits ≤2s + * later, letting the child's BILI_PARENT_PID watch run the graceful path — + * an assumption that does not hold when the spawner keeps living (plugin + * lane: long-lived desktop host), where the abandoned child would leak + * forever. The victim never became healthy, so it served no traffic and + * holds no sessions; SIGKILL loses nothing and reaches even a hung event + * loop (SIGTERM would wait for a stuck loop to drain). Stale instance + * records left behind are inert by the dead-pid checks in discovery. */ +function killAbandonedChild(child: SpawnChild | undefined): void { + if (!child || child.pid === undefined || child.pid <= 0) return; + if (process.platform !== "win32") { + try { + process.kill(-child.pid, "SIGKILL"); + } catch { + /* group already gone */ + } + } + try { + child.kill?.("SIGKILL"); + } catch {} +} + export function stopProxy(handle: ProxyHandle): void { if (handle.attached) return; const child = handle.child; @@ -4344,7 +4386,7 @@ export function resolveClientCommand( const resolved = resolveOnPath("mcode", env); if (resolved) return { command: resolved, prefixArgs: [] }; const binBase = path.join(resolveMcodeInstallDir(env), "bin", "mcode"); - for (const ext of process.platform === "win32" ? [".cmd", ".bat", ".exe", ""] : [""]) { + for (const ext of platform === "win32" ? [".cmd", ".bat", ".exe", ""] : [""]) { const candidate = binBase + ext; try { if (fs.existsSync(candidate)) return { command: candidate, prefixArgs: [] }; @@ -4360,10 +4402,10 @@ export function resolveClientCommand( // %LOCALAPPDATA%\agy\bin\agy.exe). const resolved = resolveOnPath("agy", env); if (resolved) return { command: resolved, prefixArgs: [] }; - const base = process.platform === "win32" + const base = platform === "win32" ? path.join(env.LOCALAPPDATA ?? path.join(os.homedir(), "AppData", "Local"), "agy", "bin", "agy") : path.join(os.homedir(), ".local", "bin", "agy"); - for (const ext of process.platform === "win32" ? [".exe", ""] : [""]) { + for (const ext of platform === "win32" ? [".exe", ""] : [""]) { const candidate = base + ext; try { if (fs.existsSync(candidate)) return { command: candidate, prefixArgs: [] }; diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 1749d37d18..58488dceda 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -1860,6 +1860,38 @@ function rootFromDistFile(file: string): string { return path.dirname(path.dirname(path.dirname(file))); } +// #2260(F): cache spec slots are `billion-context@`; for registry +// installs is a dotted version, which lexicographic sort mis-orders +// ("0.1.9" > "0.1.186" because '9' > '1'). Compare all-numeric specs per +// segment; anything non-numeric ("latest", file: specs) falls back to plain +// string order — same relative position as before. +function compareSpecSlots(a: string, b: string): number { + const SPEC_PREFIX = "billion-context@"; + const av = a.startsWith(SPEC_PREFIX) ? a.slice(SPEC_PREFIX.length) : a; + const bv = b.startsWith(SPEC_PREFIX) ? b.slice(SPEC_PREFIX.length) : b; + const segments = (s: string): number[] | null => { + const parts = s.split("."); + if (parts.length === 0) return null; + const out: number[] = []; + for (const p of parts) { + if (!/^\d+$/.test(p)) return null; + out.push(Number(p)); + } + return out; + }; + const an = segments(av); + const bn = segments(bv); + if (an !== null && bn !== null) { + const len = Math.max(an.length, bn.length); + for (let i = 0; i < len; i++) { + const d = (an[i] ?? 0) - (bn[i] ?? 0); + if (d !== 0) return d; + } + return 0; + } + return av.localeCompare(bv); +} + /** #1234/#2199: on-disk root of the OpenCode v2 cache copy of billion-context — * $XDG_CACHE_HOME/opencode/npm/billion-context@//node_modules/billion- * context (newest spec slot, newest timestamp wins). Read-only; undefined when @@ -1877,7 +1909,7 @@ export function opencodeCacheCopyRoot(env: NodeJS.ProcessEnv = process.env): str } catch { return undefined; } - for (const slot of slots.filter((s) => s.startsWith("billion-context@")).sort().reverse()) { + for (const slot of slots.filter((s) => s.startsWith("billion-context@")).sort(compareSpecSlots).reverse()) { let stamps: string[]; try { stamps = fs.readdirSync(path.join(npm, slot)); diff --git a/src/web/sessions-data.ts b/src/web/sessions-data.ts index 4b21d7f958..8a3458c9c5 100644 --- a/src/web/sessions-data.ts +++ b/src/web/sessions-data.ts @@ -8,7 +8,7 @@ import { buildSessionCacheReport } from "../cache-ledger.js"; import { markdownToHtml } from "./markdown.js"; import { log } from "../logger.js"; import { dataDir } from "../paths.js"; -import { statSync } from "node:fs"; +import { readdirSync, statSync } from "node:fs"; import { readdir, stat } from "node:fs/promises"; import * as path from "node:path"; @@ -271,21 +271,30 @@ function liveCoveredPaths(dir: string): Set { return out; } -/** #2180: a top-level ENOENT means "pristine" — a fresh install where the data - * root was never created, so no session file can exist anywhere — only when - * the DEFAULT layout is in effect: BILI_SESSIONS_DIR unset AND the XDG data - * root itself absent. An explicit override pointing nowhere, or a data root - * that exists without its sessions subdir, stays loud (#1937): silence there - * would hide a moved/misconfigured path while real sessions sit elsewhere. */ +// #2260(F)/#2180 follow-up: bili's own infra dirs created under the data root +// BEFORE any session exists (ensureRootCA() makes /ca at proxy start) — +// their presence alone must not read as "misconfigured". The set is closed by +// construction: paths.ts writes only `sessions` and `ca` directly under it. +const DATA_DIR_INFRA_ENTRIES = new Set(["ca"]); + +/** #2180: a top-level ENOENT means "pristine" — no session file can exist + * anywhere — only when the DEFAULT layout is in effect: BILI_SESSIONS_DIR + * unset AND the XDG data root either absent or holding ONLY bili's own infra + * dirs (a fresh install where ensureRootCA() already ran). An explicit + * override pointing nowhere, or a data root containing anything else, stays + * loud (#1937): silence there would hide a moved/misconfigured path while + * real sessions sit elsewhere. */ function isPristineSessionsRoot(error: unknown): boolean { if ((error as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") return false; if (process.env.BILI_SESSIONS_DIR) return false; + let entries: string[]; try { statSync(dataDir()); - return false; + entries = readdirSync(dataDir()); } catch (e) { return (e as NodeJS.ErrnoException).code === "ENOENT"; } + return entries.every((entry) => DATA_DIR_INFRA_ENTRIES.has(entry)); } /** Single-flight index refresh. Steady-state cost is one stat per file; only diff --git a/tests/codex-profile-effective.test.ts b/tests/codex-profile-effective.test.ts index d83a8d243e..f14fc27756 100644 --- a/tests/codex-profile-effective.test.ts +++ b/tests/codex-profile-effective.test.ts @@ -123,6 +123,18 @@ test("codexTomlProblem: valid structures pass silently", () => { 'instructions = """\nnot a key line at all\n"""\nmodel = "y"\n', "instructions = '''\nstill fine [unclosed\n'''\n", '"dotted.key" = 1\n[a.b]\nc = 2\n', + // #2260(E): quoted keys with spaces / non-ASCII are VALID TOML — the + // pre-fix regex false-fataled these and bili refused the launch. + '"my key" = 1\n', + '"ключ" = 2\n', + "'lit-eral' = 3\n", + 'a."b c".d = 4\n', + '"esc\\"aped" = 5\n', + // bracket-opened values spanning lines are value context, not key lines + "arr = [\n \"a\",\n \"b\",\n]\nmodel = \"y\"\n", + "t = {\n a = 1,\n}\nmodel = \"y\"\n", + // brackets inside values / strings / comments must not skew the depth + "s = \"a]b[c\" # note ]\nmodel = \"y\"\n", ]; for (const t of ok) assert.equal(codexTomlProblem(t), null, JSON.stringify(t)); }); @@ -133,6 +145,9 @@ test("codexTomlProblem: structural breakage is reported with its line", () => { assert.ok(typeof p === "string" && p.startsWith("line 2:"), String(p)); const garbage = "model = \"x\"\nthis is not toml\n"; assert.ok(codexTomlProblem(garbage)?.startsWith("line 2:")); + // #2260(E): unbalanced brackets are structurally broken (codex hard-fails) + assert.match(String(codexTomlProblem("arr = [\n \"a\"\n")), /never closed/); + assert.ok(codexTomlProblem("model = \"x\"\n]\n")?.startsWith("line 2:")); }); function writeHome(files: Record): string { diff --git a/tests/issue2187-dsh-spawn-retry.test.ts b/tests/issue2187-dsh-spawn-retry.test.ts index 5808287129..e93b29c979 100644 --- a/tests/issue2187-dsh-spawn-retry.test.ts +++ b/tests/issue2187-dsh-spawn-retry.test.ts @@ -75,8 +75,19 @@ function mockCtx() { }; } +// #2260(F): ambient proxy env must never leak into this suite — a BILI_PROVIDER_REWRITES +// inherited from the runner's shell flips planNativeDsh to "off" (src/agent/dsh-native.ts), +// so the spawn would be skipped and the timeouts below would test nothing. +const SEALED_PROXY_ENV = ["BILI_PROVIDER_REWRITES", "BILI_MITM_HOSTS", "NODE_EXTRA_CA_CERTS"]; + async function withEnv(env: Record, fn: () => Promise | T): Promise { const saved: Record = {}; + for (const k of SEALED_PROXY_ENV) { + if (!(k in env)) { + saved[k] = process.env[k]; + delete process.env[k]; + } + } for (const k of Object.keys(env)) { saved[k] = process.env[k]; const v = env[k]; diff --git a/tests/issue2187-launcher-slow-start.test.ts b/tests/issue2187-launcher-slow-start.test.ts index e39f34ee16..755d28eecb 100644 --- a/tests/issue2187-launcher-slow-start.test.ts +++ b/tests/issue2187-launcher-slow-start.test.ts @@ -119,6 +119,37 @@ test("#2187 never-healthy child fails after the FULL extended budget, not the in assert.ok(clock.ticks() >= 59, `the full budget (~${Math.ceil(SPAWN_BUDGET_MS / 1000)}s) must be consumed, got ${clock.ticks()}s`); }); +// #2260(A)/#2187: the timeout path is where the spawned child is still ALIVE. +// Before the fix it was abandoned — a detached proxy per failed bring-up, and +// dsh plan-time retries re-arming every 10s turned one persistently slow host +// into ~1 zombie per ~70s (each also stranding the lane sticky-port ladder). +test("#2260(A)/#2187 never-healthy child is hard-killed on timeout instead of leaking", async () => { + const clock = fakeClock(); + const kills: Array = []; + const spawnImpl: SpawnFn = () => ({ + pid: 42462, + kill(signal) { + kills.push(signal); + return true; + }, + }); + await assert.rejects( + ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, + { + fetchImpl: async () => ({ ok: false }), + fetchHealthInfo: async () => ({ ok: false }), + spawnImpl, + now: clock.now, + sleep: clock.sleep, + readInstanceFile: () => undefined, + }, + ), + new RegExp(`did not become healthy within ${SPAWN_BUDGET_MS}ms`), + ); + assert.deepEqual(kills, ["SIGKILL"], "the abandoned child must be hard-killed exactly once"); +}); + test("#2187 cross-process waiter: instance appearing at ~45s attaches instead of double-spawning", async () => { try { claimStartingMarker({ token: "starter-2187", pid: process.pid, host: "127.0.0.1", port: 8788, startedAt: Date.now() }); diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index b6e5560103..bae20a2165 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -2746,6 +2746,40 @@ test("buildCodexArgs: no rewrites → just extra args", () => { assert.deepEqual(buildCodexArgs("http://h:p", [], [], ["--foo"]), ["--foo"]); }); +// #2260(D): cli.ts only eats a LEADING `--` right after the client name, so a +// non-leading one reaches buildCodexArgs inside extra — and everything past it +// is positional to codex's parser. Appending there turned the rewrites into +// prompt text and silently bypassed the proxy (`bili codex exec -- "-p"`). +test("buildCodexArgs: #2260(D) rewrites land BEFORE a user `--` separator, not after its positionals", () => { + const rewrites: HttpRewrite[] = [ + { key: "model_providers.x.base_url", realUpstream: "https://up.local/v1" }, + ]; + assert.deepEqual(buildCodexArgs("http://h:p", rewrites, [], ["exec", "--", "-p"]), [ + "exec", + "-c", `model_providers.x.base_url=${wrapUpstream("http://h:p", "https://up.local/v1")}`, + "--", + "-p", + ]); +}); + +test("buildCodexArgs: #2260(D) last-wins holds across `--` — a user -c before the separator still loses to bili's rewrite", () => { + const rewrites: HttpRewrite[] = [ + { key: "model_providers.x.base_url", realUpstream: "https://up.local/v1" }, + ]; + const out = buildCodexArgs( + "http://h:p", + rewrites, + [], + ["-c", "model_providers.x.base_url=https://user-picked.local/v1", "--", "-p"], + ); + assert.deepEqual(out, [ + "-c", "model_providers.x.base_url=https://user-picked.local/v1", + "-c", `model_providers.x.base_url=${wrapUpstream("http://h:p", "https://up.local/v1")}`, + "--", + "-p", + ]); +}); + test("buildClaudeEnv: ANTHROPIC_BASE_URL rewrite sets env + keeps HTTPS_PROXY/CA", () => { const rewrites: HttpRewrite[] = [ { key: "ANTHROPIC_BASE_URL", realUpstream: "http://relay.local/anthropic" }, @@ -6328,6 +6362,53 @@ test("resolveClientCommand: mcode resolves `mcode` on PATH, falls back to { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-agy-home-")); + const localAppData = fs.mkdtempSync(path.join(os.tmpdir(), "bili-agy-lad-")); + const prevHome = process.env.HOME; + const prevUserProfile = process.env.USERPROFILE; + try { + process.env.HOME = home; + // os.homedir() reads USERPROFILE on win32, not HOME — seal it so the + // non-win32 expectations below hold on every host (CI runs on Windows). + if (prevUserProfile === undefined) delete process.env.USERPROFILE; + else process.env.USERPROFILE = home; + // Before #2260 these branches read process.platform directly, so the + // win32 layout was unreachable from tests (and wrong under any future + // platform-injection use). Pin both layouts via EXPLICIT platform args + // so the test stays host-independent (a bare default-platform call + // resolves through the real host's os.homedir() and cannot hold one + // literal on both Windows and POSIX runners). + assert.deepEqual( + resolveClientCommand("antigravity", { PATH: "/nonexistent-dir-zzz", LOCALAPPDATA: localAppData }, "win32"), + { command: path.join(localAppData, "agy", "bin", "agy"), prefixArgs: [] }, + ); + assert.deepEqual( + resolveClientCommand("antigravity", { PATH: "/nonexistent-dir-zzz" }, "linux"), + { command: path.join(home, ".local", "bin", "agy"), prefixArgs: [] }, + ); + const mdDir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-mcode-plat-")); + fs.mkdirSync(path.join(mdDir, "bin"), { recursive: true }); + fs.writeFileSync(path.join(mdDir, "bin", "mcode.cmd"), ""); + assert.deepEqual( + resolveClientCommand("mcode", { PATH: "/nonexistent-dir-zzz", MCODE_INSTALL_DIR: mdDir }, "win32"), + { command: path.join(mdDir, "bin", "mcode.cmd"), prefixArgs: [] }, + ); + assert.deepEqual( + resolveClientCommand("mcode", { PATH: "/nonexistent-dir-zzz", MCODE_INSTALL_DIR: mdDir }, "linux"), + { command: path.join(mdDir, "bin", "mcode"), prefixArgs: [] }, + ); + rmrf(mdDir); + } finally { + if (prevHome === undefined) delete process.env.HOME; + else process.env.HOME = prevHome; + if (prevUserProfile === undefined) delete process.env.USERPROFILE; + else process.env.USERPROFILE = prevUserProfile; + rmrf(home); + rmrf(localAppData); + } +}); + test("runLaunch mcode: cert-MITM envs (combined CA on SSL_CERT_FILE + NODE_EXTRA_CA_CERTS), discovered host whitelist, model windows (#1050)", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-mcode-launch-")); const prevHome = process.env.HOME; diff --git a/tests/pi-subagents-wiring.test.ts b/tests/pi-subagents-wiring.test.ts index d5423b4ab1..36d5357612 100644 --- a/tests/pi-subagents-wiring.test.ts +++ b/tests/pi-subagents-wiring.test.ts @@ -5,6 +5,8 @@ import os from "node:os"; import path from "node:path"; import { piSubagentsAdapter, wirePiSubagents } from "../src/agent/pi-subagents.ts"; import type { ExtensionAPI, CommandCtx } from "../src/agent/pi.ts"; +import { loadConfigFile } from "../src/config.ts"; +import { DEFAULT_DELEGATE_POLICY, resolveDelegate } from "billion-context-pi-subagents"; // #2186: hermetic wiring tests for the inlined acp_delegate surface. The // delegate tools are never EXECUTED here (they spawn real pi children); only @@ -272,3 +274,54 @@ test("piSubagentsAdapter maps the pi.subagents section onto the package adapter { delegate: { maxConcurrent: 2, displayUsage: "merged", thinkingLevel: "low" }, delegatePrompt: "P", debug: true }, ); }); + +// #2260(F): pins the documented precedence PI_ACP_DELEGATE_* > pi.subagents > +// acp.json > default (CONFIGURATION.md). The env readers live INSIDE the +// bundled package's resolveDelegate, so this drives that real function through +// bili's loader chain — a future package or adapter change that silently drops +// env must fail here. +test("PI_ACP_DELEGATE_* env beats pi.subagents file values, which beat defaults (#2260)", () => { + const envKeys = [ + "PI_ACP_DELEGATE_FORCE_ENABLE", + "PI_ACP_DELEGATE_MAX_DEPTH", + "PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES", + "PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES", + "PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES", + "PI_ACP_DELEGATE_MAX_CONCURRENT", + ]; + const saved: Record = {}; + const setEnv = (vals: Record) => { + for (const k of envKeys) { + saved[k] = process.env[k]; + if (vals[k] === undefined) delete process.env[k]; + else process.env[k] = vals[k]; + } + }; + try { + writeBiliConfig({ pi: { subagents: { maxDepth: 5, syncTimeoutMinutes: 7, forceEnable: false } } }); + const adapter = piSubagentsAdapter(loadConfigFile().pi?.subagents ?? true); + + setEnv({ PI_ACP_DELEGATE_MAX_DEPTH: "3", PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES: "2", PI_ACP_DELEGATE_FORCE_ENABLE: "true" }); + const fromEnv = resolveDelegate(adapter); + assert.equal(fromEnv.maxDepth, 3, "env maxDepth beats file 5"); + assert.equal(fromEnv.syncTimeoutMs, 2 * 60_000, "env sync timeout beats file 7"); + assert.equal(fromEnv.forceEnable, true, "env forceEnable=true beats file false"); + + setEnv({}); + const fromFile = resolveDelegate(adapter); + assert.equal(fromFile.maxDepth, 5, "file maxDepth wins without env"); + assert.equal(fromFile.syncTimeoutMs, 7 * 60_000, "file sync timeout wins without env"); + assert.equal(fromFile.forceEnable, false, "file forceEnable=false holds without env"); + + clearBiliConfig(); + const fromDefaults = resolveDelegate(piSubagentsAdapter(true)); + assert.equal(fromDefaults.maxDepth, DEFAULT_DELEGATE_POLICY.maxDepth, "package default when neither env nor file"); + assert.equal(fromDefaults.forceEnable, false); + } finally { + for (const k of envKeys) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } + clearBiliConfig(); + } +}); diff --git a/tests/plugin-update.test.ts b/tests/plugin-update.test.ts index ff22462bad..575ed9ad0a 100644 --- a/tests/plugin-update.test.ts +++ b/tests/plugin-update.test.ts @@ -104,6 +104,30 @@ test("opencodeCacheCopyRoot: resolves newest spec slot / newest timestamp, undef } }); +// #2260(F): spec slots must order by VERSION, not by string — lexicographic +// sort put @0.1.9 ahead of @0.1.186 ("9" > "1"), reporting the STALE copy. +test("opencodeCacheCopyRoot: version-ordered spec slots (0.1.186 beats 0.1.9); non-numeric specs keep string order", () => { + const base = mkdtempSync(path.join(tmpdir(), "bc-oc-cache-ver-")); + try { + const cacheHome = path.join(base, "cache"); + const npm = path.join(cacheHome, "opencode", "npm"); + const make = (spec: string, version: string): string => { + const root = path.join(npm, `billion-context@${spec}`, "1700000000000", "node_modules", "billion-context"); + mkdirSync(root, { recursive: true }); + writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "billion-context", version })); + return root; + }; + make("0.1.9", "0.1.9"); + const v186 = make("0.1.186", "0.1.186"); + assert.equal(opencodeCacheCopyRoot({ XDG_CACHE_HOME: cacheHome }), v186, "numeric version order, not lexicographic"); + // non-numeric specs keep their pre-existing relative position (string compare) + const latest = make("latest", "9.9.9"); + assert.equal(opencodeCacheCopyRoot({ XDG_CACHE_HOME: cacheHome }), latest, "'latest' still sorts after digit-led specs"); + } finally { + rmrf(base); + } +}); + test("pluginUpdate: opencode lane reports self-update-in-place (#1234), surfaces disk version, never claims 'never overwrites'", async () => { const base = mkdtempSync(path.join(tmpdir(), "bc-plugin-update-")); try { diff --git a/tests/web-sessions.test.ts b/tests/web-sessions.test.ts index fe1b4c589a..8e16072744 100644 --- a/tests/web-sessions.test.ts +++ b/tests/web-sessions.test.ts @@ -665,10 +665,11 @@ withSessionsDir("#1937/#2180: vanished dir serves stale snapshot; explicit missi await assert.rejects(buildSessionList(), "no prior snapshot → reject (→ HTTP 500), never silent empty"); }); -// #2180: pristine default layout (BILI_SESSIONS_DIR unset AND the XDG data root -// itself never created) must resolve to an EMPTY index, not the loud rejection -// above — withSessionsDir can't express that (it always sets the env var), so -// these drive XDG_DATA_HOME directly. +// #2180: pristine default layout (BILI_SESSIONS_DIR unset AND the XDG data +// root absent or holding only bili's own infra dirs — #2260(F)) must resolve +// to an EMPTY index, not the loud rejection above — withSessionsDir can't +// express that (it always sets the env var), so these drive XDG_DATA_HOME +// directly. function withPristineEnv(name: string, fn: (xdg: string) => Promise): void { test(name, async () => { @@ -705,11 +706,23 @@ withPristineEnv("#2180: fresh install (data root never created) serves empty dat assert.deepEqual((await buildSessionList()).map((s) => s.id), ["first-1"], "first persisted session creates the dir and shows up"); }); -withPristineEnv("#2180: existing data root without sessions dir stays loud (#1937)", async (xdg) => { +withPristineEnv("#2180/#1937: data root holding FOREIGN content stays loud", async (xdg) => { mkdirSync(path.join(xdg, "billion-context"), { recursive: true }); + writeFileSync(path.join(xdg, "billion-context", "stray-file.json"), "{}"); _setStoreForTest(new SessionStore({ enabled: false })); _resetDiskCacheForTest(); - await assert.rejects(buildSessionList(), "data root present but sessions dir missing must reject loudly"); + await assert.rejects(buildSessionList(), "non-infra content under the data root must reject loudly (#1937)"); +}); + +// #2260(F): the reported repro — ensureRootCA() creates /ca at proxy +// start, so a fresh install's first web load found a data root WITHOUT its +// sessions subdir and 500'd until the first session was persisted. +withPristineEnv("#2260(F): fresh install after proxy start (data root holds only ca/) serves empty data, not 500", async (xdg) => { + mkdirSync(path.join(xdg, "billion-context", "ca"), { recursive: true }); + _setStoreForTest(new SessionStore({ enabled: false })); + _resetDiskCacheForTest(); + assert.deepEqual(await buildSessionList(), [], "ca/ alone is bili infra — pristine, empty list"); + assert.equal((await buildOverview()).sessions, 0, "overview aggregates zero sessions instead of 500ing"); }); withPristineEnv("#2180/#1937: data root deleted AFTER sessions existed serves stale snapshot, not empty", async (xdg) => {