@dabuliu_wsy/dsh-im 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +197 -3
- package/cordis.patch.yml +4 -0
- package/dist/core/agent-state.d.ts +38 -0
- package/dist/core/agent-state.js +59 -0
- package/dist/core/arbiter-bridge.d.ts +25 -0
- package/dist/core/arbiter-bridge.js +20 -0
- package/dist/core/arbiter.d.ts +29 -0
- package/dist/core/arbiter.js +59 -0
- package/dist/core/avatar-brands.d.ts +23 -0
- package/dist/core/avatar-brands.js +75 -0
- package/dist/core/avatar-presets.d.ts +21 -0
- package/dist/core/avatar-presets.js +38 -0
- package/dist/core/avatar.d.ts +1 -0
- package/dist/core/avatar.js +18 -0
- package/dist/core/blocked.d.ts +12 -0
- package/dist/core/blocked.js +23 -0
- package/dist/core/budget-plan.d.ts +41 -0
- package/dist/core/budget-plan.js +69 -0
- package/dist/core/calibration-samples.d.ts +77 -0
- package/dist/core/calibration-samples.js +168 -0
- package/dist/core/calibrator.d.ts +57 -0
- package/dist/core/calibrator.js +125 -0
- package/dist/core/chapter-tree.d.ts +128 -0
- package/dist/core/chapter-tree.js +400 -0
- package/dist/core/consensus.d.ts +135 -0
- package/dist/core/consensus.js +394 -0
- package/dist/core/context-budget.d.ts +153 -0
- package/dist/core/context-budget.js +183 -0
- package/dist/core/curator.d.ts +28 -0
- package/dist/core/curator.js +190 -0
- package/dist/core/dual-window.d.ts +86 -0
- package/dist/core/dual-window.js +175 -0
- package/dist/core/events.d.ts +110 -0
- package/dist/core/events.js +117 -0
- package/dist/core/facts.d.ts +114 -0
- package/dist/core/facts.js +400 -0
- package/dist/core/fence.d.ts +34 -0
- package/dist/core/fence.js +129 -0
- package/dist/core/floor.d.ts +18 -0
- package/dist/core/floor.js +80 -0
- package/dist/core/ids.d.ts +11 -0
- package/dist/core/ids.js +29 -0
- package/dist/core/im.d.ts +167 -0
- package/dist/core/im.js +1307 -0
- package/dist/core/index.d.ts +33 -0
- package/dist/core/index.js +33 -0
- package/dist/core/log.d.ts +21 -0
- package/dist/core/log.js +63 -0
- package/dist/core/memory-claims.d.ts +67 -0
- package/dist/core/memory-claims.js +164 -0
- package/dist/core/memory-context.d.ts +121 -0
- package/dist/core/memory-context.js +303 -0
- package/dist/core/memory-visibility.d.ts +58 -0
- package/dist/core/memory-visibility.js +36 -0
- package/dist/core/memory.d.ts +12 -0
- package/dist/core/memory.js +73 -0
- package/dist/core/metrics.d.ts +49 -0
- package/dist/core/metrics.js +89 -0
- package/dist/core/multi-hop.d.ts +116 -0
- package/dist/core/multi-hop.js +278 -0
- package/dist/core/persist.d.ts +21 -0
- package/dist/core/persist.js +94 -0
- package/dist/core/proactive.d.ts +54 -0
- package/dist/core/proactive.js +108 -0
- package/dist/core/prompt.d.ts +82 -0
- package/dist/core/prompt.js +164 -0
- package/dist/core/receipt.d.ts +107 -0
- package/dist/core/receipt.js +86 -0
- package/dist/core/retrieval.d.ts +69 -0
- package/dist/core/retrieval.js +260 -0
- package/dist/core/role-state.d.ts +16 -0
- package/dist/core/role-state.js +65 -0
- package/dist/core/runtime.d.ts +137 -0
- package/dist/core/runtime.js +574 -0
- package/dist/core/summary.d.ts +19 -0
- package/dist/core/summary.js +96 -0
- package/dist/core/text.d.ts +10 -0
- package/dist/core/text.js +45 -0
- package/dist/core/time.d.ts +22 -0
- package/dist/core/time.js +84 -0
- package/dist/core/tool-schema.d.ts +12 -0
- package/dist/core/tool-schema.js +92 -0
- package/dist/core/tools.d.ts +137 -0
- package/dist/core/tools.js +348 -0
- package/dist/core/types.d.ts +400 -0
- package/dist/core/types.js +1 -0
- package/dist/core/window.d.ts +6 -0
- package/dist/core/window.js +7 -0
- package/dist/core/workspace-node.d.ts +28 -0
- package/dist/core/workspace-node.js +232 -0
- package/dist/core/workspace.d.ts +9 -0
- package/dist/core/workspace.js +45 -0
- package/dist/host/agent-session.d.ts +279 -0
- package/dist/host/agent-session.js +935 -0
- package/dist/host/attachment-gc.d.ts +37 -0
- package/dist/host/attachment-gc.js +97 -0
- package/dist/host/calibration-samples-store.d.ts +5 -0
- package/dist/host/calibration-samples-store.js +67 -0
- package/dist/host/capabilities.d.ts +45 -0
- package/dist/host/capabilities.js +67 -0
- package/dist/host/derived-store.d.ts +36 -0
- package/dist/host/derived-store.js +199 -0
- package/dist/host/dsh-llm.d.ts +143 -0
- package/dist/host/dsh-llm.js +395 -0
- package/dist/host/event-store.d.ts +47 -0
- package/dist/host/event-store.js +154 -0
- package/dist/host/fs-atomic.d.ts +1 -0
- package/dist/host/fs-atomic.js +26 -0
- package/dist/host/im-api.d.ts +352 -0
- package/dist/host/im-api.js +1137 -0
- package/dist/host/index.d.ts +103 -0
- package/dist/host/index.js +453 -0
- package/dist/host/memory-index.d.ts +65 -0
- package/dist/host/memory-index.js +181 -0
- package/dist/host/metrics-store.d.ts +7 -0
- package/dist/host/metrics-store.js +104 -0
- package/dist/host/models.d.ts +39 -0
- package/dist/host/models.js +67 -0
- package/dist/host/persona-tools.d.ts +57 -0
- package/dist/host/persona-tools.js +226 -0
- package/dist/host/preflight.d.ts +31 -0
- package/dist/host/preflight.js +29 -0
- package/dist/host/receipt-store.d.ts +26 -0
- package/dist/host/receipt-store.js +68 -0
- package/dist/host/run-check.d.ts +51 -0
- package/dist/host/run-check.js +190 -0
- package/dist/host/state-roots.d.ts +50 -0
- package/dist/host/state-roots.js +163 -0
- package/dist/host/tool-cache.d.ts +25 -0
- package/dist/host/tool-cache.js +90 -0
- package/dist/host/tool-call-budget.d.ts +29 -0
- package/dist/host/tool-call-budget.js +38 -0
- package/dsh-plugin.json +25 -0
- package/lib/client.inner.cjs +3346 -0
- package/lib/client.js +3354 -0
- package/package.json +86 -6
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type AvatarBrand } from './avatar-brands.ts';
|
|
2
|
+
/**
|
|
3
|
+
* 预制头像:把各家 AI 品牌标识渲染成 128×128 的圆形头像。
|
|
4
|
+
*
|
|
5
|
+
* - 图形数据来自 `avatar-brands.ts`(脚本生成,来源见 `scripts/gen-avatar-brands.mjs`);
|
|
6
|
+
* - 商标归各自权利人所有,这里只作为本地角色头像的可选图案,**不代表任何关联或背书**;
|
|
7
|
+
* - 全部内联成 `data:image/svg+xml`,运行时零网络请求,和其它头像一样直接进 `state.json`。
|
|
8
|
+
*/
|
|
9
|
+
export interface AvatarPreset {
|
|
10
|
+
/** 稳定 id(品牌 slug),用于识别当前选中的是哪一个 */
|
|
11
|
+
id: string;
|
|
12
|
+
/** 界面里显示 / 悬停提示的名字 */
|
|
13
|
+
label: string;
|
|
14
|
+
/** 可直接塞进 `<img src>` 的 data URL */
|
|
15
|
+
dataUrl: string;
|
|
16
|
+
}
|
|
17
|
+
/** 把一个品牌图形包成圆形头像的 SVG data URL。 */
|
|
18
|
+
export declare function presetAvatarUrl(brand: AvatarBrand): string;
|
|
19
|
+
export declare const AVATAR_PRESETS: readonly AvatarPreset[];
|
|
20
|
+
/** 当前头像命中哪个预制头像;不是预制头像(自动生成 / 上传图)返回 undefined。 */
|
|
21
|
+
export declare function findAvatarPreset(avatarUrl: string | undefined): AvatarPreset | undefined;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { AVATAR_BRANDS } from './avatar-brands.js';
|
|
2
|
+
/** 画布边长(viewBox 单位)。 */
|
|
3
|
+
const CANVAS = 40;
|
|
4
|
+
/** 品牌图形原始 viewBox 边长。 */
|
|
5
|
+
const GLYPH = 24;
|
|
6
|
+
/** 图形占画布的比例:留出圆形内边距,避免贴边被裁。 */
|
|
7
|
+
const GLYPH_RATIO = 0.66;
|
|
8
|
+
/** 单色图标(OpenAI / Grok / Ollama)统一染成近黑,白底上才看得清。 */
|
|
9
|
+
const INK = '#111827';
|
|
10
|
+
/** 圆底填充:极淡的灰蓝,白底面板上也有边界(纯色细线图标不至于糊在白色背景里)。 */
|
|
11
|
+
const PLATE = '#f4f6fa';
|
|
12
|
+
/** 圆底描边:再压一圈边界,浅色 logo 也能看清头像边界。 */
|
|
13
|
+
const RING = '#e3e7ee';
|
|
14
|
+
const SCALE = (CANVAS * GLYPH_RATIO) / GLYPH;
|
|
15
|
+
const OFFSET = (CANVAS - GLYPH * SCALE) / 2;
|
|
16
|
+
function round(value) {
|
|
17
|
+
return Math.round(value * 10000) / 10000;
|
|
18
|
+
}
|
|
19
|
+
/** 把一个品牌图形包成圆形头像的 SVG data URL。 */
|
|
20
|
+
export function presetAvatarUrl(brand) {
|
|
21
|
+
const fillRule = brand.fillRule ? ` fill-rule="${brand.fillRule}"` : '';
|
|
22
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 ${CANVAS} ${CANVAS}"${fillRule}>` +
|
|
23
|
+
`<circle cx="20" cy="20" r="19.5" fill="${PLATE}" stroke="${RING}" stroke-width="1"/>` +
|
|
24
|
+
`<g transform="translate(${round(OFFSET)} ${round(OFFSET)}) scale(${round(SCALE)})" fill="${INK}">${brand.body}</g>` +
|
|
25
|
+
`</svg>`;
|
|
26
|
+
return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
|
|
27
|
+
}
|
|
28
|
+
export const AVATAR_PRESETS = AVATAR_BRANDS.map((brand) => ({
|
|
29
|
+
id: brand.id,
|
|
30
|
+
label: brand.label,
|
|
31
|
+
dataUrl: presetAvatarUrl(brand),
|
|
32
|
+
}));
|
|
33
|
+
/** 当前头像命中哪个预制头像;不是预制头像(自动生成 / 上传图)返回 undefined。 */
|
|
34
|
+
export function findAvatarPreset(avatarUrl) {
|
|
35
|
+
if (!avatarUrl)
|
|
36
|
+
return undefined;
|
|
37
|
+
return AVATAR_PRESETS.find((preset) => preset.dataUrl === avatarUrl);
|
|
38
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function generateAvatar(name: string): string;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export function generateAvatar(name) {
|
|
2
|
+
const label = (name.trim().slice(0, 1) || '?').toUpperCase();
|
|
3
|
+
const hue = hash(name) % 360;
|
|
4
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
|
|
5
|
+
<rect width="128" height="128" rx="64" fill="hsl(${hue} 62% 48%)"/>
|
|
6
|
+
<text x="64" y="84" text-anchor="middle" fill="#fff" font-size="58" font-family="Segoe UI, PingFang SC, Microsoft YaHei, sans-serif">${escapeXml(label)}</text>
|
|
7
|
+
</svg>`;
|
|
8
|
+
return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
|
|
9
|
+
}
|
|
10
|
+
function hash(text) {
|
|
11
|
+
let n = 0;
|
|
12
|
+
for (const ch of text)
|
|
13
|
+
n = (n * 31 + ch.codePointAt(0)) >>> 0;
|
|
14
|
+
return n;
|
|
15
|
+
}
|
|
16
|
+
function escapeXml(text) {
|
|
17
|
+
return text.replace(/[<>&'"]/g, (ch) => ({ '<': '<', '>': '>', '&': '&', "'": ''', '"': '"' }[ch]));
|
|
18
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { BlockedState } from './types.ts';
|
|
2
|
+
export interface BlockedAdvice {
|
|
3
|
+
/** 给用户看的一句话建议。 */
|
|
4
|
+
hint: string;
|
|
5
|
+
/** 卡片上推荐先点哪个。 */
|
|
6
|
+
primary: 'retry' | 'skip' | 'pause';
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* 把宿主的稳定失败码翻成人话,供中断卡展示。
|
|
10
|
+
* 他们不依赖错误文案,只看 code。
|
|
11
|
+
*/
|
|
12
|
+
export declare function blockedAdvice(blocked: Pick<BlockedState, 'code'> | undefined): BlockedAdvice;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 把宿主的稳定失败码翻成人话,供中断卡展示。
|
|
3
|
+
* 他们不依赖错误文案,只看 code。
|
|
4
|
+
*/
|
|
5
|
+
export function blockedAdvice(blocked) {
|
|
6
|
+
switch (blocked?.code) {
|
|
7
|
+
case 'MISSING_CREDENTIAL':
|
|
8
|
+
case 'INVALID_CREDENTIAL':
|
|
9
|
+
case 'AUTH':
|
|
10
|
+
return { hint: '密钥/登录失效:去 DSH 设置里修好这个提供方,再回来点“已修好,重试”。', primary: 'retry' };
|
|
11
|
+
case 'NO_ADAPTER':
|
|
12
|
+
return { hint: '这个提供方已经不存在了:给角色重选一个模型,或本轮先移除它。', primary: 'skip' };
|
|
13
|
+
case 'RATE_LIMIT':
|
|
14
|
+
return { hint: '被限流了:等 30 秒左右点“重试”,或本轮先移除它。', primary: 'retry' };
|
|
15
|
+
case 'QUOTA':
|
|
16
|
+
case 'ACCOUNT_QUOTA':
|
|
17
|
+
return { hint: '额度用完了:需要充值或换提供方,本轮先把它移除。', primary: 'skip' };
|
|
18
|
+
case 'CONTEXT_WINDOW_EXCEEDED':
|
|
19
|
+
return { hint: '上下文超过了这个模型的窗口:换个长上下文模型,或先汇总再继续。', primary: 'pause' };
|
|
20
|
+
default:
|
|
21
|
+
return { hint: '可以直接重试一次;还不行就本轮先把它移除。', primary: 'retry' };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export type BudgetTier = 'economy' | 'standard' | 'deep';
|
|
2
|
+
export interface BudgetTierSpec {
|
|
3
|
+
/** 档位的 token 预算。 */
|
|
4
|
+
tokens: number;
|
|
5
|
+
/** 占上下文窗口的最大比例(防 1M 模型被灌太满)。 */
|
|
6
|
+
maxShare: number;
|
|
7
|
+
}
|
|
8
|
+
export declare const BUDGET_TIERS: Record<BudgetTier, BudgetTierSpec>;
|
|
9
|
+
export declare const DEFAULT_BUDGET_TIER: BudgetTier;
|
|
10
|
+
export declare const DEFAULT_RATIO = 1.6;
|
|
11
|
+
export declare const BUDGET_SAFETY = 0.8;
|
|
12
|
+
export declare const WINDOW_KEEP_MIN = 8;
|
|
13
|
+
export declare const WINDOW_KEEP_MAX = 60;
|
|
14
|
+
export declare function resolveTier(raw: unknown): BudgetTier;
|
|
15
|
+
export interface BudgetPlan {
|
|
16
|
+
tier: BudgetTier;
|
|
17
|
+
contextWindow?: number;
|
|
18
|
+
tokenBudget: number;
|
|
19
|
+
/** 被什么夹住:档位本身 / 上下文比例。 */
|
|
20
|
+
clampedBy: 'tier' | 'context-share';
|
|
21
|
+
ratio: number;
|
|
22
|
+
ratioSource: 'calibrated' | 'prior' | 'default';
|
|
23
|
+
windowChars: number;
|
|
24
|
+
windowKeepMin: number;
|
|
25
|
+
windowKeepMax: number;
|
|
26
|
+
/** 影子模式:上面都是 wouldBe,没有真正改裁剪。 */
|
|
27
|
+
shadow: boolean;
|
|
28
|
+
notes: string[];
|
|
29
|
+
}
|
|
30
|
+
export interface BudgetPlanInput {
|
|
31
|
+
contextWindow?: number;
|
|
32
|
+
/** 校准/先验给出的 chars/token。 */
|
|
33
|
+
ratio?: number;
|
|
34
|
+
ratioSource?: BudgetPlan['ratioSource'];
|
|
35
|
+
tier?: unknown;
|
|
36
|
+
/** 影子(默认)或真正生效。 */
|
|
37
|
+
mode?: 'shadow' | 'on';
|
|
38
|
+
/** 粘滞窗口:真正生效时,窗口只增不减。 */
|
|
39
|
+
currentWindowChars?: number;
|
|
40
|
+
}
|
|
41
|
+
export declare function planBudget(input?: BudgetPlanInput): BudgetPlan;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 预算计划(L3 · 先影子,不切实际裁剪)。
|
|
3
|
+
*
|
|
4
|
+
* 废除「24000 字符」这个常量,改成 **token 档位**;换算用校准系数,没有系数时用内容先验。
|
|
5
|
+
* 第一批只计算 `wouldBe*`(影子):不改窗口、不改 prompt,先看缓存命中率/延迟会怎样。
|
|
6
|
+
*
|
|
7
|
+
* 成本护栏(价目表/日账本/日帽/成本估算)2026-11-02 经用户裁决不做(native 通道无 usage,
|
|
8
|
+
* DSH 原生无用量账本,估算数会冒充真实用量):本文件只管 token 档位与字符预算,不涉及金额。
|
|
9
|
+
*
|
|
10
|
+
* 口径:
|
|
11
|
+
* - 档位 economy 30k / standard 80k / deep 200k tokens;hard cap = `min(档位, 上下文×maxShare)`;
|
|
12
|
+
* - `windowChars = tokenBudget × ratio × 0.8`(0.8 是安全余量),夹在 [400, 1_000_000];
|
|
13
|
+
* - 窗口条数动态:下限 8、上限 60(真正切换时再按 token 预算裁剪);
|
|
14
|
+
* - 粘滞窗口:只有 `mode='on'` 时才按「只增不减」处理;影子模式只报 wouldBe。
|
|
15
|
+
*/
|
|
16
|
+
import { RATIO_MAX, RATIO_MIN } from './calibration-samples.js';
|
|
17
|
+
export const BUDGET_TIERS = {
|
|
18
|
+
economy: { tokens: 50_000, maxShare: 0.1 },
|
|
19
|
+
standard: { tokens: 150_000, maxShare: 0.25 },
|
|
20
|
+
deep: { tokens: 320_000, maxShare: 0.4 },
|
|
21
|
+
};
|
|
22
|
+
export const DEFAULT_BUDGET_TIER = 'standard';
|
|
23
|
+
export const DEFAULT_RATIO = 1.6;
|
|
24
|
+
export const BUDGET_SAFETY = 0.8;
|
|
25
|
+
export const WINDOW_KEEP_MIN = 8;
|
|
26
|
+
export const WINDOW_KEEP_MAX = 60;
|
|
27
|
+
export function resolveTier(raw) {
|
|
28
|
+
return raw === 'economy' || raw === 'standard' || raw === 'deep' ? raw : DEFAULT_BUDGET_TIER;
|
|
29
|
+
}
|
|
30
|
+
export function planBudget(input = {}) {
|
|
31
|
+
const tier = resolveTier(input.tier);
|
|
32
|
+
const spec = BUDGET_TIERS[tier];
|
|
33
|
+
const notes = [];
|
|
34
|
+
const contextWindow = typeof input.contextWindow === 'number' && input.contextWindow > 0 ? input.contextWindow : undefined;
|
|
35
|
+
let tokenBudget = spec.tokens;
|
|
36
|
+
let clampedBy = 'tier';
|
|
37
|
+
if (contextWindow !== undefined) {
|
|
38
|
+
const shareCap = Math.floor(contextWindow * spec.maxShare);
|
|
39
|
+
if (shareCap < tokenBudget) {
|
|
40
|
+
tokenBudget = shareCap;
|
|
41
|
+
clampedBy = 'context-share';
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const typeRatio = typeof input.ratio === 'number' && Number.isFinite(input.ratio) ? input.ratio : undefined;
|
|
45
|
+
const ratio = Math.min(RATIO_MAX, Math.max(RATIO_MIN, typeRatio ?? DEFAULT_RATIO));
|
|
46
|
+
const ratioSource = typeRatio === undefined ? 'default' : input.ratioSource ?? 'calibrated';
|
|
47
|
+
let windowChars = Math.floor(tokenBudget * ratio * BUDGET_SAFETY);
|
|
48
|
+
if (input.mode === 'on' && typeof input.currentWindowChars === 'number' && input.currentWindowChars > windowChars) {
|
|
49
|
+
// 粘滞:窗口只增不减,避免每轮改前缀导致 prompt 缓存全失效。
|
|
50
|
+
windowChars = input.currentWindowChars;
|
|
51
|
+
notes.push('sticky-window(keep-current)');
|
|
52
|
+
}
|
|
53
|
+
windowChars = Math.min(1_000_000, Math.max(400, windowChars));
|
|
54
|
+
if (input.mode !== 'on')
|
|
55
|
+
notes.push('shadow(not-applied)');
|
|
56
|
+
return {
|
|
57
|
+
tier,
|
|
58
|
+
...(contextWindow === undefined ? {} : { contextWindow }),
|
|
59
|
+
tokenBudget,
|
|
60
|
+
clampedBy,
|
|
61
|
+
ratio: Math.round(ratio * 1000) / 1000,
|
|
62
|
+
ratioSource,
|
|
63
|
+
windowChars,
|
|
64
|
+
windowKeepMin: WINDOW_KEEP_MIN,
|
|
65
|
+
windowKeepMax: WINDOW_KEEP_MAX,
|
|
66
|
+
shadow: input.mode !== 'on',
|
|
67
|
+
notes,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export declare const CALIBRATION_SAMPLE_SCHEMA = 1;
|
|
2
|
+
/** 样本文件滚动上限(离线复算用,不参与运行时判断)。 */
|
|
3
|
+
export declare const MAX_CALIBRATION_SAMPLES = 500;
|
|
4
|
+
/** chars/token 合理区间:中文~1.5–2、代码/日志~3.5–4.5、base64~1.3;只做兜底,不当内容判断。 */
|
|
5
|
+
export declare const RATIO_MIN = 0.6;
|
|
6
|
+
export declare const RATIO_MAX = 6;
|
|
7
|
+
export type InvalidReason = 'usage_missing' | 'multi_round' | 'transport_native' | 'has_tools' | 'empty_prompt' | 'token_mismatch' | 'cache_semantics_unknown';
|
|
8
|
+
export type CacheSemantics = 'included' | 'excluded' | 'unknown';
|
|
9
|
+
export interface RawUsage {
|
|
10
|
+
inputTokens?: number;
|
|
11
|
+
outputTokens?: number;
|
|
12
|
+
totalTokens?: number;
|
|
13
|
+
reasoningTokens?: number;
|
|
14
|
+
cachedTokens?: number;
|
|
15
|
+
}
|
|
16
|
+
/** prompt 的内容构成(按 code point 计数,四类互斥且和为 promptChars)。 */
|
|
17
|
+
export interface Composition {
|
|
18
|
+
cjkChars: number;
|
|
19
|
+
codeLikeChars: number;
|
|
20
|
+
asciiProseChars: number;
|
|
21
|
+
otherChars: number;
|
|
22
|
+
}
|
|
23
|
+
export interface CalibrationSampleRecord {
|
|
24
|
+
schema: number;
|
|
25
|
+
at: number;
|
|
26
|
+
provider: string;
|
|
27
|
+
model: string;
|
|
28
|
+
purpose: string;
|
|
29
|
+
transport: 'ctx.llm' | 'native';
|
|
30
|
+
toolCalls: number;
|
|
31
|
+
toolCount: number;
|
|
32
|
+
systemChars: number;
|
|
33
|
+
messageChars: number;
|
|
34
|
+
promptChars: number;
|
|
35
|
+
composition: Composition;
|
|
36
|
+
promptHash: string;
|
|
37
|
+
cacheSemantics: CacheSemantics;
|
|
38
|
+
usage: RawUsage;
|
|
39
|
+
valid: boolean;
|
|
40
|
+
invalidReason?: InvalidReason;
|
|
41
|
+
}
|
|
42
|
+
export declare function cacheSemanticsFor(provider: string): CacheSemantics;
|
|
43
|
+
/** 确定性内容构成:逐行先判"代码行"(整行算代码),否则逐字符分类。 */
|
|
44
|
+
export declare function classifyComposition(text: string): Composition;
|
|
45
|
+
export interface BuildSampleInput {
|
|
46
|
+
at: number;
|
|
47
|
+
provider: string;
|
|
48
|
+
model: string;
|
|
49
|
+
purpose: string;
|
|
50
|
+
transport: 'ctx.llm' | 'native';
|
|
51
|
+
systemText: string;
|
|
52
|
+
messageText: string;
|
|
53
|
+
toolCalls: number;
|
|
54
|
+
toolCount: number;
|
|
55
|
+
usage: RawUsage;
|
|
56
|
+
cacheSemantics?: CacheSemantics;
|
|
57
|
+
}
|
|
58
|
+
/** 由一次调用的观察值构造样本(不判断 valid;判断在 validateSample)。 */
|
|
59
|
+
export declare function buildSample(input: BuildSampleInput): CalibrationSampleRecord;
|
|
60
|
+
/** 判据:返回 undefined = 有效;否则返回第一个不满足的原因(顺序即优先级)。 */
|
|
61
|
+
export declare function validateSample(sample: Pick<CalibrationSampleRecord, 'transport' | 'toolCalls' | 'toolCount' | 'promptChars' | 'cacheSemantics' | 'usage'>, options?: {
|
|
62
|
+
skipRatioRange?: boolean;
|
|
63
|
+
}): InvalidReason | undefined;
|
|
64
|
+
/** 内容先验:四类占比归一后的加权平均(不是简单相加,避免占比和≠1 时偏大)。 */
|
|
65
|
+
export declare const PRIOR_WEIGHTS: {
|
|
66
|
+
readonly cjk: 1.8;
|
|
67
|
+
readonly code: 3.8;
|
|
68
|
+
readonly prose: 3;
|
|
69
|
+
readonly other: 2.5;
|
|
70
|
+
};
|
|
71
|
+
export declare function priorRatio(composition: Composition): number;
|
|
72
|
+
/** 单条样本的 chars/token(方向写死:promptChars / inputTokens)。 */
|
|
73
|
+
export declare function sampleRatio(sample: Pick<CalibrationSampleRecord, 'promptChars' | 'usage'>): number | undefined;
|
|
74
|
+
/** 桶键:tokenizer 由 provider+model 决定,再按 purpose 分(只校准 reply 是调用方的职责)。 */
|
|
75
|
+
export declare function bucketKey(sample: Pick<CalibrationSampleRecord, 'provider' | 'model' | 'purpose'>): string;
|
|
76
|
+
/** 同一 prompt 在窗口内只算一次(重试/重放会重复采样)。 */
|
|
77
|
+
export declare function dedupeSamples(samples: readonly CalibrationSampleRecord[]): CalibrationSampleRecord[];
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 校准样本(L1 · 计量正确性)。
|
|
3
|
+
*
|
|
4
|
+
* 原则:**先证明数据可信,再谈校准**。这里只做两件事:
|
|
5
|
+
* 1. 把一次调用的「原始 usage + 我们自己的 prompt 口径(chars/构成/工具轮次/通道)」落成一条样本;
|
|
6
|
+
* 2. 用可离线复算的判据给样本定 valid / invalidReason。
|
|
7
|
+
*
|
|
8
|
+
* 关键口径(2026-11-02 与用户对齐):
|
|
9
|
+
* - `totalTokens = input + output`(±1);`reasoningTokens` 是 **output 的子集**,不是可加项;
|
|
10
|
+
* - 只校准 `ctx.llm` 通道、`toolCalls = 0`、`purpose = reply` 的样本;
|
|
11
|
+
* - `cachedTokens > 0` 不判废,但 `cacheSemantics` 未知(不知道 input 是否含缓存)→ 判废;
|
|
12
|
+
* - `charsPerToken = promptChars / inputTokens`,方向写死,不再出现 token/char;
|
|
13
|
+
* - promptChars 用 **code point** 计数(`[...text].length`),并拆 system/messages。
|
|
14
|
+
*/
|
|
15
|
+
import { stableHash } from './receipt.js';
|
|
16
|
+
export const CALIBRATION_SAMPLE_SCHEMA = 1;
|
|
17
|
+
/** 样本文件滚动上限(离线复算用,不参与运行时判断)。 */
|
|
18
|
+
export const MAX_CALIBRATION_SAMPLES = 500;
|
|
19
|
+
/** chars/token 合理区间:中文~1.5–2、代码/日志~3.5–4.5、base64~1.3;只做兜底,不当内容判断。 */
|
|
20
|
+
export const RATIO_MIN = 0.6;
|
|
21
|
+
export const RATIO_MAX = 6;
|
|
22
|
+
/**
|
|
23
|
+
* 各 provider 的 `inputTokens` 是否含缓存 token。
|
|
24
|
+
* OpenAI 兼容的 `prompt_tokens` 通常**含** cached;Anthropic 的 `input_tokens` 通常**不含** cache_read。
|
|
25
|
+
* 未知一律 `unknown` → 样本判废(宁可没样本,不要脏样本)。
|
|
26
|
+
*/
|
|
27
|
+
const CACHE_SEMANTICS_BY_PROVIDER = {
|
|
28
|
+
'deepseek-account': 'included',
|
|
29
|
+
'deepseek-official': 'included',
|
|
30
|
+
magpie: 'included',
|
|
31
|
+
anthropic: 'excluded',
|
|
32
|
+
openai: 'included',
|
|
33
|
+
};
|
|
34
|
+
export function cacheSemanticsFor(provider) {
|
|
35
|
+
const key = provider.trim().toLowerCase();
|
|
36
|
+
return CACHE_SEMANTICS_BY_PROVIDER[key] ?? CACHE_SEMANTICS_BY_PROVIDER[key.split(/[-_]/)[0]] ?? 'unknown';
|
|
37
|
+
}
|
|
38
|
+
const CJK = /[\u3400-\u9fff\uf900-\ufaff\u3040-\u30ff]/;
|
|
39
|
+
const CODE_LINE = [
|
|
40
|
+
/^\s{2,}\S/,
|
|
41
|
+
/[{};]\s*$/,
|
|
42
|
+
/\b(const|let|var|function|return|class|import|export|if|for|while|await|async)\b/,
|
|
43
|
+
/=>|==={0,1}|!==?|&&|\|\|/,
|
|
44
|
+
/^\s*(diff --git|@@|\+\+\+|---)/,
|
|
45
|
+
/^\s*\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/,
|
|
46
|
+
/\b(expect|assert|test|describe|it)\(/,
|
|
47
|
+
/^\s*[-*]\s*\[/,
|
|
48
|
+
];
|
|
49
|
+
function isCodeLine(line) {
|
|
50
|
+
return CODE_LINE.some((pattern) => pattern.test(line));
|
|
51
|
+
}
|
|
52
|
+
/** 确定性内容构成:逐行先判"代码行"(整行算代码),否则逐字符分类。 */
|
|
53
|
+
export function classifyComposition(text) {
|
|
54
|
+
const composition = { cjkChars: 0, codeLikeChars: 0, asciiProseChars: 0, otherChars: 0 };
|
|
55
|
+
for (const line of text.split('\n')) {
|
|
56
|
+
if (isCodeLine(line)) {
|
|
57
|
+
composition.codeLikeChars += [...line].length;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
for (const char of line) {
|
|
61
|
+
if (CJK.test(char))
|
|
62
|
+
composition.cjkChars += 1;
|
|
63
|
+
else if (/[A-Za-z0-9 .,;:!?'"()[\]{}<>/\\|@#$%^&*_+=~`-]/.test(char))
|
|
64
|
+
composition.asciiProseChars += 1;
|
|
65
|
+
else
|
|
66
|
+
composition.otherChars += 1;
|
|
67
|
+
}
|
|
68
|
+
// 换行符本身不计入(与 promptChars 的 join 口径一致)
|
|
69
|
+
}
|
|
70
|
+
return composition;
|
|
71
|
+
}
|
|
72
|
+
/** 由一次调用的观察值构造样本(不判断 valid;判断在 validateSample)。 */
|
|
73
|
+
export function buildSample(input) {
|
|
74
|
+
const systemText = input.systemText ?? '';
|
|
75
|
+
const messageText = input.messageText ?? '';
|
|
76
|
+
const promptText = `${systemText}\n${messageText}`;
|
|
77
|
+
const sample = {
|
|
78
|
+
schema: CALIBRATION_SAMPLE_SCHEMA,
|
|
79
|
+
at: input.at,
|
|
80
|
+
provider: input.provider,
|
|
81
|
+
model: input.model,
|
|
82
|
+
purpose: input.purpose,
|
|
83
|
+
transport: input.transport,
|
|
84
|
+
toolCalls: Math.max(0, Math.floor(input.toolCalls)),
|
|
85
|
+
toolCount: Math.max(0, Math.floor(input.toolCount)),
|
|
86
|
+
systemChars: [...systemText].length,
|
|
87
|
+
messageChars: [...messageText].length,
|
|
88
|
+
promptChars: [...promptText].length,
|
|
89
|
+
composition: classifyComposition(promptText),
|
|
90
|
+
promptHash: stableHash(`${input.provider}|${input.model}|${systemText}|${messageText}`).split(':').at(-1) ?? '',
|
|
91
|
+
cacheSemantics: input.cacheSemantics ?? cacheSemanticsFor(input.provider),
|
|
92
|
+
usage: { ...input.usage },
|
|
93
|
+
valid: false,
|
|
94
|
+
};
|
|
95
|
+
const reason = validateSample(sample, { skipRatioRange: true });
|
|
96
|
+
sample.valid = reason === undefined;
|
|
97
|
+
if (reason)
|
|
98
|
+
sample.invalidReason = reason;
|
|
99
|
+
return sample;
|
|
100
|
+
}
|
|
101
|
+
/** 判据:返回 undefined = 有效;否则返回第一个不满足的原因(顺序即优先级)。 */
|
|
102
|
+
export function validateSample(sample, options = {}) {
|
|
103
|
+
if (sample.promptChars <= 0)
|
|
104
|
+
return 'empty_prompt';
|
|
105
|
+
if (sample.transport === 'native')
|
|
106
|
+
return 'transport_native';
|
|
107
|
+
if (sample.toolCalls > 0)
|
|
108
|
+
return 'multi_round';
|
|
109
|
+
// 带工具的样本只做成本观测:工具 schema 的 token 无法从 promptChars 反映,ratio 会系统性偏低。
|
|
110
|
+
if (sample.toolCount > 0)
|
|
111
|
+
return 'has_tools';
|
|
112
|
+
if (sample.cacheSemantics === 'unknown')
|
|
113
|
+
return 'cache_semantics_unknown';
|
|
114
|
+
const { inputTokens, outputTokens, totalTokens, reasoningTokens } = sample.usage;
|
|
115
|
+
if (typeof inputTokens !== 'number' || typeof totalTokens !== 'number' || inputTokens <= 0)
|
|
116
|
+
return 'usage_missing';
|
|
117
|
+
// total = input + output(±1);reasoning 是 output 的子集,不能加成第三项。
|
|
118
|
+
const output = typeof outputTokens === 'number' ? outputTokens : 0;
|
|
119
|
+
if (Math.abs(totalTokens - (inputTokens + output)) > 1)
|
|
120
|
+
return 'token_mismatch';
|
|
121
|
+
if (typeof reasoningTokens === 'number' && typeof outputTokens === 'number' && reasoningTokens > outputTokens + 1)
|
|
122
|
+
return 'token_mismatch';
|
|
123
|
+
if (!options.skipRatioRange) {
|
|
124
|
+
const ratio = promptCharsOf(sample) / inputTokens;
|
|
125
|
+
if (!Number.isFinite(ratio) || ratio < RATIO_MIN || ratio > RATIO_MAX)
|
|
126
|
+
return 'token_mismatch';
|
|
127
|
+
}
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
function promptCharsOf(sample) {
|
|
131
|
+
return sample.promptChars;
|
|
132
|
+
}
|
|
133
|
+
/** 内容先验:四类占比归一后的加权平均(不是简单相加,避免占比和≠1 时偏大)。 */
|
|
134
|
+
export const PRIOR_WEIGHTS = { cjk: 1.8, code: 3.8, prose: 3.0, other: 2.5 };
|
|
135
|
+
export function priorRatio(composition) {
|
|
136
|
+
const total = composition.cjkChars + composition.codeLikeChars + composition.asciiProseChars + composition.otherChars;
|
|
137
|
+
if (total <= 0)
|
|
138
|
+
return 2.5;
|
|
139
|
+
const ratio = (composition.cjkChars * PRIOR_WEIGHTS.cjk
|
|
140
|
+
+ composition.codeLikeChars * PRIOR_WEIGHTS.code
|
|
141
|
+
+ composition.asciiProseChars * PRIOR_WEIGHTS.prose
|
|
142
|
+
+ composition.otherChars * PRIOR_WEIGHTS.other) / total;
|
|
143
|
+
return Math.min(RATIO_MAX, Math.max(RATIO_MIN, Math.round(ratio * 1000) / 1000));
|
|
144
|
+
}
|
|
145
|
+
/** 单条样本的 chars/token(方向写死:promptChars / inputTokens)。 */
|
|
146
|
+
export function sampleRatio(sample) {
|
|
147
|
+
const tokens = sample.usage.inputTokens;
|
|
148
|
+
if (typeof tokens !== 'number' || tokens <= 0 || sample.promptChars <= 0)
|
|
149
|
+
return undefined;
|
|
150
|
+
return sample.promptChars / tokens;
|
|
151
|
+
}
|
|
152
|
+
/** 桶键:tokenizer 由 provider+model 决定,再按 purpose 分(只校准 reply 是调用方的职责)。 */
|
|
153
|
+
export function bucketKey(sample) {
|
|
154
|
+
return `${sample.provider}::${sample.model}::${sample.purpose}`;
|
|
155
|
+
}
|
|
156
|
+
/** 同一 prompt 在窗口内只算一次(重试/重放会重复采样)。 */
|
|
157
|
+
export function dedupeSamples(samples) {
|
|
158
|
+
const seen = new Set();
|
|
159
|
+
const out = [];
|
|
160
|
+
for (const sample of samples) {
|
|
161
|
+
const key = `${bucketKey(sample)}|${sample.promptHash}`;
|
|
162
|
+
if (seen.has(key))
|
|
163
|
+
continue;
|
|
164
|
+
seen.add(key);
|
|
165
|
+
out.push(sample);
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 校准器(L2 · 影子模式)。
|
|
3
|
+
*
|
|
4
|
+
* 不出数就启用,而是先回答「如果按这桶样本启用,ratio 会是多少、预算会变成多少」。
|
|
5
|
+
* 只有样本量、离散度、invalid 占比、漂移都过关,且调用方显式允许时,才进入 `calibrated`。
|
|
6
|
+
*
|
|
7
|
+
* 统计口径(与用户对齐):
|
|
8
|
+
* - 按 `provider::model::purpose` 分桶;只对 `purpose=reply` 校准(extract/curate 结构不同);
|
|
9
|
+
* - 滑动窗口(默认 60 条)+ 中位数,不用累计平均;
|
|
10
|
+
* - 绝对容差 `|x − median| ≤ max(0.5·median, 0.8)`;
|
|
11
|
+
* - n ≥ 8 才谈启用;invalid 占比 >10% 不启用;
|
|
12
|
+
* - 收缩:`prior + (median − prior) × n/(n+K)`,样本越多越信实测;
|
|
13
|
+
* - ratio 夹在 [0.6, 6]。
|
|
14
|
+
*/
|
|
15
|
+
import { type CalibrationSampleRecord } from './calibration-samples.ts';
|
|
16
|
+
export interface CalibratorConfig {
|
|
17
|
+
windowSize: number;
|
|
18
|
+
minSamples: number;
|
|
19
|
+
toleranceAbsolute: number;
|
|
20
|
+
toleranceRelative: number;
|
|
21
|
+
shrinkageK: number;
|
|
22
|
+
maxInvalidShare: number;
|
|
23
|
+
/** 只有显式打开才允许进入 calibrated;默认 false(影子)。 */
|
|
24
|
+
allowCalibrated: boolean;
|
|
25
|
+
}
|
|
26
|
+
export declare const DEFAULT_CALIBRATOR_CONFIG: CalibratorConfig;
|
|
27
|
+
export type CalibrationMode = 'default' | 'shadow' | 'calibrated' | 'fallback';
|
|
28
|
+
export interface BucketDecision {
|
|
29
|
+
bucket: string;
|
|
30
|
+
/** 窗口内样本数(含去重后)。 */
|
|
31
|
+
samples: number;
|
|
32
|
+
validSamples: number;
|
|
33
|
+
keptSamples: number;
|
|
34
|
+
invalidShare: number;
|
|
35
|
+
priorRatio: number;
|
|
36
|
+
medianRatio?: number;
|
|
37
|
+
shadowRatio?: number;
|
|
38
|
+
weight: number;
|
|
39
|
+
mode: CalibrationMode;
|
|
40
|
+
/** 收缩后是否被 [0.6,6] 夹住。 */
|
|
41
|
+
wouldClamp: boolean;
|
|
42
|
+
reasons: string[];
|
|
43
|
+
}
|
|
44
|
+
export declare function median(values: readonly number[]): number | undefined;
|
|
45
|
+
/** 对一个桶(同 provider::model::purpose)做影子决策。 */
|
|
46
|
+
export declare function decideBucket(records: readonly CalibrationSampleRecord[], config?: Partial<CalibratorConfig>): BucketDecision;
|
|
47
|
+
export interface CalibrationReport {
|
|
48
|
+
generatedAt: number;
|
|
49
|
+
totals: {
|
|
50
|
+
samples: number;
|
|
51
|
+
valid: number;
|
|
52
|
+
invalid: number;
|
|
53
|
+
};
|
|
54
|
+
buckets: BucketDecision[];
|
|
55
|
+
}
|
|
56
|
+
/** 全量报告:按桶分组后逐桶决策(排序稳定,便于 diff)。 */
|
|
57
|
+
export declare function buildCalibrationReport(records: readonly CalibrationSampleRecord[], config?: Partial<CalibratorConfig>, now?: number): CalibrationReport;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 校准器(L2 · 影子模式)。
|
|
3
|
+
*
|
|
4
|
+
* 不出数就启用,而是先回答「如果按这桶样本启用,ratio 会是多少、预算会变成多少」。
|
|
5
|
+
* 只有样本量、离散度、invalid 占比、漂移都过关,且调用方显式允许时,才进入 `calibrated`。
|
|
6
|
+
*
|
|
7
|
+
* 统计口径(与用户对齐):
|
|
8
|
+
* - 按 `provider::model::purpose` 分桶;只对 `purpose=reply` 校准(extract/curate 结构不同);
|
|
9
|
+
* - 滑动窗口(默认 60 条)+ 中位数,不用累计平均;
|
|
10
|
+
* - 绝对容差 `|x − median| ≤ max(0.5·median, 0.8)`;
|
|
11
|
+
* - n ≥ 8 才谈启用;invalid 占比 >10% 不启用;
|
|
12
|
+
* - 收缩:`prior + (median − prior) × n/(n+K)`,样本越多越信实测;
|
|
13
|
+
* - ratio 夹在 [0.6, 6]。
|
|
14
|
+
*/
|
|
15
|
+
import { RATIO_MAX, RATIO_MIN, bucketKey, priorRatio, sampleRatio, validateSample, } from './calibration-samples.js';
|
|
16
|
+
export const DEFAULT_CALIBRATOR_CONFIG = {
|
|
17
|
+
windowSize: 60,
|
|
18
|
+
minSamples: 8,
|
|
19
|
+
toleranceAbsolute: 0.8,
|
|
20
|
+
toleranceRelative: 0.5,
|
|
21
|
+
shrinkageK: 12,
|
|
22
|
+
maxInvalidShare: 0.1,
|
|
23
|
+
allowCalibrated: false,
|
|
24
|
+
};
|
|
25
|
+
export function median(values) {
|
|
26
|
+
if (values.length === 0)
|
|
27
|
+
return undefined;
|
|
28
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
29
|
+
const mid = Math.floor(sorted.length / 2);
|
|
30
|
+
return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
|
|
31
|
+
}
|
|
32
|
+
function clampRatio(value) {
|
|
33
|
+
const clamped = Math.min(RATIO_MAX, Math.max(RATIO_MIN, value));
|
|
34
|
+
return { value: Math.round(clamped * 1000) / 1000, clamped: clamped !== value };
|
|
35
|
+
}
|
|
36
|
+
/** 对一个桶(同 provider::model::purpose)做影子决策。 */
|
|
37
|
+
export function decideBucket(records, config = {}) {
|
|
38
|
+
const cfg = { ...DEFAULT_CALIBRATOR_CONFIG, ...config };
|
|
39
|
+
const bucket = records.length ? bucketKey(records[0]) : 'unknown';
|
|
40
|
+
const window = records.slice(-cfg.windowSize);
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
const samples = window.filter((sample) => {
|
|
43
|
+
const key = sample.promptHash;
|
|
44
|
+
if (seen.has(key))
|
|
45
|
+
return false;
|
|
46
|
+
seen.add(key);
|
|
47
|
+
return true;
|
|
48
|
+
});
|
|
49
|
+
const reasons = [];
|
|
50
|
+
// 离线复算:不信任落盘时的 valid 字段。
|
|
51
|
+
const valid = samples.filter((sample) => validateSample(sample) === undefined);
|
|
52
|
+
const invalidShare = samples.length ? 1 - valid.length / samples.length : 1;
|
|
53
|
+
const prior = priorRatio(samples.length
|
|
54
|
+
? samples[samples.length - 1].composition
|
|
55
|
+
: { cjkChars: 0, codeLikeChars: 0, asciiProseChars: 0, otherChars: 0 });
|
|
56
|
+
const ratios = valid
|
|
57
|
+
.map((sample) => sampleRatio(sample))
|
|
58
|
+
.filter((ratio) => ratio !== undefined);
|
|
59
|
+
const base = {
|
|
60
|
+
bucket,
|
|
61
|
+
samples: samples.length,
|
|
62
|
+
validSamples: valid.length,
|
|
63
|
+
keptSamples: 0,
|
|
64
|
+
invalidShare: Math.round(invalidShare * 1000) / 1000,
|
|
65
|
+
priorRatio: prior,
|
|
66
|
+
weight: 0,
|
|
67
|
+
mode: 'default',
|
|
68
|
+
wouldClamp: false,
|
|
69
|
+
reasons,
|
|
70
|
+
};
|
|
71
|
+
if (samples.length < cfg.minSamples) {
|
|
72
|
+
reasons.push(`insufficient-samples(${samples.length}/${cfg.minSamples})`);
|
|
73
|
+
return base;
|
|
74
|
+
}
|
|
75
|
+
if (invalidShare > cfg.maxInvalidShare) {
|
|
76
|
+
reasons.push(`invalid-share(${Math.round(invalidShare * 100)}% > ${Math.round(cfg.maxInvalidShare * 100)}%)`);
|
|
77
|
+
return base;
|
|
78
|
+
}
|
|
79
|
+
const center = median(ratios);
|
|
80
|
+
if (center === undefined) {
|
|
81
|
+
reasons.push('no-valid-ratio');
|
|
82
|
+
return base;
|
|
83
|
+
}
|
|
84
|
+
const tolerance = Math.max(cfg.toleranceAbsolute, center * cfg.toleranceRelative);
|
|
85
|
+
const kept = ratios.filter((ratio) => Math.abs(ratio - center) <= tolerance);
|
|
86
|
+
if (kept.length < cfg.minSamples) {
|
|
87
|
+
reasons.push(`no-stable-cluster(kept=${kept.length}/${cfg.minSamples})`);
|
|
88
|
+
return { ...base, medianRatio: Math.round(center * 1000) / 1000, keptSamples: kept.length };
|
|
89
|
+
}
|
|
90
|
+
const weight = kept.length / (kept.length + cfg.shrinkageK);
|
|
91
|
+
const shrunk = prior + (center - prior) * weight;
|
|
92
|
+
const clamped = clampRatio(shrunk);
|
|
93
|
+
if (clamped.clamped)
|
|
94
|
+
reasons.push('ratio-clamped');
|
|
95
|
+
const mode = cfg.allowCalibrated ? 'calibrated' : 'shadow';
|
|
96
|
+
if (mode === 'shadow')
|
|
97
|
+
reasons.push('shadow-mode');
|
|
98
|
+
return {
|
|
99
|
+
...base,
|
|
100
|
+
keptSamples: kept.length,
|
|
101
|
+
medianRatio: Math.round(center * 1000) / 1000,
|
|
102
|
+
shadowRatio: clamped.value,
|
|
103
|
+
weight: Math.round(weight * 1000) / 1000,
|
|
104
|
+
mode,
|
|
105
|
+
wouldClamp: clamped.clamped,
|
|
106
|
+
reasons,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/** 全量报告:按桶分组后逐桶决策(排序稳定,便于 diff)。 */
|
|
110
|
+
export function buildCalibrationReport(records, config = {}, now = Date.now()) {
|
|
111
|
+
const buckets = new Map();
|
|
112
|
+
for (const record of records) {
|
|
113
|
+
const key = bucketKey(record);
|
|
114
|
+
const list = buckets.get(key) ?? [];
|
|
115
|
+
list.push(record);
|
|
116
|
+
buckets.set(key, list);
|
|
117
|
+
}
|
|
118
|
+
const decisions = [...buckets.keys()].sort().map((key) => decideBucket(buckets.get(key) ?? [], config));
|
|
119
|
+
const valid = records.filter((record) => validateSample(record) === undefined).length;
|
|
120
|
+
return {
|
|
121
|
+
generatedAt: now,
|
|
122
|
+
totals: { samples: records.length, valid, invalid: records.length - valid },
|
|
123
|
+
buckets: decisions,
|
|
124
|
+
};
|
|
125
|
+
}
|