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
12 changes: 12 additions & 0 deletions CLIENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,18 @@ is expected, not a stuck compressor. The effective size is the proxy's: read
`/acp` (or `GET /__bili/plugin/status` → `contextTokens`, provenance in
`contextTokensSource`) instead of re-deriving it locally.

**The dsh client ships a Context tab for this (#3862):** the native plugin
registers a session-scoped `Context` tab in dsh's conversation view (right of
Chat/Trajectory). It reads `GET /__bili/plugin/status` cross-origin from the
dsh web app and renders the same breakdown the `/acp` panel computes live:
the post-compression sent total against the window limit, category segments
(system+tools / tools / text / code / summaries), the usage-grade billed
anchor on its own labeled scale, and recent fold/switch events with reclaimed
tokens. It refreshes every 10 s; when the running proxy predates this build
the tab degrades to a restart notice plus an open-Web-UI button instead of
guessing. Plain React from dsh's own runtime — no iframe, no added
dependencies.

## Kimi Code (Moonshot)

Three aligned modes: `bili kimi` (launcher, cert-MITM — README Quickstart
Expand Down
384 changes: 364 additions & 20 deletions src/agent/dsh-native-client.ts

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/cache-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1635,7 +1635,7 @@ function stampedPriceProfile(session: Session): PriceProfile | undefined {
return Object.keys(out).length > 0 ? out : undefined;
}

interface ModelSwitchEvent {
export interface ModelSwitchEvent {
seq: number;
at: number;
from: string | null;
Expand Down
148 changes: 148 additions & 0 deletions src/context-view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// #3862: structured context view for programmatic consumers (the dsh client
// Context tab). bili folds happen OUTSIDE the dsh event stream, so host-side
// stat plugins anchored on it show the PRE-compression caliber forever
// (dsh-context#173); bili knows the exact post-fold bytes and publishes them
// here as a machine-readable twin of the /acp panel. Two load-bearing
// invariants: (1) every figure is the kernel countTokens estimate of the
// CURRENT sent view except `anchor`, which is the usage-grade reading (#2117
// displayContextBest ladder) on its OWN scale — never mix the two in
// arithmetic; (2) the category math mirrors kernel buildStatusPanel
// one-to-one (sentTotal = classified + host system+tools), so segments sum
// to sentTotal and the view can never drift from the panel text. Events ride
// buildSessionCacheReport — the same ledger semantics the Web UI renders.

import type { NudgeDecision } from "acp-kernel";
import { buildSessionCacheReport, type ModelSwitchEvent } from "./cache-ledger.js";
import { displayContextBest, type Session } from "./session.js";

/** Max events per trail published in the view (newest first). */
const EVENT_CAP = 20;

interface ContextViewCategory {
/** sysprompt | tool | text | code | summaries | system */
key: string;
tokens: number;
/** percent of sentTotal (rounded; segments may not sum to exactly 100). */
pct: number;
}

interface ContextViewFold {
seq: number;
at: number;
/** S: original tokens folded out of the sent view. */
s: number;
/** sigma: summary tokens that stayed in the window. */
sigma: number;
/** S − sigma clamped at 0 — the pure token removal this fold achieved. */
reclaimed: number;
/** (S−σ) × requestsAfter — tokens not billed because of this fold so far. */
savedSoFar: number;
paidBack: boolean | null;
}

interface ContextViewSwitch {
dim: "model" | "key" | "prompt" | "restart";
at: number;
from: string | null;
to: string;
/** ttlRepay tokens attributed to this event by the ledger partition. */
attributed: number;
}

interface ContextViewAnchor {
tokens: number;
kind: "usage" | "estimate" | "upper";
at: number | null;
}

interface ContextView {
/** Every token figure in this object is on ONE scale: the kernel
* countTokens estimate of the current sent view. The anchor is the
* exception — its own usage-grade scale, labeled via kind. */
scale: "estimate";
/** wall-clock of this computation (epoch ms). */
at: number;
limit: number | null;
sentTotal: number;
/** growth since the last nudge reference (0 when none recorded). */
growth: number;
categories: ContextViewCategory[];
anchor: ContextViewAnchor | null;
folds: ContextViewFold[];
switches: ContextViewSwitch[];
}

interface BuildInput {
nudge: NudgeDecision | undefined;
/** Host-measured system+tools overhead (prepare-time, same source as the
* panel's SysPrompt row). */
systemPromptTokens: number;
limit: number;
session: Session;
}

/** null when no breakdown exists yet (no messages processed this process) —
* consumers then show their waiting state instead of a zero card. */
export function buildContextView(input: BuildInput): ContextView | null {
const bd = input.nudge?.contextBreakdown;
if (bd === undefined) return null;
// Same classification as kernel/src/panel/panel.ts buildStatusPanel.
const classified = bd.system + bd.tool + bd.summaries + bd.code + bd.text;
const sentTotal = classified + input.systemPromptTokens;
const pctOf = (v: number): number => (sentTotal > 0 ? Math.round((v / sentTotal) * 100) : 0);
const rows: Array<[string, number]> = [
["sysprompt", input.systemPromptTokens],
["tool", bd.tool],
["text", bd.text],
["code", bd.code],
["summaries", bd.summaries],
["system", bd.system],
];
const categories: ContextViewCategory[] = [];
for (const [key, tokens] of rows) {
if (tokens <= 0) continue;
categories.push({ key, tokens, pct: pctOf(tokens) });
}
const folds: ContextViewFold[] = [];
const switches: ContextViewSwitch[] = [];
try {
const report = buildSessionCacheReport(input.session);
for (const f of [...report.folds].reverse().slice(0, EVENT_CAP)) {
folds.push({
seq: f.seq,
at: f.at,
s: f.S,
sigma: f.sigma,
reclaimed: Math.max(0, f.S - f.sigma),
savedSoFar: f.savedSoFar,
paidBack: f.paidBack,
});
}
const evs: ContextViewSwitch[] = [];
const take = (dim: ContextViewSwitch["dim"], events: readonly ModelSwitchEvent[]): void => {
for (const e of events) evs.push({ dim, at: e.at, from: e.from, to: e.to, attributed: e.attributed });
};
take("model", report.modelSwitches.events);
take("key", report.keySwitches.events);
take("prompt", report.promptSwitches.events);
take("restart", report.restartDrops.events);
evs.sort((a, b) => b.at - a.at);
for (const e of evs.slice(0, EVENT_CAP)) switches.push(e);
} catch {
// Ledger/report unavailable (corrupt metadata, partial restore) — the
// view still serves its primary job (current composition); trails stay
// empty rather than failing the whole status read.
}
const best = displayContextBest(input.session);
return {
scale: "estimate",
at: Date.now(),
limit: Number.isFinite(input.limit) && input.limit > 0 ? input.limit : null,
sentTotal,
growth: bd.growth,
categories,
anchor: best !== null ? { tokens: best.tokens, kind: best.kind, at: best.at ?? null } : null,
folds,
switches,
};
}
35 changes: 26 additions & 9 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { getStore, storageStatusLabel } from "./persist.js";
import { cloneStoreForRefs } from "./store.js";
import { acquireInFlight, createSession, getSession, publishForkSession, diagnoseSuccessWithoutUsage, effectiveConfig, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, statusInputBaseline, withSessionLock, type Session } from "./session.js";
import { clientConversationHeader } from "./session-id.js";
import { buildContextView } from "./context-view.js";
import { ABSORB_TOOL_NAME, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, PROXY_TOOL_NAMES, READ_ORIGINAL_IMAGE_TOOL, READ_ORIGINAL_IMAGE_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_OPENAI, READ_ORIGINAL_IMAGE_TOOL_RESPONSES, RETRIEVE_TOOL_NAME, RULE_TOOL, RULE_TOOL_NAME, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, SEARCH_CONTEXT_TOOL_NAME, absorbToolsFor, retrieveToolsFor, withAcpNotes, withAcpNotesOpenAI } from "./compress-tool.js";
import { externalSummaryEnabled, externalSummaryMaxToolDurationMs, withExternalSummaryTools } from "./external-summary-surface.js";
import { salvageCompressArgs } from "./plugin-compress-salvage.js";
Expand Down Expand Up @@ -1475,7 +1476,17 @@ function webSessionUrl(origin: string | undefined, sessionId: string): string |
return `${o}/__bili/#/session/${encodeURIComponent(sessionId)}`;
}

export function handlePluginStatus(conversationId: string, res: import("node:http").ServerResponse, deps: PluginToolDeps, fallbackLatest = false): void {
export function handlePluginStatus(conversationId: string, res: import("node:http").ServerResponse, deps: PluginToolDeps, fallbackLatest = false, trustedOrigin?: string): void {
// #3862: the dsh client's Context tab reads this route CROSS-ORIGIN from
// the dsh web app (its own loopback port / the dsh-app://app scheme). The
// trusted-origin gate upstream of dispatch already admitted the request;
// echoing that origin makes the cors-mode fetch readable in the browser —
// the same fix the HTML embed route carries (#3100 pre-flight).
const jsonHeaders = (): Record<string, string> => {
const h: Record<string, string> = { "content-type": "application/json" };
if (trustedOrigin !== undefined && trustedOrigin.length > 0) h["access-control-allow-origin"] = trustedOrigin;
return h;
};
let session = resolveForkConversation(conversationId);
const entry = conversations.get(conversationId);
let viaFallback = false;
Expand Down Expand Up @@ -1504,7 +1515,7 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt
// renderable panel; `phase` exposes the state for programmatic consumers.
const verdict = chainVerdictFor(conversationId);
if (verdict !== undefined) {
res.writeHead(200, { "content-type": "application/json" });
res.writeHead(200, jsonHeaders());
res.end(JSON.stringify({ ok: true, conversationId, phase: "chain-advisory", chain: verdict, panel: chainAdvisoryPanel(verdict), sessionId: null, sessionRevision: null, model: null, contextLimit: null, contextTokens: null, contextTokensSource: "unavailable", contextTokensAt: null, contextGeneration: null }));
return;
}
Expand All @@ -1515,7 +1526,7 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt
// with their agent name (dsh's fetchStatusLatest sends "dsh").
const pre = pluginRuntimeTable.get(conversationId) ?? pluginRuntimeByConversation.get(conversationId);
if (pre !== undefined) {
res.writeHead(200, { "content-type": "application/json" });
res.writeHead(200, jsonHeaders());
res.end(JSON.stringify({ ok: true, conversationId, phase: "pre-first-request", model: pre.model, contextLimit: pre.contextWindow ?? null, runtimeInfo: pre, panel: null, sessionId: null, sessionRevision: null, contextTokens: null, contextTokensSource: "unavailable", contextTokensAt: null, contextGeneration: null }));
return;
}
Expand Down Expand Up @@ -1569,17 +1580,20 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt
if (nudge) {
nudge = { ...nudge, compressibleRanges: excludeDeadRefRanges(nudge.compressibleRanges ?? [], session.state.deadRefs) };
}
// #532/#3862: host-measured system+tools overhead (prepare-time, same
// source as estimateInputTokens) — shared by the panel text below AND the
// structured context view, so both surfaces classify identically.
const sysTokRaw = session.metadata.systemPromptTokens;
const systemPromptTokens = typeof sysTokRaw === "number" && Number.isFinite(sysTokRaw) && sysTokRaw > 0 ? sysTokRaw : 0;
const contextView = buildContextView({ nudge, systemPromptTokens, limit: modelContextLimit, session });
let panel: string | undefined;
try {
// #532: the kernel breakdown classifies messages only; bili measured
// the outbound system+tools overhead at prepare time (same source as
// estimateInputTokens) and stored it on the session. Feeding it in is
// #532: the kernel breakdown classifies messages only; feeding in the
// host-measured system+tools (hoisted above with the context view) is
// what makes Sent/SysPrompt reflect reality instead of undercounting
// by the full system+tools size every turn. unprunedTokens gets the
// same addition so the Session-only derivation (unpruned − sent) still
// isolates pruned originals on one scale.
const sysTokRaw = session.metadata.systemPromptTokens;
const systemPromptTokens = typeof sysTokRaw === "number" && Number.isFinite(sysTokRaw) && sysTokRaw > 0 ? sysTokRaw : 0;
panel = buildStatusPanel({
version: `billion-context@${PROXY_VERSION}${BUILD_COMMIT && BUILD_COMMIT !== "unknown" ? ` (${BUILD_COMMIT})` : ""} · pack: ${session.meta.activePack ?? "default"}`,
// #2671: effective storage mode — legacy/shadow/full, including
Expand Down Expand Up @@ -1641,7 +1655,7 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt
// replace() pattern syntax ($&, $\`, $') and corrupt the box lines.
panel = panel.replace(PANEL_BOX_FOOTER, `\n${preFooter.join("\n")}\n${PANEL_BOX_FOOTER}`.replace(/\$/g, "$$$$"));
}
res.writeHead(200, { "content-type": "application/json" });
res.writeHead(200, jsonHeaders());
res.end(JSON.stringify({
ok: true,
conversationId: resolvedConversationId,
Expand All @@ -1660,6 +1674,9 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt
contextTokensSource,
contextTokensAt: observation?.at ?? null,
contextGeneration: observation ? forkHash({ sessionId: session.id, sessionRevision, generation: observation.generation, contextTokens, contextTokensSource, limit, model: session.metadata.lastModel }) : null,
// #3862: structured twin of the panel's sent-view breakdown + event
// trails — additive field, null until the first request lands.
contextView,
compressCreditTokens: session.stats.compressCreditTokens ?? 0,
inputTokens: session.stats.inputTokens,
outputTokens: session.stats.outputTokens,
Expand Down
6 changes: 5 additions & 1 deletion src/server/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,11 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv
// Web UI origin as the user's browser dials it: the ACTUAL bound port
// (req.socket.localPort differs from opts.port when listening on port 0).
const webOrigin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${req.socket?.localPort ?? opts.port}`;
return handlePluginStatus(conversationId, res, { core, config, log, webOrigin }, params.get("fallback") === "latest");
// #3862: pass the requesting origin through so the handler can echo it
// back for cross-origin browser readers (the dsh client Context tab);
// only origins the gate above admitted ever reach this line.
const reqOrigin = req.headers.origin;
return handlePluginStatus(conversationId, res, { core, config, log, webOrigin }, params.get("fallback") === "latest", typeof reqOrigin === "string" && reqOrigin.length > 0 ? reqOrigin : undefined);
}
if (req.method === "POST" && req.url === "/__bili/watcher") {
// #7: an ATTACHING claude session registers its host pid so the shared
Expand Down
Loading
Loading