Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions devlog/2026-09-23_dsh-llm-pi-ai-fetch-bypass/REQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,4 @@
3. README zh/en dsh 节条目改为"已报告、调查中"(撤回"已知局限=llm-pi-ai 注入 fetch"的断言),给出两个检测信号与启动器规避;
4. 回归测试:`tests/issue1158-no-model-request-warning.test.ts`(子串保持、一次性语义、entry 分支旧行为不变、文案不得点名单一已确认成因)+ `tests/dsh-native.test.ts` 新增 gate 拒绝日志测试(每端点一次、query 不入日志、不同端点各一行、有归属静默认领)。
5. **引导失败持久化到 bili.log(同日三次修订)**:owner Linux 全链路复现(headless + chromium 驱动 web GUI)未能复现症状,llm-pi-ai 全部流量均过代理;传输形态假设在 Linux 上出局,残余最大嫌疑 = Windows 特有的 spawn/attach 引导失败静默降级——唯一输出是一次性 console.error,GUI 进程 stderr 不可见。故 dsh-native 所有降级点(bootstrap catch / attach 目标不健康回落 / 三处 respawn onGiveUp)同时经 `persistClientEvent` 以 `[dsh-client]` 标记行追加进共享 bili.log(与代理 tee 日志同文件同行形,best-effort 永不向宿主抛错);console.error 双通道保留。
6. **Gate 三态 + 累计计数(L2 follow-up,#1187 落地后)**:报告者运行时证据钉死根因(dsh-http-proxy settings-refresh re-arm 用冻结的 pre-bili capture 覆写 `globalThis.fetch`,把 bili 踢出链;owner 已在 #1187 以 guarded accessor 自愈 L1)。按线程内达成一致的计划升级 gate 仪器:`attributionOf` 三态(ok / none / threw-with-message —— 旧 bare catch 把 `currentInitiator()` 异常吞成"无归属",throwing ALS 边界与合法 agentless 车道不可区分);每端点首次拒绝打一行(格式不变)+ 同态静默累计计数 + 仅状态迁移时重打 `(state none→threw)`;每条打印行同时经 persistClientEvent 追加进 bili.log(`[dsh-client]` 标记,GUI stderr 不可见是本次"零痕迹"的直接原因)。gate 布尔契约不变,#1117 每请求静默保持。
42 changes: 42 additions & 0 deletions devlog/2026-09-23_dsh-llm-pi-ai-fetch-bypass/WORKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,45 @@ ask): bootstrap failures must also land in the shared bili.log file.
vanishing silently — visible, but intended uncompressed.
- `handlePluginCompact`'s analogous 404 wording left untouched (not part of
the symptom; dsh-native has no compaction hook calling it).

## Follow-up: L2 gate three-state (branch 2026-09-23_dsh-gate-three-state-log)

Root cause was pinned by the reporter's runtime evidence (dsh-http-proxy
settings-refresh re-arm overwrites `globalThis.fetch` with its frozen
pre-bili capture, evicting bili from the chain); the owner shipped the L1
self-heal separately (#1187, guarded accessor + `BILI_RECLAIM_FETCH_PATCH`).
This follow-up delivers the agreed L2 instrument in `src/agent/dsh-native.ts`:

- `attributionOf(ctx)`: three states — `ok` (usable session id), `none`
(initiator present-or-absent, no id), `threw` (+ exception message). The old
bare catch folded `threw` into `none`. `sessionIdOf` is now a thin wrapper;
statusOutcome/headersFor behavior is byte-identical.
- Gate refusal log: first refusal per endpoint prints exactly as before plus
`— refusals so far: N`; same-state refusals accumulate silently; a state
transition (none↔threw) re-prints with `(state none→threw)`. Bounded noise
— #1117's per-request silence preserved; the 256-endpoint cap now clears
only when a NEW endpoint would overflow (existing counts survive).
- Every printed line is additionally appended to bili.log via
`persistClientEvent` (`[warn] [dsh-client] …`) so GUI hosts that swallow
stderr leave a durable trace.

Behavior change disclosure (old → new):
- A gate refusal on a previously-unseen endpoint now ends with
`— refusals so far: 1` (previously no count suffix).
- NEW log lines appear on attribution-state transitions
(`(state none→threw)` / `(state threw→none)`) carrying the accumulated
count — previously only one flat line per endpoint ever existed.
- NEW durable lines in `~/.local/state/billion-context/bili.log`
(`[dsh-client]`-marked) mirroring every printed refusal line — previously
refusals were stderr-only and invisible in GUI hosts.
- No change to gate decision logic, wire shapes, config schema, or persistence
format.

Verification (head 2a6778df, based on master incl. merged #1187):
- `npm run typecheck`: clean (after `npm ci` — a stale local acp-kernel 0.0.82
vs pinned 0.0.84 had produced spurious src/store.ts errors on the old tree).
- `npm test`: 2359 total, 2357 pass, 0 fail, 2 skipped (gated E2E);
dsh-native 31/31 (+1 new three-state test covering silent counting,
both transition directions, attributed-silent claim, and the durable
bili.log copy).
- `npm run build`: success.
71 changes: 49 additions & 22 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,15 +350,33 @@ function maybeRetry(ctx: PluginContext): void {
void registerTools(ctx).catch(() => {});
}

function sessionIdOf(ctx: PluginContext): string | undefined {
// #1158 L2: three-state attribution for the takeover gate. The old bare catch
// swallowed currentInitiator() exceptions (disposed/closing agent scope) as
// plain "no attribution", making a throwing ALS boundary indistinguishable
// from a legitimate agentless lane — both went silent-direct behind one flat
// log line each. Three states + per-endpoint cumulative counts make the
// "dozens refused, one passed" distribution diagnosable at a glance.
type GateAttribution =
| { state: "ok"; sid: string }
| { state: "none"; initiatorPresent: boolean }
| { state: "threw"; message: string };

function attributionOf(ctx: PluginContext): GateAttribution {
try {
const sid = ctx.agents?.currentInitiator?.()?.session?.id;
return typeof sid === "string" && sid.length > 0 ? sid : undefined;
} catch {
return undefined;
const init = ctx.agents?.currentInitiator?.();
const sid = init?.session?.id;
if (typeof sid === "string" && sid.length > 0) return { state: "ok", sid };
return { state: "none", initiatorPresent: init !== undefined && init !== null };
} catch (err) {
return { state: "threw", message: err instanceof Error ? err.message : String(err) };
}
}

function sessionIdOf(ctx: PluginContext): string | undefined {
const attr = attributionOf(ctx);
return attr.state === "ok" ? attr.sid : undefined;
}

async function statusOutcome(ctx: PluginContext): Promise<CommandOutcome> {
const base = register.base;
if (!base) {
Expand Down Expand Up @@ -492,31 +510,40 @@ export function apply(ctx: PluginContext): void {
state.ready = start();
}

// #1158: a refusal sends model traffic DIRECT with zero trace — the exact
// silence that made the reported zero-traffic case undiagnosable. Log each
// distinct endpoint once per process with the attribution state at refusal
// time; legitimate agentless lanes (dsh's withoutInitiator background
// drivers, third-party in-process callers) add at most one flat line per
// endpoint, so the noise floor stays constant (#1117 silence preserved).
const gateRefusedPaths = new Set<string>();
// #1158 L2: a refusal sends model traffic DIRECT. First refusal per
// endpoint logs once; same-state refusals accumulate silently and re-print
// only on an attribution STATE change (none↔threw), always carrying the
// cumulative count — bounded noise (#1117 silence preserved) while a
// "dozens refused, one passed" distribution becomes visible. The durable
// copy goes through persistClientEvent: GUI hosts swallow stderr, which is
// exactly how the reported zero-traffic case stayed invisible.
const gateRefusals = new Map<string, { state: string; count: number }>();
state.takeoverGate = (url) => {
if (sessionIdOf(ctx) !== undefined) return true;
const attr = attributionOf(ctx);
if (attr.state === "ok") return true;
let key: string;
try {
const u = new URL(url);
key = `${u.origin}${u.pathname}`;
} catch {
key = url;
}
if (gateRefusedPaths.size >= 256) gateRefusedPaths.clear();
if (!gateRefusedPaths.has(key)) {
gateRefusedPaths.add(key);
let init: unknown;
try { init = ctx.agents?.currentInitiator?.(); } catch { init = undefined; }
const initiatorPresent = init !== undefined && init !== null;
console.error(
`bili-native-dsh: model request sent DIRECT (uncompressed) — takeover gate refused ${key}: ${initiatorPresent ? "initiator present but missing session id" : "no active initiator attribution (agentless/background lane, third-party in-process caller, or stale attribution after host resume?)"}`,
);
const prev = gateRefusals.get(key);
const count = (prev?.count ?? 0) + 1;
const changed = prev !== undefined && prev.state !== attr.state;
if (prev === undefined && gateRefusals.size >= 256) gateRefusals.clear();
gateRefusals.set(key, { state: attr.state, count });
if (prev === undefined || changed) {
const reason =
attr.state === "threw"
? `currentInitiator() threw (${attr.message}) — agent scope disposed/closing mid-request?`
: attr.initiatorPresent
? "initiator present but missing session id"
: "no active initiator attribution (agentless/background lane, third-party in-process caller, or stale attribution after host resume?)";
const suffix = prev !== undefined ? ` (state ${prev.state}→${attr.state})` : "";
const line = `bili-native-dsh: model request sent DIRECT (uncompressed) — takeover gate refused ${key}: ${reason} — refusals so far: ${count}${suffix}`;
console.error(line);
persistClientEvent(line);
}
return false;
};
Expand Down
77 changes: 75 additions & 2 deletions tests/dsh-native.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -833,9 +833,10 @@ test("#983 maybeRetry self-heals a base-less register after a failed respawn", a

test("#1117 apply() installs takeoverGate keyed on currentInitiator attribution", async () => {
const proxy = await startMockProxy([]);
const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-1117-state-"));
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-1117-"));
try {
await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => {
await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin, XDG_STATE_HOME: stateHome }, async () => {
_resetRegisterForTest(proxy.origin);
const ctx = mockCtx();
apply(ctx);
Expand All @@ -855,16 +856,18 @@ test("#1117 apply() installs takeoverGate keyed on currentInitiator attribution"
});
} finally {
proxy.close();
fs.rmSync(stateHome, { recursive: true, force: true });
fs.rmSync(home, { recursive: true, force: true });
_resetRegisterForTest(undefined);
}
});

test("#1158 apply() gate refusal logs each endpoint once per process with attribution state", async () => {
const proxy = await startMockProxy([]);
const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-1158-state-"));
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-1158-"));
try {
await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => {
await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin, XDG_STATE_HOME: stateHome }, async () => {
_resetRegisterForTest(proxy.origin);
const ctx = mockCtx();
apply(ctx);
Expand Down Expand Up @@ -901,6 +904,76 @@ test("#1158 apply() gate refusal logs each endpoint once per process with attrib
});
} finally {
proxy.close();
fs.rmSync(stateHome, { recursive: true, force: true });
fs.rmSync(home, { recursive: true, force: true });
_resetRegisterForTest(undefined);
}
});

test("#1158 L2 gate three-state: thrown attribution is a distinct state; counts accumulate; transitions re-print (+bili.log)", async () => {
const proxy = await startMockProxy([]);
const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-1158e-state-"));
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-1158e-home-"));
try {
await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin, XDG_STATE_HOME: stateHome }, async () => {
_resetRegisterForTest(proxy.origin);
const ctx = mockCtx();
apply(ctx);
await waitFor(() => ctx.registeredTools.length === 1, "initial attach tool registration");
const gate = _stateTakeoverGateForTest();
assert.ok(gate !== undefined, "takeoverGate installed");
const origCI = ctx.agents.currentInitiator;
const origErr = console.error;
const errs: string[] = [];
console.error = (...args: unknown[]) => {
errs.push(args.map(String).join(" "));
};
try {
const url = "https://api.gate-l2.test/v1/chat/completions";
// four same-state (none) refusals → exactly one line; counting continues silently
assert.equal(gate(url), false);
assert.equal(gate(url), false);
assert.equal(gate(url), false);
assert.equal(gate(url), false);
let lines = errs.filter((e) => e.includes("takeover gate refused"));
assert.equal(lines.length, 1, `expected one line for repeated same-state refusals, got: ${errs.join(" | ")}`);
assert.match(lines[0]!, /no active initiator attribution/);
assert.match(lines[0]!, /refusals so far: 1$/);
// the ALS boundary starts throwing (disposed/closing agent scope) →
// new category → re-print carrying the accumulated count
ctx.agents.currentInitiator = () => {
throw new Error("agent initiator scope is disposed");
};
assert.equal(gate(url), false);
lines = errs.filter((e) => e.includes("takeover gate refused"));
assert.equal(lines.length, 2, `expected a state-transition re-print, got: ${errs.join(" | ")}`);
assert.match(lines[1]!, /currentInitiator\(\) threw \(agent initiator scope is disposed\)/);
assert.match(lines[1]!, /refusals so far: 5 \(state none→threw\)$/);
// further thrown refusals stay silent again
assert.equal(gate(url), false);
assert.equal(errs.filter((e) => e.includes("takeover gate refused")).length, 2);
// back to plain none → transition the other way, count keeps running
ctx.agents.currentInitiator = () => undefined;
assert.equal(gate(url), false);
lines = errs.filter((e) => e.includes("takeover gate refused"));
assert.equal(lines.length, 3);
assert.match(lines[2]!, /refusals so far: 7 \(state threw→none\)$/);
// attributed traffic claims silently — no line
ctx.agents.currentInitiator = origCI;
ctx.setInitiator({ session: { id: "s1158l2" } });
assert.equal(gate(url), true);
assert.equal(errs.filter((e) => e.includes("takeover gate refused")).length, 3);
// the durable copy carries the same lines into bili.log, [dsh-client]-marked
const logFile = path.join(stateHome, "billion-context", "bili.log");
const content = fs.readFileSync(logFile, "utf8");
assert.match(content, /\[warn\] \[dsh-client\] bili-native-dsh: model request sent DIRECT \(uncompressed\) — takeover gate refused https:\/\/api\.gate-l2\.test\/v1\/chat\/completions: currentInitiator\(\) threw \(agent initiator scope is disposed\) — agent scope disposed\/closing mid-request\? — refusals so far: 5 \(state none→threw\)$/m);
} finally {
console.error = origErr;
}
});
} finally {
proxy.close();
fs.rmSync(stateHome, { recursive: true, force: true });
fs.rmSync(home, { recursive: true, force: true });
_resetRegisterForTest(undefined);
}
Expand Down
Loading