dsh-context-compression-improved 0.10.4 → 0.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/$null +1 -0
- package/.agents/plans/improve/checklist.md +32 -0
- package/.agents/plans/improve/findings.md +102 -0
- package/.agents/plans/improve/spec.md +53 -0
- package/.agents/plans/improve/tasks.md +70 -0
- package/.gitattributes +2 -0
- package/.githooks/pre-push +37 -0
- package/.github/workflows/ci.yml +47 -0
- package/CHANGELOG.de.md +580 -0
- package/CHANGELOG.es.md +588 -0
- package/CHANGELOG.fr.md +576 -0
- package/CHANGELOG.it.md +577 -0
- package/CHANGELOG.ja.md +261 -0
- package/CHANGELOG.ko.md +254 -0
- package/CHANGELOG.md +549 -0
- package/CHANGELOG.ru.md +554 -0
- package/CHANGELOG.zh.md +238 -0
- package/CONTRIBUTING.md +22 -0
- package/README.de.md +96 -0
- package/README.es.md +96 -0
- package/README.fr.md +96 -0
- package/README.it.md +96 -0
- package/README.ja.md +102 -0
- package/README.ko.md +102 -0
- package/README.md +110 -15
- package/README.ru.md +96 -0
- package/README.zh.md +104 -14
- package/SECURITY.md +18 -0
- package/THIRD_PARTY_NOTICES.md +7 -25
- package/assets/board.png +0 -0
- package/assets/context.png +0 -0
- package/docs/assets/context-compression-selector-profiles.jpg +0 -0
- package/docs/assets/context-compression-selector-settings.png +0 -0
- package/docs/compat-0.1.5-report.md +77 -0
- package/docs/installation.de.md +104 -0
- package/docs/installation.es.md +104 -0
- package/docs/installation.fr.md +104 -0
- package/docs/installation.it.md +104 -0
- package/docs/installation.ja.md +78 -0
- package/docs/installation.ko.md +78 -0
- package/docs/installation.md +103 -0
- package/docs/installation.ru.md +104 -0
- package/docs/installation.zh.md +100 -0
- package/docs/repair-log.md +657 -0
- package/eslint.config.js +30 -0
- package/package.json +113 -126
- package/packages/selector/LICENSE +21 -0
- package/packages/selector/README.md +26 -0
- package/packages/selector/README.zh.md +24 -0
- package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
- package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
- package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
- package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
- package/packages/selector/lib/style.css +350 -0
- package/packages/selector/package.json +178 -0
- package/packages/selector/screenshots.json +3 -0
- package/packages/selector/src/client/CompressionProfileControls.tsx +319 -0
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +87 -0
- package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
- package/packages/selector/src/client/EstimatorControls.tsx +277 -0
- package/packages/selector/src/client/bridge-scope.ts +125 -0
- package/packages/selector/src/client/decode.ts +64 -0
- package/packages/selector/src/client/fab-pos.ts +71 -0
- package/packages/selector/src/client/index.ts +434 -0
- package/packages/selector/src/client/locales/de.ts +160 -0
- package/packages/selector/src/client/locales/es.ts +160 -0
- package/packages/selector/src/client/locales/fr.ts +160 -0
- package/packages/selector/src/client/locales/it.ts +160 -0
- package/packages/selector/src/client/locales/ja.ts +160 -0
- package/packages/selector/src/client/locales/ko.ts +160 -0
- package/packages/selector/src/client/locales/ru.ts +160 -0
- package/packages/selector/src/client/locales.ts +320 -0
- package/packages/selector/src/client/monitor-fab.ts +431 -0
- package/packages/selector/src/client/preset-options.ts +88 -0
- package/packages/selector/src/client/savings-card.tsx +269 -0
- package/packages/selector/src/client/scope-face.ts +24 -0
- package/packages/selector/src/client/settings-section.tsx +149 -0
- package/packages/selector/src/compat/host-generation.ts +96 -0
- package/packages/selector/src/compat/llm-messages.ts +50 -0
- package/packages/selector/src/compat/settings-lease.ts +108 -0
- package/packages/selector/src/compat/tool-result.ts +91 -0
- package/packages/selector/src/css-modules.d.ts +6 -0
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
- package/packages/selector/src/estimator-catalog.ts +104 -0
- package/packages/selector/src/index.ts +890 -0
- package/packages/selector/src/invariant.ts +113 -0
- package/packages/selector/src/preset-overlay.ts +749 -0
- package/packages/selector/src/profiles.ts +451 -0
- package/packages/selector/src/pruner/content.ts +199 -0
- package/packages/selector/src/pruner/session.ts +97 -0
- package/packages/selector/src/pruner/state.ts +61 -0
- package/packages/selector/src/pruner/tuning.ts +23 -0
- package/packages/selector/src/pruner/types.ts +78 -0
- package/packages/selector/src/pruner.ts +2916 -0
- package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
- package/packages/selector/src/runtime/audit.ts +320 -0
- package/packages/selector/src/runtime/config.ts +800 -0
- package/packages/selector/src/runtime/custom-policy.ts +300 -0
- package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
- package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
- package/packages/selector/src/runtime/display-prefs.ts +98 -0
- package/packages/selector/src/runtime/measurement.ts +444 -0
- package/packages/selector/src/runtime/monitor.ts +310 -0
- package/packages/selector/src/runtime/panel-command.ts +213 -0
- package/packages/selector/src/runtime/reducers.ts +1755 -0
- package/packages/selector/src/runtime/retrieve.ts +505 -0
- package/packages/selector/src/runtime/savings-integral.ts +117 -0
- package/packages/selector/src/runtime/savings-projection.ts +229 -0
- package/packages/selector/src/runtime/savings-verify.ts +446 -0
- package/packages/selector/src/runtime/savings.ts +526 -0
- package/packages/selector/src/runtime/session-events.ts +30 -0
- package/packages/selector/src/runtime/session-file-decode.ts +523 -0
- package/packages/selector/src/runtime/stats-backfill.ts +541 -0
- package/packages/selector/src/runtime/stats-db.ts +492 -0
- package/packages/selector/src/runtime/stats-schema.ts +123 -0
- package/packages/selector/src/runtime/stats-sync.ts +307 -0
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tail-trim.ts +177 -0
- package/packages/selector/src/runtime/token-count.ts +72 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
- package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
- package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
- package/packages/selector/src/runtime/tokenpilot/dedup.ts +82 -0
- package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/tokenpilot/locator.ts +129 -0
- package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
- package/packages/selector/src/runtime/tool-names.ts +36 -0
- package/packages/selector/src/runtime/toolclass.ts +103 -0
- package/packages/selector/src/runtime/types.ts +368 -0
- package/packages/selector/src/runtime/value.ts +48 -0
- package/packages/selector/src/settings-bridge.ts +175 -0
- package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
- package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
- package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
- package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
- package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
- package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
- package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
- package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
- package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
- package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
- package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
- package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
- package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
- package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
- package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
- package/packages/selector/tests/profiles.client.spec.tsx +436 -0
- package/packages/selector/tests/ptc-custom-write.client.spec.ts +86 -0
- package/packages/selector/tests/public/package-contract.client.spec.ts +86 -0
- package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
- package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
- package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
- package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
- package/packages/selector/tests/runtime/audit.spec.ts +275 -0
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
- package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
- package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
- package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
- package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
- package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
- package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
- package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
- package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
- package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
- package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
- package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
- package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
- package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
- package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
- package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
- package/packages/selector/tests/runtime/ptc-profile.spec.ts +133 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2795 -0
- package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
- package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
- package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
- package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
- package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
- package/packages/selector/tests/runtime/savings.spec.ts +139 -0
- package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
- package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
- package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
- package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
- package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
- package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
- package/packages/selector/tests/runtime/stats-backfill.spec.ts +350 -0
- package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
- package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
- package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
- package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
- package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
- package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
- package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
- package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +121 -0
- package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
- package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
- package/packages/selector/tests/runtime/value.spec.ts +23 -0
- package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +724 -0
- package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
- package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
- package/packages/selector/tests/support/mock-adapter.ts +37 -0
- package/packages/selector/tests/support/ui-primitives.tsx +34 -0
- package/packages/selector/tsconfig.json +11 -0
- package/packages/selector/tsdown.client.config.ts +102 -0
- package/packages/selector/tsdown.config.ts +20 -0
- package/pnpm-workspace.yaml +76 -0
- package/screenshots.json +6 -3
- package/scripts/capture-profile-baseline.mjs +42 -0
- package/scripts/cell-browser-e2e.mjs +354 -0
- package/scripts/generate-tokenizer-fixtures.py +81 -0
- package/scripts/generate-vision-fixtures.py +208 -0
- package/scripts/hosts.mjs +79 -0
- package/scripts/packed-components-smoke.mjs +763 -0
- package/scripts/packed-install-e2e.mjs +1346 -0
- package/scripts/sync-hosts.mjs +174 -0
- package/scripts/toolclass-corpus-replay.mjs +281 -0
- package/scripts/verify-release.mjs +338 -0
- package/tests/TEST_INVENTORY.md +41 -0
- package/tsconfig.base.json +18 -0
- package/tsconfig.json +7 -0
- package/tsconfig.tests.json +15 -0
- package/vitest.built.config.ts +9 -0
- package/vitest.config.ts +54 -0
- /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
- /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
- /package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +0 -0
- /package/{lib → packages/selector/lib}/client.d.ts +0 -0
- /package/{lib → packages/selector/lib}/client.js +0 -0
- /package/{lib → packages/selector/lib}/index.d.ts +0 -0
- /package/{lib → packages/selector/lib}/index.js +0 -0
- /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
- /package/{lib → packages/selector/lib}/invariant.js +0 -0
- /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
- /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
- /package/{lib → packages/selector/lib}/pruner.js +0 -0
- /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
- /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
- /package/{lib → packages/selector/lib}/tool-result.js +0 -0
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Current-session recovery tool for context-compression placeholders.
|
|
3
|
+
*
|
|
4
|
+
* It reads the immutable append-only event cited by a `session://.../event/N`
|
|
5
|
+
* reference. The tool never reads the replacement surface as the source of
|
|
6
|
+
* truth and never crosses into another Session.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-context-compression-improved-runtime/retrieve
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
12
|
+
import z from '@deepseek-ai/schemastery'
|
|
13
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
14
|
+
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
|
|
15
|
+
import type {} from '@deepseek-ai/dsh-system-prompt'
|
|
16
|
+
import {
|
|
17
|
+
parseTailTrimRef,
|
|
18
|
+
validatePublishedTailTrim,
|
|
19
|
+
type PublishedTailTrim,
|
|
20
|
+
} from './tail-trim.ts'
|
|
21
|
+
import { sessionEvents } from './session-events.ts'
|
|
22
|
+
import { getSavingsLedger } from './savings.ts'
|
|
23
|
+
import { claimOffset } from './stats-sync.ts'
|
|
24
|
+
import { viewToolResult } from '../compat/tool-result.ts'
|
|
25
|
+
import { PTC_BINDING_NOTE, RUNTIME_TOOL_NAMES } from './tool-names.ts'
|
|
26
|
+
|
|
27
|
+
export const name = 'context-compression-retrieve'
|
|
28
|
+
export const inject = ['tools', 'systemPrompt']
|
|
29
|
+
|
|
30
|
+
/** Maximum text returned by one recovery call. */
|
|
31
|
+
export interface Config {
|
|
32
|
+
/** Hard response bound in Unicode code points. Defaults to 12000. */
|
|
33
|
+
maxChars?: number
|
|
34
|
+
/** Maximum source text inspected by one call. Defaults to 250000. */
|
|
35
|
+
maxScanChars?: number
|
|
36
|
+
/** Maximum query length in Unicode code points. Defaults to 256. */
|
|
37
|
+
maxQueryChars?: number
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Loader schema for the recovery tool's bounded runtime configuration. */
|
|
41
|
+
export const Config: z<Config> = z.object({
|
|
42
|
+
maxChars: z.number().step(1).min(1).default(12_000),
|
|
43
|
+
maxScanChars: z.number().step(1).min(1).default(250_000),
|
|
44
|
+
maxQueryChars: z.number().step(1).min(1).default(256),
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/
|
|
48
|
+
const MAX_LINES = 1_000
|
|
49
|
+
const DEFAULT_MAX_CHARS = 12_000
|
|
50
|
+
const DEFAULT_MAX_SCAN_CHARS = 250_000
|
|
51
|
+
const DEFAULT_MAX_QUERY_CHARS = 256
|
|
52
|
+
const TRUNCATION_MARKER = `\n[${RUNTIME_TOOL_NAMES.RETRIEVE} output truncated; reported lines describe the selected source range]\n`
|
|
53
|
+
const PROMPT = 'When a compacted tool result contains a session://<session-id>/event/<seq> reference, '
|
|
54
|
+
+ `or TailTrim contains a session://<session-id>/tailtrim/<seq> reference, use ${RUNTIME_TOOL_NAMES.RETRIEVE} with that exact ref `
|
|
55
|
+
+ 'and a narrow line range or query if the omitted evidence is necessary. '
|
|
56
|
+
+ 'Prefer a query or a tight start_line/max_lines over re-reading the whole result: every recovery re-enters the context and is charged against the savings, so a targeted slice keeps the rest of the reduction. '
|
|
57
|
+
+ 'The returned event content comes from the append-only session log, which is the source of truth. '
|
|
58
|
+
+ PTC_BINDING_NOTE
|
|
59
|
+
|
|
60
|
+
const OUTPUT = {
|
|
61
|
+
schema: { type: 'string' as const },
|
|
62
|
+
render: (_args: unknown, value: string) => [{ type: 'text' as const, text: value }],
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Register the current-session recovery tool and its stable guidance.
|
|
67
|
+
*
|
|
68
|
+
* @param ctx Plugin context providing the tool registry and system prompt.
|
|
69
|
+
* @param config Optional response, scan, and query bounds.
|
|
70
|
+
*/
|
|
71
|
+
export function installContextCompressionRetrieve(ctx: Context, config: Config = {}): void {
|
|
72
|
+
const maxChars = resolvePositiveInteger('maxChars', config.maxChars, DEFAULT_MAX_CHARS)
|
|
73
|
+
const maxScanChars = resolvePositiveInteger(
|
|
74
|
+
'maxScanChars', config.maxScanChars, DEFAULT_MAX_SCAN_CHARS,
|
|
75
|
+
)
|
|
76
|
+
const maxQueryChars = resolvePositiveInteger(
|
|
77
|
+
'maxQueryChars', config.maxQueryChars, DEFAULT_MAX_QUERY_CHARS,
|
|
78
|
+
)
|
|
79
|
+
ctx.systemPrompt.section({ name: 'tool:context-compression-retrieve', order: 114, text: PROMPT })
|
|
80
|
+
ctx.tools.register(defineTool({
|
|
81
|
+
name: RUNTIME_TOOL_NAMES.RETRIEVE,
|
|
82
|
+
description: `Recover exact content from one compacted tool result or TailTrim group using its current-session session:// reference. ${PTC_BINDING_NOTE}`,
|
|
83
|
+
parameters: {
|
|
84
|
+
ref: { type: 'string', required: true, description: 'Exact session://<current-session-id>/event/<seq> or /tailtrim/<seq> reference from a placeholder.' },
|
|
85
|
+
query: { type: 'string', description: 'Optional case-insensitive text to search for inside the original result.' },
|
|
86
|
+
start_line: { type: 'integer', description: 'Optional 1-based first line for a direct slice. Defaults to 1.' },
|
|
87
|
+
max_lines: { type: 'integer', description: 'Maximum lines to return. Defaults to 200; maximum 1000.' },
|
|
88
|
+
},
|
|
89
|
+
output: OUTPUT,
|
|
90
|
+
isConcurrencySafe: () => true,
|
|
91
|
+
execute(args, exec) {
|
|
92
|
+
if (exec.agent === undefined) throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE} requires an agent session`)
|
|
93
|
+
const match = REF_PATTERN.exec(args.ref)
|
|
94
|
+
const tailTrimRef = parseTailTrimRef(args.ref)
|
|
95
|
+
if (match === null && tailTrimRef === null) {
|
|
96
|
+
throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: ref must be session://<session-id>/(event|tailtrim)/<seq>`)
|
|
97
|
+
}
|
|
98
|
+
const sessionId = match?.[1] ?? tailTrimRef?.sessionId
|
|
99
|
+
// 身份键一律用 session.id(与 pruner 落账/占位符 sourceRef 同键);旧版这里
|
|
100
|
+
// 用 exec.agent.id,两键不一致时抵消会记到另一本账上。
|
|
101
|
+
if (sessionId !== String(exec.agent.session.id)) {
|
|
102
|
+
throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: a compression reference may only read the caller's current session`)
|
|
103
|
+
}
|
|
104
|
+
if (tailTrimRef !== null) {
|
|
105
|
+
const sessionId = String(exec.agent.session.id)
|
|
106
|
+
return Promise.resolve(recoverTailTrim(
|
|
107
|
+
exec.agent.session,
|
|
108
|
+
args.ref,
|
|
109
|
+
tailTrimRef.manifestSeq,
|
|
110
|
+
args.query,
|
|
111
|
+
args.start_line,
|
|
112
|
+
args.max_lines,
|
|
113
|
+
{ maxChars, maxScanChars, maxQueryChars },
|
|
114
|
+
)).then((text: string) => {
|
|
115
|
+
// 节省统计:回读内容重新进入上下文 = 对该组原声称节省的抵消。
|
|
116
|
+
// 同 basis(chars/4 估算口径;retrieve 不持有精确 counter 身份,
|
|
117
|
+
// 分列不混算)经 foldRecall 折进源条目翻负;跨基退化带 sourceSeq 的收敛 offset。
|
|
118
|
+
const offsetTokens = Math.ceil(codePointLength(text) / 4)
|
|
119
|
+
getSavingsLedger().foldRecall(sessionId, tailTrimRef.manifestSeq, offsetTokens, 'characters', {
|
|
120
|
+
component: 'tailtrim-retrieve',
|
|
121
|
+
note: `tailtrim/${tailTrimRef.manifestSeq} 回读`,
|
|
122
|
+
})
|
|
123
|
+
// T6 接线:持久 offset claim(流水审计层);幂等键含 manifestSeq,
|
|
124
|
+
// 同源反复召回首次入账、重放去重(定键口径见 stats-sync 头注)。
|
|
125
|
+
claimOffset({
|
|
126
|
+
sessionId,
|
|
127
|
+
component: 'tailtrim-retrieve',
|
|
128
|
+
tokens: offsetTokens,
|
|
129
|
+
basis: 'characters',
|
|
130
|
+
sourceSeq: tailTrimRef.manifestSeq,
|
|
131
|
+
})
|
|
132
|
+
return text
|
|
133
|
+
})
|
|
134
|
+
}
|
|
135
|
+
const seq = Number(match?.[2])
|
|
136
|
+
const event = sessionEvents(exec.agent.session)[seq]
|
|
137
|
+
if (event?.type !== 'tool/result') {
|
|
138
|
+
throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: event ${String(seq)} is not a tool/result in the current session`)
|
|
139
|
+
}
|
|
140
|
+
const maxLines = resolveMaxLines(args.max_lines)
|
|
141
|
+
// Generation-gated triple view: content blocks / error flag / call id
|
|
142
|
+
// move together across the 0.1.x envelope and the flat 0.2.0 message.
|
|
143
|
+
const resultView = viewToolResult(event.data.message)
|
|
144
|
+
const scan = scanBlocks(resultView.blocks as ContentBlock[], maxScanChars)
|
|
145
|
+
const scannedLines = splitScannedLines(scan)
|
|
146
|
+
const lines = scannedLines.lines
|
|
147
|
+
const query = args.query
|
|
148
|
+
if (query !== undefined && exceedsCodePointLimit(query, maxQueryChars)) {
|
|
149
|
+
throw new Error(
|
|
150
|
+
`${RUNTIME_TOOL_NAMES.RETRIEVE}: query must be at most ${String(maxQueryChars)} Unicode code points`,
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
const selected = query === undefined || query === ''
|
|
154
|
+
? directSlice(lines, args.start_line ?? 1, maxLines, scan.complete, scannedLines.partialTail)
|
|
155
|
+
: querySlice(lines, query, maxLines, scan.complete, scannedLines.partialTail)
|
|
156
|
+
const total = scan.complete ? String(lines.length) : `at least ${String(lines.length)}`
|
|
157
|
+
const header = [
|
|
158
|
+
`source: ${args.ref}`,
|
|
159
|
+
`tool_call_id: ${resultView.callId}`,
|
|
160
|
+
`status: ${resultView.isError ? 'error' : 'completed'}`,
|
|
161
|
+
`lines: ${String(selected.start)}-${String(selected.end)} of ${total}`,
|
|
162
|
+
scan.complete ? '' : 'note: source scan limit reached; later lines were not inspected',
|
|
163
|
+
selected.partialLine === undefined
|
|
164
|
+
? ''
|
|
165
|
+
: `note: line ${String(selected.partialLine)} is a partial prefix ending at the source scan limit`,
|
|
166
|
+
selected.omitted
|
|
167
|
+
? query === undefined || query === ''
|
|
168
|
+
? 'note: additional source lines were omitted'
|
|
169
|
+
: 'note: additional matching or neighboring lines were omitted'
|
|
170
|
+
: '',
|
|
171
|
+
'--- original tool result ---',
|
|
172
|
+
].filter(Boolean).join('\n')
|
|
173
|
+
const output = `${header}\n${selected.text}`
|
|
174
|
+
const bounded = boundCodePoints(output, maxChars)
|
|
175
|
+
// 节省统计:retrieve 产物重新进入上下文 = 抵消(chars/4 估算口径);
|
|
176
|
+
// 同 basis 折进源条目翻负,R = boundCodePoints 后的实测值,跨基退化为
|
|
177
|
+
// 带 sourceSeq(event/N)的收敛 offset。落账键用 session.id 与 pruner 统一。
|
|
178
|
+
const offsetTokens = Math.ceil(codePointLength(bounded) / 4)
|
|
179
|
+
getSavingsLedger().foldRecall(String(exec.agent.session.id), seq, offsetTokens, 'characters', {
|
|
180
|
+
component: 'retrieve',
|
|
181
|
+
note: `event/${String(seq)} 回读`,
|
|
182
|
+
})
|
|
183
|
+
// T6 接线:持久 offset claim;幂等键 (session_id, 源事件绝对 seq, …)。
|
|
184
|
+
claimOffset({
|
|
185
|
+
sessionId: String(exec.agent.session.id),
|
|
186
|
+
component: 'retrieve',
|
|
187
|
+
tokens: offsetTokens,
|
|
188
|
+
basis: 'characters',
|
|
189
|
+
sourceSeq: seq,
|
|
190
|
+
})
|
|
191
|
+
return Promise.resolve(bounded)
|
|
192
|
+
},
|
|
193
|
+
}))
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function recoverTailTrim(
|
|
197
|
+
session: Parameters<typeof validatePublishedTailTrim>[0],
|
|
198
|
+
ref: string,
|
|
199
|
+
manifestSeq: number,
|
|
200
|
+
query: string | undefined,
|
|
201
|
+
startLine: number | undefined,
|
|
202
|
+
requestedMaxLines: number | undefined,
|
|
203
|
+
bounds: { readonly maxChars: number; readonly maxScanChars: number; readonly maxQueryChars: number },
|
|
204
|
+
): string {
|
|
205
|
+
const published = validatePublishedTailTrim(session, manifestSeq)
|
|
206
|
+
if (published === null || published.ref !== ref) {
|
|
207
|
+
throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: ref is not a valid published TailTrim group`)
|
|
208
|
+
}
|
|
209
|
+
if (query !== undefined && exceedsCodePointLimit(query, bounds.maxQueryChars)) {
|
|
210
|
+
throw new Error(
|
|
211
|
+
`${RUNTIME_TOOL_NAMES.RETRIEVE}: query must be at most ${String(bounds.maxQueryChars)} Unicode code points`,
|
|
212
|
+
)
|
|
213
|
+
}
|
|
214
|
+
const fixedHeader = [
|
|
215
|
+
`source: ${ref}`,
|
|
216
|
+
'kind: tailtrim-group',
|
|
217
|
+
`records: ${String(published.roots.length)}`,
|
|
218
|
+
'--- original tool group (jsonl) ---',
|
|
219
|
+
].join('\n')
|
|
220
|
+
const scanBudget = Math.max(0, bounds.maxScanChars - codePointLength(`${fixedHeader}\n`))
|
|
221
|
+
const scan = consumeChunks(renderGroupRecordChunks(published.roots), scanBudget)
|
|
222
|
+
const scannedLines = splitScannedLines(scan)
|
|
223
|
+
const maxLines = resolveMaxLines(requestedMaxLines)
|
|
224
|
+
const selected = query === undefined || query === ''
|
|
225
|
+
? directSlice(
|
|
226
|
+
scannedLines.lines,
|
|
227
|
+
startLine ?? 1,
|
|
228
|
+
maxLines,
|
|
229
|
+
scan.complete,
|
|
230
|
+
scannedLines.partialTail,
|
|
231
|
+
)
|
|
232
|
+
: querySlice(
|
|
233
|
+
scannedLines.lines,
|
|
234
|
+
query,
|
|
235
|
+
maxLines,
|
|
236
|
+
scan.complete,
|
|
237
|
+
scannedLines.partialTail,
|
|
238
|
+
)
|
|
239
|
+
const header = [
|
|
240
|
+
fixedHeader.split('\n').slice(0, 3).join('\n'),
|
|
241
|
+
scan.complete ? '' : 'note: source scan limit reached; later records were not inspected',
|
|
242
|
+
selected.omitted ? 'note: additional group records were omitted' : '',
|
|
243
|
+
'--- original tool group (jsonl) ---',
|
|
244
|
+
].filter(Boolean).join('\n')
|
|
245
|
+
return boundCodePoints(`${header}\n${selected.text}`, bounds.maxChars)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
interface ScanResult {
|
|
249
|
+
readonly text: string
|
|
250
|
+
readonly complete: boolean
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
interface ScannedLines {
|
|
254
|
+
readonly lines: readonly string[]
|
|
255
|
+
readonly partialTail: boolean
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
interface Selection {
|
|
259
|
+
readonly text: string
|
|
260
|
+
readonly start: number
|
|
261
|
+
readonly end: number
|
|
262
|
+
readonly omitted: boolean
|
|
263
|
+
readonly partialLine?: number
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function resolvePositiveInteger(name: string, value: number | undefined, fallback: number): number {
|
|
267
|
+
const resolved = value ?? fallback
|
|
268
|
+
if (!Number.isSafeInteger(resolved) || resolved <= 0) {
|
|
269
|
+
throw new TypeError(`tool-context-retrieve: ${name} must be a positive safe integer`)
|
|
270
|
+
}
|
|
271
|
+
return resolved
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function resolveMaxLines(value: number | undefined): number {
|
|
275
|
+
const resolved = value ?? 200
|
|
276
|
+
if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > MAX_LINES) {
|
|
277
|
+
throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: max_lines must be an integer from 1 to ${String(MAX_LINES)}`)
|
|
278
|
+
}
|
|
279
|
+
return resolved
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function scanBlocks(blocks: readonly ContentBlock[], maxChars: number): ScanResult {
|
|
283
|
+
return consumeChunks(renderBlockChunks(blocks), maxChars)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function* renderBlockChunks(blocks: readonly ContentBlock[]): Generator<string> {
|
|
287
|
+
let first = true
|
|
288
|
+
for (const block of blocks) {
|
|
289
|
+
if (!first) yield '\n'
|
|
290
|
+
first = false
|
|
291
|
+
if (block.type === 'text') yield block.text
|
|
292
|
+
else yield* jsonTokens(block)
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function* renderGroupRecordChunks(roots: PublishedTailTrim['roots']): Generator<string> {
|
|
297
|
+
let first = true
|
|
298
|
+
for (const root of roots) {
|
|
299
|
+
if (!first) yield '\n'
|
|
300
|
+
first = false
|
|
301
|
+
const message = root.data.message
|
|
302
|
+
yield* jsonTokens({
|
|
303
|
+
seq: root.seq,
|
|
304
|
+
type: root.type,
|
|
305
|
+
message: {
|
|
306
|
+
id: message.id,
|
|
307
|
+
role: message.role,
|
|
308
|
+
content: message.content,
|
|
309
|
+
source: message.source,
|
|
310
|
+
},
|
|
311
|
+
})
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function* jsonTokens(value: unknown): Generator<string> {
|
|
316
|
+
if (value === null) {
|
|
317
|
+
yield 'null'
|
|
318
|
+
return
|
|
319
|
+
}
|
|
320
|
+
switch (typeof value) {
|
|
321
|
+
case 'string':
|
|
322
|
+
yield '"'
|
|
323
|
+
for (const point of value) {
|
|
324
|
+
const quoted = jsonScalar(point)
|
|
325
|
+
yield quoted.slice(1, -1)
|
|
326
|
+
}
|
|
327
|
+
yield '"'
|
|
328
|
+
return
|
|
329
|
+
case 'number':
|
|
330
|
+
case 'boolean':
|
|
331
|
+
yield jsonScalar(value)
|
|
332
|
+
return
|
|
333
|
+
case 'object': {
|
|
334
|
+
if (Array.isArray(value)) {
|
|
335
|
+
yield '['
|
|
336
|
+
for (let index = 0; index < value.length; index++) {
|
|
337
|
+
if (index > 0) yield ','
|
|
338
|
+
yield* jsonTokens(value[index])
|
|
339
|
+
}
|
|
340
|
+
yield ']'
|
|
341
|
+
return
|
|
342
|
+
}
|
|
343
|
+
yield '{'
|
|
344
|
+
let first = true
|
|
345
|
+
for (const key in value) {
|
|
346
|
+
if (!Object.hasOwn(value, key)) continue
|
|
347
|
+
if (!first) yield ','
|
|
348
|
+
first = false
|
|
349
|
+
yield* jsonTokens(key)
|
|
350
|
+
yield ':'
|
|
351
|
+
yield* jsonTokens((value as Record<string, unknown>)[key])
|
|
352
|
+
}
|
|
353
|
+
yield '}'
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
default:
|
|
357
|
+
throw new TypeError(`${RUNTIME_TOOL_NAMES.RETRIEVE}: source content is not JSON-serializable`)
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function jsonScalar(value: string | number | boolean): string {
|
|
362
|
+
return JSON.stringify(value)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function consumeChunks(chunks: Iterable<string>, maxChars: number): ScanResult {
|
|
366
|
+
const output: string[] = []
|
|
367
|
+
let remaining = maxChars
|
|
368
|
+
for (const chunk of chunks) {
|
|
369
|
+
const prefix = codePointPrefix(chunk, remaining)
|
|
370
|
+
output.push(prefix.text)
|
|
371
|
+
remaining -= prefix.count
|
|
372
|
+
if (!prefix.complete) return { text: output.join(''), complete: false }
|
|
373
|
+
}
|
|
374
|
+
return { text: output.join(''), complete: true }
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function splitScannedLines(scan: ScanResult): ScannedLines {
|
|
378
|
+
const lines = scan.text.split('\n')
|
|
379
|
+
const partialTail = !scan.complete && !scan.text.endsWith('\n')
|
|
380
|
+
if (scan.text.endsWith('\n')) lines.pop()
|
|
381
|
+
return { lines, partialTail }
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function directSlice(
|
|
385
|
+
lines: readonly string[],
|
|
386
|
+
startLine: number,
|
|
387
|
+
maxLines: number,
|
|
388
|
+
scanComplete: boolean,
|
|
389
|
+
partialTail: boolean,
|
|
390
|
+
): Selection {
|
|
391
|
+
if (!Number.isSafeInteger(startLine) || startLine < 1) {
|
|
392
|
+
throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: start_line must be a positive safe integer`)
|
|
393
|
+
}
|
|
394
|
+
if (startLine > lines.length) {
|
|
395
|
+
const reason = scanComplete ? 'outside the source line range' : 'beyond the source scan limit'
|
|
396
|
+
throw new Error(`${RUNTIME_TOOL_NAMES.RETRIEVE}: start_line ${String(startLine)} is ${reason}`)
|
|
397
|
+
}
|
|
398
|
+
const startIndex = startLine - 1
|
|
399
|
+
const selected = lines.slice(startIndex, startIndex + maxLines)
|
|
400
|
+
return {
|
|
401
|
+
text: selected.join('\n'),
|
|
402
|
+
start: startIndex + 1,
|
|
403
|
+
end: startIndex + selected.length,
|
|
404
|
+
omitted: startIndex > 0 || startIndex + selected.length < lines.length || !scanComplete,
|
|
405
|
+
...partialTail && startIndex + selected.length === lines.length
|
|
406
|
+
? { partialLine: lines.length }
|
|
407
|
+
: {},
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function querySlice(
|
|
412
|
+
lines: readonly string[],
|
|
413
|
+
query: string,
|
|
414
|
+
maxLines: number,
|
|
415
|
+
scanComplete: boolean,
|
|
416
|
+
partialTail: boolean,
|
|
417
|
+
): Selection {
|
|
418
|
+
const needle = query.toLowerCase()
|
|
419
|
+
const chosen = new Set<number>()
|
|
420
|
+
let matched = false
|
|
421
|
+
let omitted = !scanComplete
|
|
422
|
+
for (let index = 0; index < lines.length; index++) {
|
|
423
|
+
const line = lines[index]
|
|
424
|
+
if (line === undefined || !line.toLowerCase().includes(needle)) continue
|
|
425
|
+
matched = true
|
|
426
|
+
for (let row = Math.max(0, index - 2); row <= Math.min(lines.length - 1, index + 2); row++) {
|
|
427
|
+
if (chosen.has(row)) continue
|
|
428
|
+
if (chosen.size >= maxLines) {
|
|
429
|
+
omitted = true
|
|
430
|
+
continue
|
|
431
|
+
}
|
|
432
|
+
chosen.add(row)
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
if (!matched) {
|
|
436
|
+
return {
|
|
437
|
+
text: scanComplete ? '[no matches]' : '[no matches within source scan limit]',
|
|
438
|
+
start: 0,
|
|
439
|
+
end: 0,
|
|
440
|
+
omitted,
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
const ordered = [...chosen].sort((a, b) => a - b)
|
|
444
|
+
const rendered: string[] = []
|
|
445
|
+
let previous = -2
|
|
446
|
+
let start = 0
|
|
447
|
+
let end = 0
|
|
448
|
+
for (const index of ordered) {
|
|
449
|
+
const line = lines[index]
|
|
450
|
+
if (line === undefined) continue
|
|
451
|
+
if (index > previous + 1) rendered.push('...')
|
|
452
|
+
rendered.push(`${String(index + 1)}: ${line}`)
|
|
453
|
+
if (start === 0) start = index + 1
|
|
454
|
+
end = index + 1
|
|
455
|
+
previous = index
|
|
456
|
+
}
|
|
457
|
+
return {
|
|
458
|
+
text: rendered.join('\n'),
|
|
459
|
+
start,
|
|
460
|
+
end,
|
|
461
|
+
omitted,
|
|
462
|
+
...partialTail && ordered.includes(lines.length - 1)
|
|
463
|
+
? { partialLine: lines.length }
|
|
464
|
+
: {},
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function boundCodePoints(text: string, maxChars: number): string {
|
|
469
|
+
const bounded = codePointPrefix(text, maxChars)
|
|
470
|
+
if (bounded.complete) return text
|
|
471
|
+
const marker = codePointPrefix(TRUNCATION_MARKER, maxChars)
|
|
472
|
+
if (!marker.complete) return marker.text
|
|
473
|
+
const body = codePointPrefix(text, maxChars - marker.count)
|
|
474
|
+
return body.text + marker.text
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function codePointPrefix(text: string, maxChars: number): {
|
|
478
|
+
readonly text: string
|
|
479
|
+
readonly count: number
|
|
480
|
+
readonly complete: boolean
|
|
481
|
+
} {
|
|
482
|
+
const output: string[] = []
|
|
483
|
+
let count = 0
|
|
484
|
+
for (const point of text) {
|
|
485
|
+
if (count >= maxChars) return { text: output.join(''), count, complete: false }
|
|
486
|
+
output.push(point)
|
|
487
|
+
count++
|
|
488
|
+
}
|
|
489
|
+
return { text: output.join(''), count, complete: true }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function exceedsCodePointLimit(text: string, limit: number): boolean {
|
|
493
|
+
let count = 0
|
|
494
|
+
for (const _point of text) {
|
|
495
|
+
count++
|
|
496
|
+
if (count > limit) return true
|
|
497
|
+
}
|
|
498
|
+
return false
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function codePointLength(text: string): number {
|
|
502
|
+
let count = 0
|
|
503
|
+
for (const _point of text) count++
|
|
504
|
+
return count
|
|
505
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 按 call 积分器(spec T15/T16)——"真节省"口径。
|
|
3
|
+
*
|
|
4
|
+
* 定义:真节省 = Σ_每次call(该次基线输入 − 实际输入)。存量(delta, observeActive
|
|
5
|
+
* 收敛)回答"现在省多少";积分把每个 fresh 边界的存量净快照累加成跨重启的
|
|
6
|
+
* "累计(按 N 次 call)"。召回不追溯翻账:召回前的 call 真省过钱,样本保留;
|
|
7
|
+
* 召回后存量转负,后续采样自然把积分往下拉——前向口径,历史样本永不改写。
|
|
8
|
+
*
|
|
9
|
+
* 采样点:pruneSession stage='fresh' 的 recordUsage 同点(pruner 接线行,本
|
|
10
|
+
* 模块不重做任何测量)。boundarySeq = 采样时刻事件日志的最大绝对 seq——每完成
|
|
11
|
+
* 一次请求日志必追加(assistant/message 等),相邻两次 fresh 采样之间 maxSeq
|
|
12
|
+
* 单调递增,天然构成 per-call 幂等键;同 seq 重放被 claims 主键吸收。
|
|
13
|
+
*
|
|
14
|
+
* 省钱口径(T16):cached/uncached 分权——cachedInput×inputCacheHit +
|
|
15
|
+
* uncachedInput×inputCacheMiss(官方定价目录,定点 bigint,零浮点)。无定价
|
|
16
|
+
* 路由(非 deepseek-official 官方公网/未知模型)返回 null,面板仅 token 口径。
|
|
17
|
+
* 拆分规则:cacheReadTokens = 命中数;uncached = inputTokens − cacheRead
|
|
18
|
+
* (负值截 0)。首 call 无 usage 报告时照常采样存量(calls 照计,拆分记 0)。
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-context-compression-improved/runtime/savings-integral
|
|
21
|
+
*/
|
|
22
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
23
|
+
import {
|
|
24
|
+
decimalRateNanoUnits,
|
|
25
|
+
type OfficialDeepSeekPriceRecord,
|
|
26
|
+
} from './deepseek-official-pricing.ts'
|
|
27
|
+
import { sessionEvents } from './session-events.ts'
|
|
28
|
+
import { recordIntegralSample } from './stats-sync.ts'
|
|
29
|
+
|
|
30
|
+
/** 一次 fresh 边界采样的输入(测量由调用方完成,本模块只定键、拆分、落库)。 */
|
|
31
|
+
export interface IntegralSampleInput {
|
|
32
|
+
sessionId: string
|
|
33
|
+
session: Session
|
|
34
|
+
/** 内存账本当前存量净额(snapshot(sessionId).net,双 basis 分列)。 */
|
|
35
|
+
net: { exact: number; estimated: number }
|
|
36
|
+
/** 该边界读到的上一已完成请求官方 usage;首 call 缺报时 undefined。 */
|
|
37
|
+
usage?: { inputTokens?: number; cacheReadTokens?: number } | undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 采样时刻事件日志的最大绝对 seq;空日志(无从定键)返回 undefined。 */
|
|
41
|
+
export function latestEventSeq(session: Session): number | undefined {
|
|
42
|
+
let max: number | undefined
|
|
43
|
+
for (const event of sessionEvents(session)) {
|
|
44
|
+
const seq = Number(event.seq)
|
|
45
|
+
if (Number.isFinite(seq)) max = max === undefined ? seq : Math.max(max, seq)
|
|
46
|
+
}
|
|
47
|
+
return max
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** usage 拆分:cacheRead = 命中;uncached = input − cacheRead(负截 0);非法值记 0。 */
|
|
51
|
+
export function splitCachedUncached(usage: IntegralSampleInput['usage']): { cachedInput: number; uncachedInput: number } {
|
|
52
|
+
const cached = typeof usage?.cacheReadTokens === 'number' && Number.isFinite(usage.cacheReadTokens) && usage.cacheReadTokens > 0
|
|
53
|
+
? Math.trunc(usage.cacheReadTokens)
|
|
54
|
+
: 0
|
|
55
|
+
const input = typeof usage?.inputTokens === 'number' && Number.isFinite(usage.inputTokens) && usage.inputTokens > 0
|
|
56
|
+
? Math.trunc(usage.inputTokens)
|
|
57
|
+
: 0
|
|
58
|
+
return { cachedInput: cached, uncachedInput: Math.max(0, input - cached) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** fresh 边界采样入口:定键 → 拆分 → 经 stats-sync 幂等落库;空日志静默跳过。 */
|
|
62
|
+
export function sampleIntegralBoundary(input: IntegralSampleInput): void {
|
|
63
|
+
const boundarySeq = latestEventSeq(input.session)
|
|
64
|
+
if (boundarySeq === undefined) return
|
|
65
|
+
const { cachedInput, uncachedInput } = splitCachedUncached(input.usage)
|
|
66
|
+
recordIntegralSample({
|
|
67
|
+
sessionId: input.sessionId,
|
|
68
|
+
boundarySeq,
|
|
69
|
+
netExact: input.net.exact,
|
|
70
|
+
netEstimated: input.net.estimated,
|
|
71
|
+
cachedInput,
|
|
72
|
+
uncachedInput,
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 定价目录单位(每 1M tokens)下的双科目省钱估计;记录缺有效费率 = null。 */
|
|
77
|
+
export interface IntegralMoneyEstimate {
|
|
78
|
+
/** 定点十进制(主币种单位),格式同定价模块 femto 渲染。 */
|
|
79
|
+
decimal: string
|
|
80
|
+
/** 原始定点整数(femto 主币种单位),供聚合而不丢精度。 */
|
|
81
|
+
femtoUnits: string
|
|
82
|
+
currency: 'USD' | 'CNY'
|
|
83
|
+
band: 'peak' | 'off-peak'
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 省钱估计(T16):cached 走 inputCacheHit、uncached 走 inputCacheMiss,
|
|
88
|
+
* femto = tokens × nanoRate(与定价模块 amountFor 同构,输出侧不计——
|
|
89
|
+
* 积分口径只对输入省钱)。费率不可解析(理论上目录内不会)返回 null。
|
|
90
|
+
*/
|
|
91
|
+
export function estimateIntegralMoney(input: {
|
|
92
|
+
cachedInput: number
|
|
93
|
+
uncachedInput: number
|
|
94
|
+
record: OfficialDeepSeekPriceRecord
|
|
95
|
+
}): IntegralMoneyEstimate | null {
|
|
96
|
+
const hit = decimalRateNanoUnits(input.record.inputCacheHit)
|
|
97
|
+
const miss = decimalRateNanoUnits(input.record.inputCacheMiss)
|
|
98
|
+
if (hit === undefined || miss === undefined) return null
|
|
99
|
+
const cached = Number.isFinite(input.cachedInput) && input.cachedInput > 0 ? BigInt(Math.trunc(input.cachedInput)) : 0n
|
|
100
|
+
const uncached = Number.isFinite(input.uncachedInput) && input.uncachedInput > 0 ? BigInt(Math.trunc(input.uncachedInput)) : 0n
|
|
101
|
+
if (cached === 0n && uncached === 0n) return null
|
|
102
|
+
const femtoUnits = cached * hit + uncached * miss
|
|
103
|
+
return {
|
|
104
|
+
decimal: formatFemtoUnits(femtoUnits),
|
|
105
|
+
femtoUnits: femtoUnits.toString(),
|
|
106
|
+
currency: input.record.currency,
|
|
107
|
+
band: input.record.band,
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** femto(1e-15)整数 → 十进制串;与定价模块的 femto 渲染同构(模块内私有,此处独立实现)。 */
|
|
112
|
+
function formatFemtoUnits(value: bigint): string {
|
|
113
|
+
const digits = value.toString().padStart(16, '0')
|
|
114
|
+
const whole = digits.slice(0, -15)
|
|
115
|
+
const fraction = digits.slice(-15).replace(/0+$/u, '')
|
|
116
|
+
return fraction.length === 0 ? whole : `${whole}.${fraction}`
|
|
117
|
+
}
|