From 77e491f9b0694664ccddee39614cf5a13fe5cd10 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 12 Nov 2026 17:41:17 +0800 Subject: [PATCH] refactor(compaction): record the answered route in a private projection Review feedback: the summary route and its restorable state belong to compaction-basic. A host-only projection now records the provider/model of each assistant message source, replacing the tokenMeter.answeredRoute() service method, which had one caller. --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/subsystems/token-meter.md | 8 -- docs/subsystems/token-meter.zh.md | 8 -- .../compaction-basic/README.i18n.yaml | 12 +-- .../compaction/compaction-basic/README.md | 5 +- .../compaction/compaction-basic/README.zh.md | 5 +- .../compaction/compaction-basic/package.json | 4 +- .../compaction-basic/src/answered-route.ts | 27 +++++++ .../compaction/compaction-basic/src/index.ts | 33 +++++--- .../tests/compaction-basic.spec.ts | 77 ++++++++++++++++++- .../compaction/compaction-basic/tsconfig.json | 3 + .../extensions/tool-cordis/src/api-catalog.ts | 6 -- packages/llm/token-meter/README.i18n.yaml | 4 +- packages/llm/token-meter/README.md | 2 +- packages/llm/token-meter/README.zh.md | 2 +- packages/llm/token-meter/src/index.ts | 13 ---- .../llm/token-meter/tests/token-meter.spec.ts | 34 -------- pnpm-lock.yaml | 3 + 19 files changed, 152 insertions(+), 98 deletions(-) create mode 100644 packages/compaction/compaction-basic/src/answered-route.ts diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 8934b48a39..c25cb34cf3 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -780,7 +780,7 @@ export interface Config { ## `@deepseek-ai/dsh-compaction-basic` -- `inject`: `llm` · `tokenMeter` · `sessions` +- `inject`: `llm` · `tokenMeter` · `sessions` · `sessionProjections` - `source`: [`packages/compaction/compaction-basic/src/types.ts:46`](../packages/compaction/compaction-basic/src/types.ts) ```ts config-catalog diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 05be342169..b325099dc6 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -782,7 +782,7 @@ export interface Config { ## `@deepseek-ai/dsh-compaction-basic` -- `inject`: `llm` · `tokenMeter` · `sessions` +- `inject`: `llm` · `tokenMeter` · `sessions` · `sessionProjections` - `source`: [`packages/compaction/compaction-basic/src/types.ts:46`](../packages/compaction/compaction-basic/src/types.ts) ```ts config-catalog diff --git a/docs/subsystems/token-meter.md b/docs/subsystems/token-meter.md index 4a12d2a206..1aa56a8d24 100644 --- a/docs/subsystems/token-meter.md +++ b/docs/subsystems/token-meter.md @@ -113,14 +113,6 @@ Replay owner for one service-wide estimator and isolated per-session folds. */ contextPressure(session: Session): Pick -/** - * Read the route of the request that produced the latest assistant message. - * A request that failed before recording an assistant message leaves it unchanged. - * @param session - Session whose durable history is read. - * @returns a detached provider/model pair, or `undefined` before any assistant message or when no request header preceded it. - */ -answeredRoute(session: Session): { provider: string; model: string } | undefined - /** * Measure current request pressure and surface through the durable tail. * diff --git a/docs/subsystems/token-meter.zh.md b/docs/subsystems/token-meter.zh.md index 0124c376ad..970f90d9dd 100644 --- a/docs/subsystems/token-meter.zh.md +++ b/docs/subsystems/token-meter.zh.md @@ -113,14 +113,6 @@ Replay owner for one service-wide estimator and isolated per-session folds. */ contextPressure(session: Session): Pick -/** - * Read the route of the request that produced the latest assistant message. - * A request that failed before recording an assistant message leaves it unchanged. - * @param session - Session whose durable history is read. - * @returns a detached provider/model pair, or `undefined` before any assistant message or when no request header preceded it. - */ -answeredRoute(session: Session): { provider: string; model: string } | undefined - /** * Measure current request pressure and surface through the durable tail. * diff --git a/packages/compaction/compaction-basic/README.i18n.yaml b/packages/compaction/compaction-basic/README.i18n.yaml index 0f41c95907..be3ff4e4b5 100644 --- a/packages/compaction/compaction-basic/README.i18n.yaml +++ b/packages/compaction/compaction-basic/README.i18n.yaml @@ -21,8 +21,8 @@ en: eb8e340061f72b98 zh: 327a51037b2d1adf /deepseek-ai-dsh-compaction-basic/use-this-package/smallest-working-composition: - en: 4cb73d7a57908948 - zh: 7ba2ddc4c76e4957 + en: 24b0cc6db9c9f080 + zh: 5adb5b585a45df95 /deepseek-ai-dsh-compaction-basic/use-this-package/tuning-when-condensation-starts: en: 0a4bf89e1c55fed7 zh: 34463d8492922e92 @@ -45,8 +45,8 @@ en: ed2d43610d4eaa83 zh: b46a1eaad396cdd7 /deepseek-ai-dsh-compaction-basic/understand-the-implementation/automatic-triggers-and-overflow-recovery: - en: bd02f95bb8778565 - zh: f183111bedb6e0a4 + en: 8d31a23eb7dcafac + zh: 2e2a4a41e1587d1f /deepseek-ai-dsh-compaction-basic/understand-the-implementation/summarization-mechanics: en: 967531b71453eb88 zh: c7919b46e36763e6 @@ -57,8 +57,8 @@ en: 313e019b1a9f8aa8 zh: 3c75d11b02adb693 /deepseek-ai-dsh-compaction-basic/understand-the-implementation/source-map: - en: 747bad235fbb04ad - zh: 02e6562f3d745d4f + en: 03784273b57e140b + zh: 8b699b5366452d9e /deepseek-ai-dsh-compaction-basic/further-exploration: en: 84b5b81eb9b5965d zh: 7000af0fa502fcc1 diff --git a/packages/compaction/compaction-basic/README.md b/packages/compaction/compaction-basic/README.md index c1ab8a2224..4c05ac9333 100644 --- a/packages/compaction/compaction-basic/README.md +++ b/packages/compaction/compaction-basic/README.md @@ -43,7 +43,7 @@ Mount session storage, token measurement, the optional pruner, this backend, and - name: '@deepseek-ai/dsh-command-compact' ``` -You can verify success by watching the conversation continue past the point where it would otherwise overflow, and by running `/compact` for an immediate condensation. If the composition lacks an LLM, session storage, or token measurement, the plugin fails to load. One backend can serve models with different context sizes; give each route its own threshold and retention with a per-model override: +You can verify success by watching the conversation continue past the point where it would otherwise overflow, and by running `/compact` for an immediate condensation. If the composition lacks an LLM, session storage, session projections, or token measurement, the plugin fails to load. One backend can serve models with different context sizes; give each route its own threshold and retention with a per-model override: ```yaml - name: '@deepseek-ai/dsh-compaction-basic' @@ -118,7 +118,7 @@ The backend is built on four commitments: ### Automatic triggers and overflow recovery -The `agent/request` listener waits for routing listeners to select the destination, then checks its pressure before the new header is logged. It uses `compactPressure` directly because `compactIfNeeded` reads the committed header; both paths generate summaries through `summarize()`, which reads `ctx.tokenMeter.answeredRoute()` before the committed header because a request that failed has already replaced that header. +The `agent/request` listener waits for routing listeners to select the destination, then checks its pressure before the new header is logged. It uses `compactPressure` directly because `compactIfNeeded` reads the committed header; both paths generate summaries through `summarize()`, which reads the route recorded on the latest assistant message before the committed header because a request that failed has already replaced that header. A host-only session projection, `compactionAnsweredRoute`, holds that provider/model pair, so a restored session reads it from its checkpoint; the plugin registers the projection at construction and releases it on unload. With `auto: true`, a serial `agent/pre-step` listener checks pressure before request derivation: it prices the latest durable routed request envelope through `ctx.tokenMeter`, and when pressure crosses the routed model's threshold it prunes, then summarizes the oldest balanced span while keeping a priced recent tail. Every selected range starts at the first surface node that is not a `system/message`, so a system prompt at surface node 0 is never shadowed; a later `system/message` appended by an in-history prompt update is ordinary history that the range may shadow, and the agent loop's projection then replaces node 0 with the current prompt when their text differs ([decision rule](../../core/agent-loop/README.md#understand-the-implementation)). The `agent/request-error` listener reacts to a provider-confirmed `CONTEXT_WINDOW_EXCEEDED`: it bypasses the normal threshold and retention policy, attempts one maximal balanced head reduction, and authorizes a retry only after the surface replacement generation advances. Cancellation stays authoritative throughout. @@ -143,6 +143,7 @@ The transaction validates the surface span and the durable lock, appends `compac | File | Role | |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `BasicCompactionEngine`, automatic listeners, entry-point dispatch | +| [`src/answered-route.ts`](src/answered-route.ts) | Host-only projection of the provider/model recorded on the latest assistant message | | [`src/region.ts`](src/region.ts) | Retention selection and the shared bracket-first compaction transaction | | [`src/summarizer.ts`](src/summarizer.ts) | Default `ctx.llm.stream()` summarization, checkpoint framing, safe-summary projection | | [`src/config.ts`](src/config.ts) | Load-time validation and routed-model policy resolution | diff --git a/packages/compaction/compaction-basic/README.zh.md b/packages/compaction/compaction-basic/README.zh.md index 6553577ebe..d48b446708 100644 --- a/packages/compaction/compaction-basic/README.zh.md +++ b/packages/compaction/compaction-basic/README.zh.md @@ -43,7 +43,7 @@ kind: "package-reference" - name: '@deepseek-ai/dsh-command-compact' ``` -你可以通过观察会话越过本来会溢出的位置继续工作、以及运行 `/compact` 立即压缩一次来确认成功。如果组合缺少 LLM、会话存储或 token 测量,插件会加载失败。同一个后端可以服务上下文大小不同的模型;用按模型覆盖为每条路由设置各自的阈值与保留: +你可以通过观察会话越过本来会溢出的位置继续工作、以及运行 `/compact` 立即压缩一次来确认成功。如果组合缺少 LLM、会话存储、会话投影或 token 测量,插件会加载失败。同一个后端可以服务上下文大小不同的模型;用按模型覆盖为每条路由设置各自的阈值与保留: ```yaml - name: '@deepseek-ai/dsh-compaction-basic' @@ -118,7 +118,7 @@ kind: "package-reference" ### 自动触发与溢出恢复 -`agent/request` listener 等待路由 listener 选定目标,再在新 header 记入日志前检查其压力。它直接使用 `compactPressure`,因为 `compactIfNeeded` 读取的是已提交的 header;两条路径都通过 `summarize()` 生成摘要;它先读取 `ctx.tokenMeter.answeredRoute()`,再读取已提交的 header,因为失败的请求已经替换了该 header。 +`agent/request` listener 等待路由 listener 选定目标,再在新 header 记入日志前检查其压力。它直接使用 `compactPressure`,因为 `compactIfNeeded` 读取的是已提交的 header;两条路径都通过 `summarize()` 生成摘要;它先读取最新助手消息上记录的路由,再读取已提交的 header,因为失败的请求已经替换了该 header。仅供宿主使用的会话投影 `compactionAnsweredRoute` 保存这对提供方/模型,因此恢复的会话从检查点读取它;插件在构造时注册该投影,卸载时释放。 当 `auto: true` 时,串行 `agent/pre-step` listener 会在请求派生前检查压力:它通过 `ctx.tokenMeter` 为最新持久路由请求 envelope 定价,当压力越过路由模型的阈值时,先剪枝,再在保留已定价近期尾部的同时摘要最旧的平衡范围。每个选定范围都从第一个不是 `system/message` 的 surface 节点开始,因此位于 surface 节点 0 的系统提示词永不会被遮蔽;由历史内提示词更新追加的后续 `system/message` 是普通历史,范围可以遮蔽它,agent loop(智能体循环)的投影随后会在二者文本不同时用当前提示词替换节点 0([决策规则](../../core/agent-loop/README.zh.md#understand-the-implementation))。`agent/request-error` listener 响应提供方确认的 `CONTEXT_WINDOW_EXCEEDED`:它绕过常规阈值与保留策略,尝试一次最大平衡头部缩减,并且只在表层替换 generation 前进后才授权重试。取消全程保持最终决定权。 @@ -143,6 +143,7 @@ kind: "package-reference" | 文件 | 职责 | |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`BasicCompactionEngine`、自动 listener、入口点分发 | +| [`src/answered-route.ts`](src/answered-route.ts) | 仅供宿主使用的投影,保存最新助手消息上记录的提供方/模型 | | [`src/region.ts`](src/region.ts) | 保留选择与共享的先记录标记压缩事务 | | [`src/summarizer.ts`](src/summarizer.ts) | 默认 `ctx.llm.stream()` 摘要、检查点框定、安全摘要投影 | | [`src/config.ts`](src/config.ts) | 加载时验证与路由模型策略解析 | diff --git a/packages/compaction/compaction-basic/package.json b/packages/compaction/compaction-basic/package.json index 8597154c9d..9aec2bef16 100644 --- a/packages/compaction/compaction-basic/package.json +++ b/packages/compaction/compaction-basic/package.json @@ -39,6 +39,7 @@ "@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-token-meter": "workspace:*" }, "peerDependenciesMeta": { @@ -49,7 +50,8 @@ "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", - "@deepseek-ai/schemastery": "workspace:~" + "@deepseek-ai/schemastery": "workspace:~", + "zod": "4.6.6" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/compaction/compaction-basic/src/answered-route.ts b/packages/compaction/compaction-basic/src/answered-route.ts new file mode 100644 index 0000000000..8de709c6ab --- /dev/null +++ b/packages/compaction/compaction-basic/src/answered-route.ts @@ -0,0 +1,27 @@ +/** + * Host-only Session projection of the route that produced the latest assistant message. + * + * @module @deepseek-ai/dsh-compaction-basic/answered-route + */ + +import { z } from 'zod' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' + +/** Provider/model pair recorded on the latest assistant message; `null` before the first one. */ +export type AnsweredRoute = { provider: string; model: string } | null + +/** + * Fold of every `assistant/message` source. A request that ends without an + * assistant message, such as one the provider rejects, leaves the state unchanged. + */ +export const answeredRouteProjectionDefinition = { + key: 'compactionAnsweredRoute', + stateVersion: 1, + stateSchema: z.object({ provider: z.string(), model: z.string() }).strict().nullable(), + init: (): AnsweredRoute => null, + apply: (state, event) => { + if (event.type !== 'assistant/message') return state + const { provider, model } = event.data.message.source + return state?.provider === provider && state.model === model ? state : { provider, model } + }, +} satisfies ProjectionDefinition<'compactionAnsweredRoute', AnsweredRoute> diff --git a/packages/compaction/compaction-basic/src/index.ts b/packages/compaction/compaction-basic/src/index.ts index e53770030b..dc361d8f5e 100644 --- a/packages/compaction/compaction-basic/src/index.ts +++ b/packages/compaction/compaction-basic/src/index.ts @@ -4,17 +4,20 @@ * @module @deepseek-ai/dsh-compaction-basic */ -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { CompactionEngine, ManualCompactionError } from '@deepseek-ai/dsh-compaction' import type { CompactionResult, CompactionTrigger } from '@deepseek-ai/dsh-compaction' import type { EpochHeader, Session, SessionSeq } from '@deepseek-ai/dsh-session' +import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import type { CommandId } from '@deepseek-ai/dsh-commands/types' // Type-only: makes the optional sibling service available to `ctx.get()`. import type {} from '@deepseek-ai/dsh-compaction-tool-result-pruner' +import { answeredRouteProjectionDefinition } from './answered-route.ts' +import type { AnsweredRoute } from './answered-route.ts' import { resolveCompactSpec, resolveConfig, @@ -68,17 +71,17 @@ function reservedCompletionTokens(header: EpochHeader, defaultMaxTokens: number /** * Resolve the route that summarizes the conversation and selects its policy - * override. The route that last answered has held this history; the latest - * header may name a route whose only request overflowed. + * override. The route that last answered already accepted this history; the + * latest header may name a route whose only request overflowed. * @param agent - supplies the latest header and the live fallback options. - * @param answered - route of the request that produced the latest assistant message. + * @param answered - route recorded on the latest assistant message; `null` before the first one. * @returns the first complete route among `answered`, the latest header, and the agent options. */ function conversationTarget( agent: Agent, - answered: SummaryRoute | undefined, + answered: AnsweredRoute, ): SummaryRoute | undefined { - return completeRoute(answered) ?? routedTarget(agent.session) ?? completeRoute(agent.options) + return completeRoute(answered ?? undefined) ?? routedTarget(agent.session) ?? completeRoute(agent.options) } const thresholdRatioSchema = z.number() @@ -114,7 +117,7 @@ const modelPolicy: z = z.object({ * token meter. */ export class BasicCompactionEngine extends CompactionEngine { - static inject = ['llm', 'tokenMeter', 'sessions'] + static inject = ['llm', 'tokenMeter', 'sessions', 'sessionProjections'] static Config: z = z.object({ thresholdRatio: thresholdRatioSchema, @@ -136,13 +139,21 @@ export class BasicCompactionEngine extends CompactionEngine { private readonly warnedPressureConfigTargets = new Set() private readonly overflowRetries = new WeakMap() private readonly overflowAgents = new WeakMap() + /** Registered at construction; `summarize()` awaits it, so no read precedes readiness. */ + private readonly answeredRoute: Promise> constructor(ctx: Context, config: BasicCompactionConfig = {}) { super(ctx) this.config = resolveConfig(config) + this.answeredRoute = this.ctx.sessionProjections.register(answeredRouteProjectionDefinition) if (this.config.auto) this._registerAutomaticCompaction() } + /** Fail plugin activation when the answered-route projection cannot register. */ + protected async [Service.init](): Promise { + await this.answeredRoute + } + /** * Register between-step pressure, model-switch pressure, and request-overflow * recovery. Pre-step and overflow listeners dispatch through `compactIfNeeded`; @@ -265,9 +276,9 @@ export class BasicCompactionEngine extends CompactionEngine { * Summarize the replayed conversation region through a direct one-shot * `ctx.llm.stream()` call whose prefix reuses the conversation's own system * prompt, tools, and messages so the provider's KV cache is not invalidated. - * Without a configured summary target the call goes to the route that - * produced the latest assistant message, then the latest request header, - * then the agent options. A model selected for a later request is not used. + * Without a configured summary target the call goes to the route recorded + * on the latest assistant message, then the latest request header, then the + * agent options. A model selected for a later request is not used. * Override this sole hook for a template or remote summarizer. * @param input - replayed conversation prefix (system, tools, and leading messages) to condense. * @param agent - supplies the session history, fallback model, and session id. @@ -279,7 +290,7 @@ export class BasicCompactionEngine extends CompactionEngine { agent: Agent, signal?: AbortSignal, ): Promise { - const target = conversationTarget(agent, this.ctx.tokenMeter.answeredRoute(agent.session)) + const target = conversationTarget(agent, (await this.answeredRoute).stateOf(agent.session)) const config = target === undefined ? this.config : resolveTargetPolicy(this.config, target) diff --git a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts index 6f7ef9ca7c..c87adeb2ed 100644 --- a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts +++ b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts @@ -4,6 +4,7 @@ import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' import BasicCompactionEngine from '@deepseek-ai/dsh-compaction-basic' import type { BasicCompactionConfig } from '@deepseek-ai/dsh-compaction-basic' import { selectCompactableRange } from '@deepseek-ai/dsh-compaction-basic/src/region.ts' +import { answeredRouteProjectionDefinition } from '@deepseek-ai/dsh-compaction-basic/src/answered-route.ts' import { frameSummary } from '@deepseek-ai/dsh-compaction-basic/src/summarizer.ts' import type { SummarizationInput, SummaryResult } from '@deepseek-ai/dsh-compaction-basic/src/summarizer.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -27,8 +28,9 @@ import type { StreamChunk, TokenUsage, } from '@deepseek-ai/dsh-llm' -import SessionStore, { Session, type SessionId, SessionSeq } from '@deepseek-ai/dsh-session' +import SessionStore, { Session, type SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import type { ProjectionCheckpoint } from '@deepseek-ai/dsh-session-projection' import TokenMeter from '@deepseek-ai/dsh-token-meter' import { agentEvents, type Agent, type RequestErrorAction } from '@deepseek-ai/dsh-agent' import ToolResultPruner from '@deepseek-ai/dsh-compaction-tool-result-pruner' @@ -1581,6 +1583,79 @@ describe('default one-shot summarizer', () => { expect(unanswered.lastOptions).toBeUndefined() }) + it.each([false, true])('restores the answered route from a JSON checkpoint and folds only the suffix (answer in suffix: %s)', async (answerInSuffix) => { + const { ctx, compact } = await summarizerHarness([{ type: 'text', text: 'summary' }]) + ctx.llm.registerAdapter(['later'], new ScriptedAdapter([{ type: 'text', text: 'later summary' }])) + const session = conversation(1) + const checkpoint = JSON.parse(JSON.stringify(ctx.sessionProjections.checkpoint(session))) as ProjectionCheckpoint + expect(checkpoint['compactionAnsweredRoute']).toMatchObject({ ver: 1, val: { provider: MODEL, model: MODEL } }) + const cut = session.seq + session.append('step/start', { turn: 2, step: 1 }) + session.append('request/header', { header: { config: { provider: 'later', model: 'later' } }, reason: 'change' }) + if (answerInSuffix) { + session.append('assistant/message', { + stream: [], + turn: 2, + step: 1, + message: createMessage({ + role: 'assistant', + content: [{ type: 'text', text: 'later answer' }], + source: { kind: 'model', provider: 'later', model: 'later' }, + }), + }, { surfaceOp: 'append' }) + } + const events = session.snapshotEvents() + const restored = Session.fromRestore(session.id, events, session.header, SessionLogOffset(0), 'detached') + const apply = vi.spyOn(answeredRouteProjectionDefinition, 'apply') + onTestFinished(() => { apply.mockRestore() }) + ctx.sessionProjections.hydrate(restored, checkpoint, events.slice(cut), cut) + expect(apply.mock.calls.map(([, event]) => event.seq)).toEqual(events.slice(cut).map(event => event.seq)) + + const expected = answerInSuffix ? 'later' : MODEL + await expect(compact.runSummarize(promptInput('history'), agent(restored))).resolves + .toMatchObject({ provider: expected, model: expected }) + await expect(compact.runSummarize(promptInput('history'), agent(session))).resolves + .toMatchObject({ provider: expected, model: expected }) + }) + + it('keeps the answered-route state reference for unrelated events and an unchanged route', () => { + const { init, apply } = answeredRouteProjectionDefinition + const events = conversation(2).snapshotEvents() + const answers = events.filter(event => event.type === 'assistant/message') + const first = apply(init(), answers[0]!) + expect(first).toEqual({ provider: MODEL, model: MODEL }) + for (const event of events) expect(apply(first, event)).toBe(first) + expect(apply(null, events.find(event => event.type === 'request/header')!)).toBeNull() + expect(answers).toHaveLength(2) + }) + + it('registers the answered-route projection with the plugin and releases it on unload', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(LlmRuntime) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(TokenMeter) + const fiber = await ctx.plugin(BasicCompactionEngine, { auto: false }) + expect(ctx.sessionProjections.checkpoint(conversation(1))).toHaveProperty('compactionAnsweredRoute') + + await fiber.dispose() + expect(ctx.sessionProjections.checkpoint(conversation(2))).not.toHaveProperty('compactionAnsweredRoute') + }) + + it('fails plugin activation when the answered-route projection cannot register', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(LlmRuntime) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(TokenMeter) + await ctx.sessionProjections.register({ ...answeredRouteProjectionDefinition, stateVersion: 2 }) + + await expect(ctx.plugin(BasicCompactionEngine, { auto: false })).rejects.toThrow('compactionAnsweredRoute') + expect(ctx.get('compaction')).toBeUndefined() + }) + it('records the model actually dispatched after one-shot stream routing', async () => { const { ctx, compact } = await summarizerHarness([{ type: 'text', text: 'unused' }]) const routedAdapter = new ScriptedAdapter([{ type: 'text', text: 'routed summary' }]) diff --git a/packages/compaction/compaction-basic/tsconfig.json b/packages/compaction/compaction-basic/tsconfig.json index a9058935d2..e202df1cea 100644 --- a/packages/compaction/compaction-basic/tsconfig.json +++ b/packages/compaction/compaction-basic/tsconfig.json @@ -27,6 +27,9 @@ { "path": "../../core/session" }, + { + "path": "../../session/session-projection" + }, { "path": "../../core/agent" }, diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 52adb4377c..eabb017513 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4340,12 +4340,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'session', description: 'Session whose committed usage and request capacity are read.' }], returns: 'context pressure; fields remain absent until their source events are recorded.', }, - { - signature: 'answeredRoute(session: Session): { provider: string; model: string } | undefined', - description: 'Read the route of the request that produced the latest assistant message. A request that failed before recording an assistant message leaves it unchanged.', - parameters: [{ name: 'session', description: 'Session whose durable history is read.' }], - returns: 'a detached provider/model pair, or `undefined` before any assistant message or when no request header preceded it.', - }, { signature: 'measure(session: Session, requestHeader?: EpochHeader): TokenMeasurement', description: 'Measure current request pressure and surface through the durable tail.\n\nThe effective envelope\'s routed provider/model selects the request-image pricing every node is priced under: a route whose adapter declares image pricing charges each retained image its visual tokens plus its model-visible text, while other routes keep the fixed heuristic. Provider usage is reused only when the latest successful call\'s canonical request envelope matches `requestHeader` and its total is no lower than that call\'s full route-priced anchor; otherwise the complete envelope and surface are repriced. The anchor includes all surface nodes immediately before the assistant message, including inputs admitted after step/start.\n\n`requestHeader` replaces the latest logged envelope for pressure and node pricing; the node set always describes the current session surface. Every call clones those positional nodes, so measurement is O(surface).', diff --git a/packages/llm/token-meter/README.i18n.yaml b/packages/llm/token-meter/README.i18n.yaml index 75f7363393..739fefb148 100644 --- a/packages/llm/token-meter/README.i18n.yaml +++ b/packages/llm/token-meter/README.i18n.yaml @@ -24,8 +24,8 @@ en: 58de3b364ab5af6b zh: c5440af43d321e56 /deepseek-ai-dsh-token-meter/use-this-package/session-projections: - en: 6d536694425152cb - zh: 285890e92af3ea58 + en: 880f4fde933fb526 + zh: 7990c753d756eb46 /deepseek-ai-dsh-token-meter/use-this-package/composition: en: 1a0b7f49e01cba08 zh: 666213a1024767c5 diff --git a/packages/llm/token-meter/README.md b/packages/llm/token-meter/README.md index dd9eefde13..e128f57e43 100644 --- a/packages/llm/token-meter/README.md +++ b/packages/llm/token-meter/README.md @@ -46,7 +46,7 @@ The measurement anchor includes the priced surface immediately before the succes ### Session projections -Token-meter registers three client-view projection units and one host-only unit through its required `ctx.sessionProjections` service. Host consumers call `ctx.tokenMeter.contextPressure(session)` to read the latest provider-reported prompt size and route capacity synchronously, and `ctx.tokenMeter.answeredRoute(session)` to read the provider/model of the request that produced the latest assistant message; the registration handle stays private. `tokenUsage` carries the complete durable log's `uncachedInputTokens`, `outputTokens`, `cacheReadTokens`, and `cacheWriteTokens`. A final assistant-message sample replaces streaming usage from the same attempt; `llm/retry-started` ends that replacement scope, so a retry in the same step contributes another billed attempt. `contextPressure` carries optional `pressureTokens` (the newest provider-reported prompt size), optional `projectedTokens` (what the next request's prompt would cost), and optional `contextWindow` from the newest `request/context` record. `contextBreakdown` carries heuristic `systemTokens`, `toolsTokens`, and `messageTokens` — the context's composition, not its provider-billed size. Unloading the plugin removes all four keys. The host-only `tokenMeasurement` state saves header references, the open step, and the latest successful call's usage and output price. It contains no message arrays, tool schemas, attachment data, or price caches. Invalid measurement history records only its first failed position; unrelated projection updates and checkpoints continue. `measure()` reports the original error at that event, before committing prices or advancing its cursor. State version 2 discards older measurement rows and rebuilds from the journal. +Token-meter registers three client-view projection units and one host-only unit through its required `ctx.sessionProjections` service. Host consumers call `ctx.tokenMeter.contextPressure(session)` to read the latest provider-reported prompt size and route capacity synchronously; the registration handle stays private. `tokenUsage` carries the complete durable log's `uncachedInputTokens`, `outputTokens`, `cacheReadTokens`, and `cacheWriteTokens`. A final assistant-message sample replaces streaming usage from the same attempt; `llm/retry-started` ends that replacement scope, so a retry in the same step contributes another billed attempt. `contextPressure` carries optional `pressureTokens` (the newest provider-reported prompt size), optional `projectedTokens` (what the next request's prompt would cost), and optional `contextWindow` from the newest `request/context` record. `contextBreakdown` carries heuristic `systemTokens`, `toolsTokens`, and `messageTokens` — the context's composition, not its provider-billed size. Unloading the plugin removes all four keys. The host-only `tokenMeasurement` state saves header references, the open step, and the latest successful call's usage and output price. It contains no message arrays, tool schemas, attachment data, or price caches. Invalid measurement history records only its first failed position; unrelated projection updates and checkpoints continue. `measure()` reports the original error at that event, before committing prices or advancing its cursor. State version 2 discards older measurement rows and rebuilds from the journal. Image offload reprices existing node identities while preserving prior usage anchors. The fixed reference heuristic excludes `offloaded` metadata, so an offload decision does not change `contextBreakdown` or the scalar heuristic total; route-aware measurement replaces the selected visual prices with placeholder text. diff --git a/packages/llm/token-meter/README.zh.md b/packages/llm/token-meter/README.zh.md index ba9e6ce8ee..a209e04ee3 100644 --- a/packages/llm/token-meter/README.zh.md +++ b/packages/llm/token-meter/README.zh.md @@ -46,7 +46,7 @@ const price = ctx.tokenMeter.estimateMessage(message) ### 会话投影 -token-meter 通过必需的 `ctx.sessionProjections` 服务注册三个客户端投影单元和一个仅供宿主使用的单元。Host 消费方调用 `ctx.tokenMeter.contextPressure(session)` 同步读取提供方报告的最新提示词规模和路由容量,调用 `ctx.tokenMeter.answeredRoute(session)` 读取产生最新助手消息的那次请求的提供方与模型;注册句柄保留在内部。`tokenUsage` 携带完整持久日志中的 `uncachedInputTokens`、`outputTokens`、`cacheReadTokens` 与 `cacheWriteTokens`。最终 assistant 消息样本会替换同一次尝试的流式用量;`llm/retry-started` 会结束该替换范围,因此同一步骤中的重试会贡献另一次计费用量。`contextPressure` 携带可选 `pressureTokens`(提供方报告的最新提示词规模)、可选 `projectedTokens`(下一个请求的提示词将花费多少)与来自最新一条 `request/context` 记录的可选 `contextWindow`。`contextBreakdown` 携带启发式 `systemTokens`、`toolsTokens` 与 `messageTokens`——上下文的构成,而非提供方计费规模。卸载插件会移除全部四个键。仅宿主使用的 `tokenMeasurement` 保存请求头引用、未结束的步骤,以及最近一次成功调用的用量和输出价格。它不保存消息数组、工具定义、附件数据或价格缓存。计量历史有误时,只记录首次失败的位置,其他投影更新和检查点仍可继续;`measure()` 在该事件处报告原有错误,不提交价格或推进读取位置。状态版本 2 会丢弃旧版计量记录,再从日志重建。 +token-meter 通过必需的 `ctx.sessionProjections` 服务注册三个客户端投影单元和一个仅供宿主使用的单元。Host 消费方调用 `ctx.tokenMeter.contextPressure(session)` 同步读取提供方报告的最新提示词规模和路由容量;注册句柄保留在内部。`tokenUsage` 携带完整持久日志中的 `uncachedInputTokens`、`outputTokens`、`cacheReadTokens` 与 `cacheWriteTokens`。最终 assistant 消息样本会替换同一次尝试的流式用量;`llm/retry-started` 会结束该替换范围,因此同一步骤中的重试会贡献另一次计费用量。`contextPressure` 携带可选 `pressureTokens`(提供方报告的最新提示词规模)、可选 `projectedTokens`(下一个请求的提示词将花费多少)与来自最新一条 `request/context` 记录的可选 `contextWindow`。`contextBreakdown` 携带启发式 `systemTokens`、`toolsTokens` 与 `messageTokens`——上下文的构成,而非提供方计费规模。卸载插件会移除全部四个键。仅宿主使用的 `tokenMeasurement` 保存请求头引用、未结束的步骤,以及最近一次成功调用的用量和输出价格。它不保存消息数组、工具定义、附件数据或价格缓存。计量历史有误时,只记录首次失败的位置,其他投影更新和检查点仍可继续;`measure()` 在该事件处报告原有错误,不提交价格或推进读取位置。状态版本 2 会丢弃旧版计量记录,再从日志重建。 图片省略重新计算现有节点的价格,同时保留此前的用量锚点。固定引用启发式规则不计入 `offloaded` 元数据,因此一次省略决定不改变 `contextBreakdown` 或标量启发式总量,按路由的测量则把所选图片的视觉价格换成占位文本价格。 diff --git a/packages/llm/token-meter/src/index.ts b/packages/llm/token-meter/src/index.ts index ff0a05b644..8b4f7fff94 100644 --- a/packages/llm/token-meter/src/index.ts +++ b/packages/llm/token-meter/src/index.ts @@ -127,19 +127,6 @@ export class TokenMeter extends Service { } } - /** - * Read the route of the request that produced the latest assistant message. - * A request that failed before recording an assistant message leaves it unchanged. - * @param session - Session whose durable history is read. - * @returns a detached provider/model pair, or `undefined` before any assistant message or when no request header preceded it. - */ - answeredRoute(session: Session): { provider: string; model: string } | undefined { - const { prices, measurement } = this._sync(session) - if (measurement.anchor === null) return undefined - const config = this._cachedHeader(prices, measurement.anchor.headerSeq)?.config - return config === undefined ? undefined : { provider: config.provider, model: config.model } - } - /** * Measure current request pressure and surface through the durable tail. * diff --git a/packages/llm/token-meter/tests/token-meter.spec.ts b/packages/llm/token-meter/tests/token-meter.spec.ts index 440031ed58..e4e7a6e0b3 100644 --- a/packages/llm/token-meter/tests/token-meter.spec.ts +++ b/packages/llm/token-meter/tests/token-meter.spec.ts @@ -389,40 +389,6 @@ describe('replay anchors and surface folds', () => { expect(switchedBack.surfaceDeltaTokens).toBe(0) }) - it('reports the route of the latest assistant message, unchanged by later unanswered headers', () => { - const service = meter() - const session = Session.create(brandString('answered-route')) - expect(service.answeredRoute(session)).toBeUndefined() - - appendHeader(session, header('alpha')) - expect(service.answeredRoute(session)).toBeUndefined() - - appendSuccessfulCall(session, header('alpha')) - expect(service.answeredRoute(session)).toEqual({ provider: 'mock', model: 'alpha' }) - - appendHeader(session, header('beta')) - expect(session.requestHeader()?.config.model).toBe('beta') - const unanswered = service.answeredRoute(session) - expect(unanswered).toEqual({ provider: 'mock', model: 'alpha' }) - expect(service.answeredRoute(session)).not.toBe(unanswered) - - appendSuccessfulCall(session, header('beta'), { turn: 1, step: 2 }) - expect(service.answeredRoute(session)).toEqual({ provider: 'mock', model: 'beta' }) - }) - - it('reports no answered route for an assistant message without a preceding header', () => { - const service = meter() - const session = Session.create(brandString('headerless-answer')) - session.append('step/start', { turn: 1, step: 1 }) - session.append('assistant/message', { - stream: [], - turn: 1, - step: 1, - message: createAssistantMessage({ content: [{ type: 'text', text: 'answer' }], source: { provider: 'mock', model: 'mock' } }), - }, { surfaceOp: 'append' }) - expect(service.answeredRoute(session)).toBeUndefined() - }) - it('invalidates usage for any canonical envelope change or explicit override', () => { const service = meter() const session = Session.create(brandString('envelope')) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 09d02a64d5..8fcfd9f5d9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7579,6 +7579,9 @@ importers: '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery + zod: + specifier: 4.6.6 + version: 4.6.6 devDependencies: '@deepseek-ai/cordis': specifier: workspace:~