Skip to content
Closed
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
9 changes: 9 additions & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed
| `compress.nudgeModelDecided` | boolean | off (unset) | — | Model-decided nudge timing (#2228): an armed tier-1 nudge first asks the model — via a short side call over the session's cached prefix — whether compressing NOW helps the current task. A strict-JSON "yes" injects an explicit directive with a program-finalized span; "no", a malformed answer, or a timeout injects nothing this round. EMERGENCY arms and tier≥2 distillation always keep the legacy advisory. Off unless explicitly enabled. |
| `compress.nudgeDecisionMaxTokens` | number | 200 | — | Output budget (tokens) of the model-decision side call used by nudgeModelDecided. Must be > 0. |
| `compress.streamSummary` | boolean | false (unset) | — | Force preflight summarization to run as a streaming (SSE) call from the first attempt. The error-driven self-learn handles stream-mandating upstreams on its own (any 400 on a non-streaming summary triggers a one-shot SSE probe, #2494) but NEVER arms on gateway timeouts (e.g. Cloudflare HTTP 524): set this where such a gateway sits between bili and the origin, or simply to skip the one probe round-trip. |
| `compress.timestamps` | boolean | false (unset) | — | Render arrival timestamps (#4313): every rendered ref tag carries at="YYYY-MM-DD HH:mm" (UTC, minute precision) and each folded summary ends with the covered span's [folded A → B UTC] range, so a days-old plan stops competing with a minutes-old instruction on equal footing. History that predates the setting renders unmarked (times are frozen at first sight, never guessed). Enabling rewrites every already-rendered tag once — a one-time provider prefix-cache flush. |
| `compress.preserveRecentMessages` | number | 3 | — | The most recent messages stay soft-protected from folds. |
| `compress.preserveRecentTokens` | number | kernel ≈5000 | — | The most recent tokens stay soft-protected from folds. |
| `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | Smallest foldable range, in characters; shorter ranges never fold. |
Expand Down Expand Up @@ -1393,6 +1394,14 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t
- **Status:** ACTIVE (#2228)
- **Description:** Output budget, in tokens, of the model-decision side call made when `nudgeModelDecided` is enabled. Must be > 0 (invalid values are rejected at config load).

#### `timestamps`

- **Type:** `boolean`
- **Default:** `false` (unset)
- **Status:** ACTIVE (#4313)
- **Description:** Render arrival timestamps. When on, every rendered message ref tag carries the message's arrival time — `at="YYYY-MM-DD HH:mm"` (UTC, minute precision, frozen at first sight) — and each rendered summary carrier ends with the covered span's arrival-time range, `[folded 2026-10-22 06:14 → 2026-10-22 18:03 UTC]` (single point when the range collapses to one minute). The freeze is unconditional even while rendering is off, so enabling mid-session yields real arrival times for everything seen since deployment. History that predates the feature has no frozen time and renders UNMARKED — never guessed at. Maps to the kernel field `renderTimestamps` (acp-kernel ≥ 0.0.171).
- **Caveats:** enabling rewrites every already-rendered tag once — a one-time provider prefix-cache flush on the next turn. Keep it off for cache-critical long sessions unless the temporal signal matters. Available as a Web UI quick toggle.

#### `preserveRecentMessages`

- **Type:** `number`
Expand Down
9 changes: 9 additions & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@
| `compress.nudgeModelDecided` | boolean | off (unset) | — | 模型自决的压缩时机(#2228):tier-1 提醒触发时,先通过一次走会话缓存前缀的短 side call 问模型——以当前任务为前提,现在压缩是否划算。严格 JSON 的 "yes" 会注入带程序最终确定范围的明确压缩指令;"no"、格式错误或超时则本轮不注入任何内容。EMERGENCY 档与 tier≥2 蒸馏始终保留原有 advisory。默认关闭,需显式开启。 |
| `compress.nudgeDecisionMaxTokens` | number | 200 | — | nudgeModelDecided 所用模型决策 side call 的输出预算(token)。必须 > 0。 |
| `compress.streamSummary` | boolean | false (unset) | — | 强制 preflight 摘要从首次尝试起就走流式(SSE)请求。要求流式的上游现在由错误驱动自学习自动处理(非流式摘要的任何 400 都会触发一次性 SSE 探测,#2494),但网关超时(如 Cloudflare HTTP 524)永远无法触发自学习:在此类网关位于 bili 与源站之间时设置此项,或用于省去一次探测往返。 |
| `compress.timestamps` | boolean | false (unset) | — | 渲染消息到达时间(#4313):每个已渲染的 ref 标签带 at="YYYY-MM-DD HH:mm"(UTC、分钟精度),每条折叠摘要末尾带覆盖区间的 [folded A → B UTC] 时间范围,让几天前的旧方案不再与几分钟前的新指令“看起来同时发生”。早于本设置开启的历史不打标(时间在首次看到时冻结,从不倒填猜测)。开启会把已渲染标签一次性重写——即一次性 provider 前缀缓存冲刷。 |
| `compress.preserveRecentMessages` | number | 3 | — | 最近的消息软保护、免于折叠。 |
| `compress.preserveRecentTokens` | number | kernel ≈5000 | — | 最近的 token 软保护、免于折叠。 |
| `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | 可折叠片段的最小字符数;更短的永不折叠。 |
Expand Down Expand Up @@ -1396,6 +1397,14 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报
- **状态:** ACTIVE (#2228)
- **说明:** `nudgeModelDecided` 开启时,模型决策 side call 的输出预算(token)。必须 > 0(非法值在配置加载时被拒绝)。

#### `timestamps`

- **类型:** `boolean`
- **默认:** `false`(不设)
- **状态:** ACTIVE(#4313)
- **说明:** 渲染消息到达时间戳。开启后,每个已渲染的消息 ref 标签携带该消息的到达时间 `at="YYYY-MM-DD HH:mm"`(UTC、分钟精度、首见即冻结),每条渲染出的摘要载体末尾带覆盖区间的到达时间范围 `[folded 2026-10-22 06:14 → 2026-10-22 18:03 UTC]`(区间塌缩为一分钟时为单点形式)。时间冻结在渲染关闭时也无条件进行,因此中途开启能拿到部署以来所有消息的真实到达时间。早于本功能的历史消息没有冻结时间、不打标——绝不猜时间。映射到内核字段 `renderTimestamps`(acp-kernel ≥ 0.0.171)。
- **注意:** 开启会一次性改写所有已渲染标签——下一轮产生一次性的服务商前缀缓存冲刷。对前缀缓存敏感的长会话,除非确实需要时间信号,建议保持关闭。Web UI 快捷开关已提供。

#### `preserveRecentMessages`

- **类型:** `number`
Expand Down
4 changes: 2 additions & 2 deletions kernel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion kernel/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "acp-kernel",
"version": "0.0.170",
"version": "0.0.171",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
Expand Down
37 changes: 28 additions & 9 deletions kernel/src/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1056,15 +1056,33 @@ const assignRefsNode: PipelineNode = {
const migratedRefs = refResult.migratedIds
.map((id) => refResult.map.byRaw[id])
.filter((r): r is string => typeof r === "string" && r !== BLOCKED_REF);
const state = migratedRefs.length
? {
...io.state,
messageRefs: refResult.map,
renderDeferredRefs: [
...new Set([...(io.state.renderDeferredRefs ?? []), ...migratedRefs]),
],
}
: { ...io.state, messageRefs: refResult.map };
// #4313: freeze each ref's first-seen wall-clock alongside the ref map —
// refs are minted exactly once per message identity, so this is the
// message's arrival time. Unconditional (Config.renderTimestamps gates
// RENDERING only): enabling the flag mid-session yields real arrival
// times for everything seen since deployment, never "now" stamps on old
// messages.
let time = { ...(io.state.timeSnapshot ?? {}) };
let timeChanged = false;
for (const message of io.messages) {
if (!message.id || message.id.startsWith(RETRIEVED_ID_PREFIX)) continue;
const ref = refResult.map.byRaw[message.id];
if (!ref || ref === BLOCKED_REF || time[ref] !== undefined) continue;
time[ref] = Date.now();
timeChanged = true;
}
const state = {
...(migratedRefs.length
? {
...io.state,
messageRefs: refResult.map,
renderDeferredRefs: [
...new Set([...(io.state.renderDeferredRefs ?? []), ...migratedRefs]),
],
}
: { ...io.state, messageRefs: refResult.map }),
...(timeChanged ? { timeSnapshot: time } : {}),
};
return { ...io, state };
},
};
Expand All @@ -1085,6 +1103,7 @@ const pruneNode: PipelineNode = {
...io,
messages: prune(io.messages, io.state, {
isCompressTool: ctx.config.isCompressTool,
renderTimestamps: ctx.config.renderTimestamps === true,
}),
// #2663: keep the pre-prune resent array reachable so recommend can
// judge foldability on the same input class applyCompression sees.
Expand Down
52 changes: 51 additions & 1 deletion kernel/src/prune.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { activeBlocks, coveredMessageIds } from "./state.js";
import { formatUtcMinute } from "./time-fmt.js";
import type { CompressionState, CoreMessage } from "./types.js";

export const SUMMARY_HEADER = "[Compressed conversation section]";
Expand Down Expand Up @@ -109,6 +110,9 @@ export function isRenderedSummaryMessage(

export interface PruneOptions {
injectSummaries?: boolean;
/** #4313: append `[folded A → B UTC]` footers (arrival-time range of the
* block's anchor ids) to rendered summary carriers. */
renderTimestamps?: boolean;
/**
* Chronological head anchoring for views with NO provider prefix cache at
* stake (session handoff/restore docs). Default (false) is the pin-safe
Expand Down Expand Up @@ -203,6 +207,7 @@ export function prune(
? lastUserIndex
: messages.length,
visibleCompressCallIds,
options.renderTimestamps === true,
)
: [];
// Summary ids of every block this session has ever created — active or
Expand Down Expand Up @@ -240,6 +245,10 @@ interface SummaryAnchor {
blockId: string;
summary: string;
topic?: string;
/** #4313: pre-formatted arrival-time footer of the block's anchor range
* (`[folded A → B UTC]`); undefined when timestamps are off or no anchor
* id carries a frozen time (pre-#4313 history). */
timeFooter?: string;
insertAt: number;
/** True when no anchor id was present in the input (the substrate is off
* the wire). Unresolved anchors park before the newest user message and
Expand All @@ -251,6 +260,35 @@ interface SummaryAnchor {
unresolved?: boolean;
}

/** #4313: `[folded A → B UTC]` over the anchor ids' frozen arrival times
* (single point when min == max). Deterministic — read-only over
* timeSnapshot and the immutable block record. */
function summaryTimeFooter(
state: CompressionState,
block: { directMessageIds?: string[]; effectiveMessageIds: string[] },
renderTimestamps: boolean,
): string | undefined {
if (!renderTimestamps) return undefined;
const ids =
block.directMessageIds && block.directMessageIds.length > 0
? block.directMessageIds
: block.effectiveMessageIds;
const times = state.timeSnapshot;
if (!times) return undefined;
let min: number | undefined;
let max: number | undefined;
for (const id of ids) {
const t = times[state.messageRefs.byRaw[id] ?? ""];
if (typeof t !== "number") continue;
if (min === undefined || t < min) min = t;
if (max === undefined || t > max) max = t;
}
if (min === undefined || max === undefined) return undefined;
return min === max
? `[folded ${formatUtcMinute(min)} UTC]`
: `[folded ${formatUtcMinute(min)} → ${formatUtcMinute(max)} UTC]`;
}

function collectSummaryAnchors(
state: CompressionState,
baseIndexById: Map<string, number>,
Expand All @@ -260,6 +298,7 @@ function collectSummaryAnchors(
// blocks created by one of these skip their anchor render (see the
// collection site above for the rationale and the safety conditions).
visibleCompressCallIds: Set<string>,
renderTimestamps: boolean,
): SummaryAnchor[] {
const anchors: SummaryAnchor[] = [];
for (const block of activeBlocks(state)) {
Expand All @@ -269,6 +308,12 @@ function collectSummaryAnchors(
// rebuildMessages via knownSummaryIds and NOT re-injected here.
if (block.compressCallId && visibleCompressCallIds.has(block.compressCallId))
continue;
// #4313: arrival-time footer over the block's DIRECT range — the same
// id set the anchor position uses below (legacy blocks fall back to the
// effective set). Refs without a frozen time (pre-#4313 history) are
// skipped, not guessed at; no times at all → no footer.
const footer = summaryTimeFooter(state, block, renderTimestamps);

// Prefer the position of an already-rendered summary (hosts may pass a
// previously-pruned view): keeps the summary stable in place instead of
// jumping to index 0 when the raw ids are no longer in the input.
Expand All @@ -278,6 +323,7 @@ function collectSummaryAnchors(
blockId: block.blockId,
summary: block.summary,
topic: block.topic,
timeFooter: footer,
insertAt: existingIndex,
});
continue;
Expand Down Expand Up @@ -307,6 +353,7 @@ function collectSummaryAnchors(
blockId: block.blockId,
summary: block.summary,
topic: block.topic,
timeFooter: footer,
// Unresolved (no anchor id present in this input): park before the
// newest user message — see prune() for the #3640/#2733 reasoning.
// Tail-parking (the pre-#3640 behavior) let stale summaries land after
Expand Down Expand Up @@ -550,7 +597,10 @@ function renderSummary(anchor: SummaryAnchor): CoreMessage {
const topicLine = anchor.topic
? `${SUMMARY_HEADER} — ${anchor.topic}`
: SUMMARY_HEADER;
const text = body.length === 0 ? topicLine : `${topicLine}\n${body}`;
const text =
body.length === 0
? topicLine
: `${topicLine}\n${body}${anchor.timeFooter ? `\n${anchor.timeFooter}` : ""}`;
return {
id: summaryMessageId(anchor.blockId),
role: "system",
Expand Down
44 changes: 40 additions & 4 deletions kernel/src/render-refs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { CoreMessage, CompressionState, MessageRefMap } from "./types.js";
import { refForRaw, BLOCKED_REF } from "./refs.js";
import { thinkingTokenValue } from "./tokenize.js";
import { formatUtcMinute } from "./time-fmt.js";
import type { PipelineNode, PipelineContext, NodeIO } from "./pipeline.js";

/**
Expand Down Expand Up @@ -42,14 +43,15 @@ const GT = "\x3e";
const TAG_OPEN = LT + "acp ";
const TAG_CLOSE = LT + "/acp" + GT;

function acpTag(ref: string, tokens: number, type: string): string {
function acpTag(ref: string, tokens: number, type: string, at?: string): string {
return (
TAG_OPEN +
'tokens="' +
formatTokens(tokens) +
'" type="' +
type +
'"' +
(at !== undefined ? ' at="' + at + '"' : "") +
GT +
ref +
TAG_CLOSE
Expand All @@ -63,6 +65,8 @@ function renderMessage(
strategy: RenderStrategy,
snapshot: Record<string, number> | null = null,
deferred: ReadonlySet<string> | null = null,
timeSnapshot: Record<string, number> | null = null,
timestamps = false,
): CoreMessage {
const ref = refForRaw(map, message.id);
if (!ref || ref === BLOCKED_REF) return message;
Expand Down Expand Up @@ -102,7 +106,15 @@ function renderMessage(
: countTokens(cleanText);
const tokens = textTokens + thinkingTokenValue(message.thinkingTokens);
const type = classifyType(message);
const prefix = acpTag(ref, tokens, type) + "\n";
// #4313: arrival stamp, read-only — the freeze happened at ref mint
// (assign-refs node). A ref with no frozen time (pre-#4313 history) renders
// UNMARKED rather than guessing "now" (rejected option A for legacy
// history in the issue).
const at =
timestamps && timeSnapshot !== null && timeSnapshot[ref] !== undefined
? formatUtcMinute(timeSnapshot[ref]!)
: undefined;
const prefix = acpTag(ref, tokens, type, at) + "\n";

if (!cleanText) return { ...message, text: prefix };
return { ...message, text: prefix + cleanText };
Expand All @@ -113,14 +125,24 @@ export function renderVisibleRefs(
state: CompressionState,
countTokens: (text: string) => number = (text) => Math.ceil(text.length / 4),
strategy: RenderStrategy = "all",
timestamps = false,
): CoreMessage[] {
// Legacy behavior: recompute tokens every render (snapshot = null).
const map = state.messageRefs;
const deferred = state.renderDeferredRefs
? new Set(state.renderDeferredRefs)
: null;
return messages.map((message) =>
renderMessage(message, map, countTokens, strategy, null, deferred),
renderMessage(
message,
map,
countTokens,
strategy,
null,
deferred,
state.timeSnapshot ?? null,
timestamps,
),
);
}

Expand All @@ -138,14 +160,27 @@ export function renderWithSnapshot(
state: CompressionState,
countTokens: (text: string) => number = (text) => Math.ceil(text.length / 4),
strategy: RenderStrategy = "all",
timestamps = false,
): RenderWithSnapshotResult {
const map = state.messageRefs;
const snapshot = { ...(state.tokenSnapshot ?? {}) };
const deferred = state.renderDeferredRefs
? new Set(state.renderDeferredRefs)
: null;
// #4313: read-only view of the frozen arrival times (stamped upstream by
// the assign-refs node in the same turn).
const timeSnapshot = state.timeSnapshot ?? null;
const rendered = messages.map((message) =>
renderMessage(message, map, countTokens, strategy, snapshot, deferred),
renderMessage(
message,
map,
countTokens,
strategy,
snapshot,
deferred,
timeSnapshot,
timestamps,
),
);
return { messages: rendered, tokenSnapshot: snapshot };
}
Expand All @@ -160,6 +195,7 @@ export function createRenderRefsNode(strategy: RenderStrategy): PipelineNode {
io.state,
ctx.countTokens,
strategy,
ctx.config.renderTimestamps === true,
);
// Write the snapshot back only when it grew: steady-state (all hits)
// must not churn the state object and force an adapter save every turn.
Expand Down
Loading
Loading