dsh-task-time-cost 0.0.0-stage → 0.2.8-beta.2
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/CHANGELOG.md +29 -0
- package/COMPATIBILITY.md +26 -0
- package/CONTRIBUTING.md +11 -0
- package/LICENSE +21 -0
- package/README.en.md +60 -0
- package/README.md +59 -2
- package/THIRD_PARTY_NOTICES.md +113 -0
- package/cordis.patch.yml +4 -0
- package/data/baselines.json +12 -0
- package/data/defaults.json +21 -0
- package/data/models-dev-prices.json +1 -0
- package/data/prices.json +7 -0
- package/data/sources.json +15 -0
- package/docs/public/DETAIL.md +1 -0
- package/docs/public/DETAIL.zh.md +1 -0
- package/docs/public/acceptance.md +26 -0
- package/docs/public/guide.en.md +33 -0
- package/docs/public/guide.zh.md +35 -0
- package/docs/public/preview.svg +1 -0
- package/docs/public/privacy.md +13 -0
- package/docs/public/publishing.md +9 -0
- package/icon.svg +1 -0
- package/lib/client.js +175 -0
- package/lib/index.js +22948 -0
- package/lib/index.js.map +7 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +122 -4
- package/scripts/import-public-prices.mjs +35 -0
- package/src/client/INTEGRATION.md +61 -0
- package/src/client/config.ts +24 -0
- package/src/client/details.tsx +126 -0
- package/src/client/format.ts +218 -0
- package/src/client/index.tsx +225 -0
- package/src/client/locale.ts +353 -0
- package/src/client/management.tsx +246 -0
- package/src/client/placement.ts +26 -0
- package/src/client/remote.ts +59 -0
- package/src/client/store.ts +210 -0
- package/src/client/styles.ts +94 -0
- package/src/client/use-panel-placement.ts +54 -0
- package/src/client-entry.ts +12 -0
- package/src/host/config-entry.ts +47 -0
- package/src/host/config.ts +85 -0
- package/src/host/engine.ts +580 -0
- package/src/host/facts.ts +170 -0
- package/src/host/forecast-cost.ts +16 -0
- package/src/host/index.ts +269 -0
- package/src/host/record-schema.ts +175 -0
- package/src/host/repository.ts +167 -0
- package/src/host/runtime.ts +99 -0
- package/src/shared/ai-plan.ts +45 -0
- package/src/shared/baseline-selection.ts +43 -0
- package/src/shared/baselines.ts +135 -0
- package/src/shared/call-size.ts +32 -0
- package/src/shared/config.ts +65 -0
- package/src/shared/forecast.ts +91 -0
- package/src/shared/index.ts +12 -0
- package/src/shared/ledger.ts +38 -0
- package/src/shared/money.ts +46 -0
- package/src/shared/performance.ts +216 -0
- package/src/shared/pricing.ts +293 -0
- package/src/shared/public-prices.ts +57 -0
- package/src/shared/remote-contract.ts +72 -0
- package/src/shared/retained-time.ts +14 -0
- package/src/shared/time.ts +207 -0
- package/src/shared/types.ts +66 -0
- package/src/shared/usage.ts +232 -0
- package/src/shared/wire.ts +134 -0
- package/src/shared/workload.ts +265 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { validateConfig } from './config.ts';
|
|
2
|
+
import type { EstimatorConfig } from './config.ts';
|
|
3
|
+
import { assertSpan, ewma, nonnegative } from './types.ts';
|
|
4
|
+
import type { EstimateOrigin, Outcome, RouteIdentity, SourceKind, Span, TaskKind } from './types.ts';
|
|
5
|
+
|
|
6
|
+
export interface TaskFeatures {
|
|
7
|
+
/** Transient classifier input. Never included in returned plans/history. */
|
|
8
|
+
prompt: string;
|
|
9
|
+
currentInputTokens: number | null;
|
|
10
|
+
explicitOutputTokens?: Span;
|
|
11
|
+
artifactCount?: number;
|
|
12
|
+
fileCount?: number;
|
|
13
|
+
attachmentTokens?: Span;
|
|
14
|
+
observedPlanSteps?: number;
|
|
15
|
+
}
|
|
16
|
+
export interface ClassificationRule { id: string; kind: TaskKind; patterns: string[]; excludePatterns?: string[]; requiresAll?: boolean }
|
|
17
|
+
export interface WorkloadTemplate { kind: TaskKind; requestCount: Span; visibleOutputTokens: Span; toolMs: Span; sourceKind: SourceKind; sourceId?: string }
|
|
18
|
+
export interface RequestBudget {
|
|
19
|
+
id: string;
|
|
20
|
+
route: RouteIdentity;
|
|
21
|
+
inputTokens: Span | null;
|
|
22
|
+
visibleTextTokens: Span | null;
|
|
23
|
+
/** Includes observable body OR tool parameters, never includes hidden reasoning. */
|
|
24
|
+
visibleOutputTokens: Span;
|
|
25
|
+
reasoningTokens: Span | null;
|
|
26
|
+
cacheReadRatio: Span | null;
|
|
27
|
+
dependsOn: string[];
|
|
28
|
+
sourceKind: SourceKind;
|
|
29
|
+
}
|
|
30
|
+
export interface ToolBudget { id: string; durationMs: Span; dependsOn: string[]; resource?: string; sourceKind: SourceKind }
|
|
31
|
+
export interface PlanScenario { requests: RequestBudget[]; tools: ToolBudget[] }
|
|
32
|
+
export interface WorkloadPlan { kind: TaskKind; low: PlanScenario; high: PlanScenario; origin: EstimateOrigin; reasons: string[]; workloadSamples: number; sourceIds: string[] }
|
|
33
|
+
export interface WorkloadHistory { kind: TaskKind; requestCount: number; visibleOutputTokens: number; toolMs: number; samples: number; lastObservedAtMs: number | null; sourceKind: 'local-measured' }
|
|
34
|
+
export interface WorkloadObservation {
|
|
35
|
+
kind: TaskKind;
|
|
36
|
+
outcome: Outcome;
|
|
37
|
+
requestCount: number;
|
|
38
|
+
visibleOutputTokens: number | null;
|
|
39
|
+
toolMs: number | null;
|
|
40
|
+
observedAtMs?: number;
|
|
41
|
+
scopeChanged?: boolean;
|
|
42
|
+
appendedRequirements?: boolean;
|
|
43
|
+
dataComplete?: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const DEFAULT_TEMPLATES: readonly WorkloadTemplate[] = Object.freeze([
|
|
47
|
+
{ kind: 'question', requestCount: { low: 1, high: 2 }, visibleOutputTokens: { low: 150, high: 800 }, toolMs: { low: 0, high: 0 }, sourceKind: 'heuristic' },
|
|
48
|
+
{ kind: 'writing', requestCount: { low: 1, high: 3 }, visibleOutputTokens: { low: 600, high: 4_000 }, toolMs: { low: 0, high: 10_000 }, sourceKind: 'heuristic' },
|
|
49
|
+
{ kind: 'file-analysis', requestCount: { low: 2, high: 10 }, visibleOutputTokens: { low: 800, high: 6_000 }, toolMs: { low: 10_000, high: 300_000 }, sourceKind: 'heuristic' },
|
|
50
|
+
{ kind: 'code', requestCount: { low: 6, high: 40 }, visibleOutputTokens: { low: 1_200, high: 15_000 }, toolMs: { low: 60_000, high: 1_200_000 }, sourceKind: 'heuristic' },
|
|
51
|
+
{ kind: 'research', requestCount: { low: 4, high: 20 }, visibleOutputTokens: { low: 1_500, high: 12_000 }, toolMs: { low: 60_000, high: 900_000 }, sourceKind: 'heuristic' },
|
|
52
|
+
{ kind: 'unknown', requestCount: { low: 3, high: 15 }, visibleOutputTokens: { low: 500, high: 8_000 }, toolMs: { low: 30_000, high: 600_000 }, sourceKind: 'heuristic' },
|
|
53
|
+
] as WorkloadTemplate[]);
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Ordered local classifier. Rules run top-down; the first match wins.
|
|
57
|
+
*
|
|
58
|
+
* Real prompts are short requests, not specifications: "重新打包并验证" or
|
|
59
|
+
* "重构 settings 面板" name a code action with no repository noun next to it,
|
|
60
|
+
* and an earlier rule set that demanded `verb + project-noun` sent nearly every
|
|
61
|
+
* real task to `unknown`. Each rule therefore accepts either a verb adjacent to
|
|
62
|
+
* a domain noun or a strong domain noun on its own, in Chinese and English.
|
|
63
|
+
*/
|
|
64
|
+
export const DEFAULT_CLASSIFICATION_RULES: readonly ClassificationRule[] = Object.freeze([
|
|
65
|
+
{
|
|
66
|
+
id: 'engineering-work', kind: 'code',
|
|
67
|
+
// A code verb whose object is a document is writing, and a definitional
|
|
68
|
+
// request that merely names a module is still a question.
|
|
69
|
+
excludePatterns: [
|
|
70
|
+
'(?:写|撰写|起草|生成|输出|整理成|改写成).{0,12}(?:README|readme|CHANGELOG|文档|说明|报告|文章|文案|摘要|演讲稿)',
|
|
71
|
+
'(?:^|[。!?!?]\\s*)(?:请)?(?:解释|什么是|为什么|如何理解|介绍|告诉我|怎么理解)',
|
|
72
|
+
'^\\s*(?:what|why|how|explain|tell me)\\b',
|
|
73
|
+
],
|
|
74
|
+
patterns: [
|
|
75
|
+
// A development verb within 24 characters of a development noun.
|
|
76
|
+
'(?:迭代|优化|实现|开发|重构|调试|修复|部署|打包|编译|构建|安装|升级|迁移|接入|封装|抽取|改造|改写|补全|落地|联调|排查|定位|复现|验证|跑通|跑一下|改|写|加|删|拆|合并|升级).{0,24}(?:插件|接口|组件|模块|函数|脚本|配置文件|配置项|配置|仓库|代码库|代码|项目|单元测试|集成测试|测试|用例|面板|页面|服务|命令|样式|类型|编译|构建|打包|部署|报错|崩溃|异常|bug|patch|release|api|API|CLI|SDK|schema)',
|
|
77
|
+
// A strong engineering noun standing alone already identifies the work.
|
|
78
|
+
'(?:插件|代码库|单元测试|集成测试|构建产物|依赖版本|类型定义|接口定义|错误栈|异常栈|回归测试|打包发布).{0,24}(?:修|改|做|写|跑|装|发|实现|优化|重构)',
|
|
79
|
+
'(?:插件|代码库|单元测试|集成测试|类型定义|接口定义|错误栈|异常栈|构建脚本)',
|
|
80
|
+
'(?:重新|再次)?(?:打包|编译|构建|部署|重构|重构一下|跑一遍测试|运行测试|跑测试)',
|
|
81
|
+
'\\b(?:fix|refactor|implement|debug|deploy|build|compile|migrate|upgrade|optimi[sz]e|iterate|patch)\\b.{0,32}\\b(?:bug|repo\\w*|code\\w*|project|test\\w*|plugin|module|component|script|api|build|config|release)\\b',
|
|
82
|
+
'\\b(?:bug|refactor|unit tests?|pull request|stack trace|regression|build failing)\\b',
|
|
83
|
+
],
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
id: 'direct-artifact', kind: 'writing',
|
|
87
|
+
patterns: [
|
|
88
|
+
'(?:直接|只需|仅需|生成|输出|写|撰写|起草|润色|翻译|总结|概括|整理成|改写成).{0,24}(?:SVG|svg|HTML片段|代码片段|故事|文章|文案|摘要|总结|诗|邮件|README|readme|readme文档|文档|公告|说明|报告|致辞|演讲稿)',
|
|
89
|
+
'\\b(?:write|generate|compose|draft|summarize|translate|polish|rewrite)\\b.{0,32}\\b(?:story|article|essay|svg|snippet|summary|email|readme|docs?|post|poem|copy)\\b',
|
|
90
|
+
'\\b(?:README|CHANGELOG)\\b',
|
|
91
|
+
],
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
id: 'research', kind: 'research',
|
|
95
|
+
patterns: [
|
|
96
|
+
'调研|研究.{0,16}(?:资料|来源|报告|对比|现状)|多步.{0,10}(?:搜索|检索)|联网.{0,10}(?:搜索|查找)|(?:搜索|查找|检索|调研|了解).{0,20}(?:最新|对比|资料|来源|现状|竞品)',
|
|
97
|
+
'\\b(?:research|investigate|search the web|find sources|look up|compare)\\b',
|
|
98
|
+
],
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: 'files', kind: 'file-analysis',
|
|
102
|
+
patterns: [
|
|
103
|
+
'(?:分析|阅读|检查|审阅|提取|解析|统计|对照).{0,24}(?:文件|附件|文档|表格|PDF|pdf|CSV|csv|数据集|日志|截图|图片)',
|
|
104
|
+
'\\b(?:analy[sz]e|read|review|extract|parse|inspect)\\b.{0,32}\\b(?:file|document|attachment|pdf|spreadsheet|csv|dataset|log|screenshot)\\b',
|
|
105
|
+
],
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
id: 'explanation', kind: 'question',
|
|
109
|
+
patterns: ['^(?:请)?(?:解释|什么是|为什么|如何理解|介绍|告诉我|怎么理解)|[??]$', '^\\s*(?:what|why|how|explain|tell me)\\b'],
|
|
110
|
+
},
|
|
111
|
+
]);
|
|
112
|
+
|
|
113
|
+
export function validateTemplates(templates: readonly WorkloadTemplate[]): void {
|
|
114
|
+
const kinds = new Set<TaskKind>();
|
|
115
|
+
for (const template of templates) {
|
|
116
|
+
if (!DEFAULT_TEMPLATES.some(item => item.kind === template.kind) || kinds.has(template.kind)) throw new TypeError('Unknown/duplicate workload kind');
|
|
117
|
+
kinds.add(template.kind);
|
|
118
|
+
assertSpan(template.requestCount, 'requestCount');
|
|
119
|
+
assertSpan(template.visibleOutputTokens, 'visibleOutputTokens');
|
|
120
|
+
assertSpan(template.toolMs, 'toolMs');
|
|
121
|
+
if (template.requestCount.low < 1 || !Number.isSafeInteger(template.requestCount.low) || !Number.isSafeInteger(template.requestCount.high)) throw new TypeError('Request counts must be positive integers');
|
|
122
|
+
if (!['heuristic', 'public-measured', 'local-measured'].includes(template.sourceKind)) throw new TypeError('Invalid workload source');
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function validateClassificationRules(rules: readonly ClassificationRule[]): void {
|
|
127
|
+
const ids = new Set<string>();
|
|
128
|
+
for (const rule of rules) {
|
|
129
|
+
if (!rule.id || ids.has(rule.id) || !DEFAULT_TEMPLATES.some(template => template.kind === rule.kind) || !Array.isArray(rule.patterns) || !rule.patterns.length || (rule.requiresAll !== undefined && typeof rule.requiresAll !== 'boolean')) throw new TypeError('Invalid classification rule');
|
|
130
|
+
ids.add(rule.id);
|
|
131
|
+
for (const pattern of [...rule.patterns, ...(rule.excludePatterns ?? [])]) {
|
|
132
|
+
if (typeof pattern !== 'string' || !pattern) throw new TypeError('Classification patterns must be nonempty strings');
|
|
133
|
+
new RegExp(pattern, 'iu');
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function classifyTask(input: TaskFeatures, rules: readonly ClassificationRule[] = DEFAULT_CLASSIFICATION_RULES): { kind: TaskKind; reasons: string[] } {
|
|
139
|
+
validateClassificationRules(rules);
|
|
140
|
+
for (const rule of rules) {
|
|
141
|
+
const tests = rule.patterns.map(pattern => new RegExp(pattern, 'iu').test(input.prompt));
|
|
142
|
+
const excluded = (rule.excludePatterns ?? []).some(pattern => new RegExp(pattern, 'iu').test(input.prompt));
|
|
143
|
+
if (!excluded && (rule.requiresAll ? tests.every(Boolean) : tests.some(Boolean))) return { kind: rule.kind, reasons: [`classification-rule:${rule.id}`, 'classification:heuristic'] };
|
|
144
|
+
}
|
|
145
|
+
if ((input.fileCount ?? 0) > 0 || input.attachmentTokens !== undefined) return { kind: 'file-analysis', reasons: ['observable-attachments', 'classification:heuristic'] };
|
|
146
|
+
return { kind: 'unknown', reasons: ['no-classification-match', 'classification:heuristic'] };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function estimateWorkload(input: TaskFeatures, route: RouteIdentity, options: { config?: Partial<EstimatorConfig>; templates?: readonly WorkloadTemplate[]; rules?: readonly ClassificationRule[]; history?: WorkloadHistory[] } = {}): WorkloadPlan {
|
|
150
|
+
const config = validateConfig(options.config);
|
|
151
|
+
const templates = options.templates ?? DEFAULT_TEMPLATES;
|
|
152
|
+
validateTemplates(templates);
|
|
153
|
+
if (input.currentInputTokens !== null && (!Number.isSafeInteger(input.currentInputTokens) || input.currentInputTokens < 0)) throw new TypeError('Invalid current input Token count');
|
|
154
|
+
for (const key of ['artifactCount', 'fileCount', 'observedPlanSteps'] as const) if (input[key] !== undefined && (!Number.isSafeInteger(input[key]) || input[key]! < (key === 'fileCount' ? 0 : 1))) throw new TypeError(`Invalid ${key}`);
|
|
155
|
+
if (input.attachmentTokens) assertSpan(input.attachmentTokens, 'attachmentTokens');
|
|
156
|
+
const classification = classifyTask(input, options.rules);
|
|
157
|
+
const template = templates.find(template => template.kind === classification.kind) ?? templates.find(template => template.kind === 'unknown');
|
|
158
|
+
if (!template) throw new TypeError('No compatible workload template');
|
|
159
|
+
const history = options.history?.find(item => item.kind === classification.kind && item.samples > 0);
|
|
160
|
+
let count = { ...template.requestCount };
|
|
161
|
+
let output = { ...template.visibleOutputTokens };
|
|
162
|
+
let tool = { ...template.toolMs };
|
|
163
|
+
const reasons = [...classification.reasons, 'serial-conservative-dependencies', 'cache-ratio-unknown', 'reasoning-budget-unknown'];
|
|
164
|
+
if (history) {
|
|
165
|
+
for (const key of ['requestCount', 'visibleOutputTokens', 'toolMs', 'samples'] as const) nonnegative(history[key], key);
|
|
166
|
+
count = scaleRange(count, history.requestCount);
|
|
167
|
+
count = { low: Math.max(1, Math.floor(count.low)), high: Math.max(1, Math.ceil(count.high)) };
|
|
168
|
+
output = scaleRange(output, history.visibleOutputTokens);
|
|
169
|
+
tool = scaleRange(tool, history.toolMs);
|
|
170
|
+
reasons.push('local-workload-ewma');
|
|
171
|
+
} else reasons.push('engineering-workload-template');
|
|
172
|
+
const artifacts = input.artifactCount ?? 1;
|
|
173
|
+
if (artifacts > 1) {
|
|
174
|
+
output = { low: output.low * artifacts, high: output.high * artifacts };
|
|
175
|
+
if (!['question', 'writing'].includes(classification.kind)) count.high = Math.max(count.high, artifacts);
|
|
176
|
+
reasons.push('explicit-artifact-count');
|
|
177
|
+
}
|
|
178
|
+
if (input.observedPlanSteps !== undefined) {
|
|
179
|
+
count.high = Math.max(count.high, input.observedPlanSteps);
|
|
180
|
+
reasons.push('observable-plan-steps');
|
|
181
|
+
}
|
|
182
|
+
if ((input.fileCount ?? 0) > 4) {
|
|
183
|
+
const batches = Math.ceil(input.fileCount! / 4);
|
|
184
|
+
count.high = Math.max(count.high, batches);
|
|
185
|
+
tool.high *= batches;
|
|
186
|
+
reasons.push('file-batch-assumption');
|
|
187
|
+
}
|
|
188
|
+
const length = input.explicitOutputTokens ?? outputLengthFromPrompt(input.prompt);
|
|
189
|
+
if (length) {
|
|
190
|
+
assertSpan(length, 'explicitOutputTokens');
|
|
191
|
+
// Requested length describes the final artifact; intermediate output is retained separately.
|
|
192
|
+
const overhead = ['code', 'research', 'file-analysis'].includes(classification.kind) ? 1.5 : 1;
|
|
193
|
+
output = { low: Math.max(output.low, length.low * artifacts), high: Math.max(output.high, length.high * artifacts * overhead) };
|
|
194
|
+
reasons.push(input.explicitOutputTokens ? 'explicit-output-token-budget' : 'requested-length-token-conversion:heuristic');
|
|
195
|
+
}
|
|
196
|
+
const origin: EstimateOrigin = history ? (template.sourceKind === 'local-measured' ? 'local-measured' : 'mixed') : template.sourceKind;
|
|
197
|
+
return {
|
|
198
|
+
kind: classification.kind,
|
|
199
|
+
low: buildScenario(count.low, output.low, tool.low, input.currentInputTokens, route, classification.kind, template.sourceKind, config, false, length ? length.low * artifacts : null),
|
|
200
|
+
high: buildScenario(count.high, output.high, tool.high, input.currentInputTokens, route, classification.kind, template.sourceKind, config, true, length ? length.high * artifacts : null),
|
|
201
|
+
origin, reasons, workloadSamples: history?.samples ?? 0,
|
|
202
|
+
sourceIds: [template.sourceId ?? `engineering-${template.kind}-v1`, ...(history ? [`local-workload:${history.kind}:${history.samples}`] : [])],
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function outputLengthFromPrompt(prompt: string): Span | null {
|
|
207
|
+
const match = prompt.match(/(?:约|大约|写|输出|write|about)?\s*(\d{2,7})\s*(字|words?)/iu);
|
|
208
|
+
if (!match) return null;
|
|
209
|
+
const length = Number(match[1]);
|
|
210
|
+
const chinese = match[2] === '字';
|
|
211
|
+
return { low: Math.floor(length * (chinese ? 1 : 1.2)), high: Math.ceil(length * (chinese ? 2 : 1.8)) };
|
|
212
|
+
}
|
|
213
|
+
function scaleRange(range: Span, center: number): Span {
|
|
214
|
+
const old = (range.low + range.high) / 2;
|
|
215
|
+
return old > 0 ? { low: range.low * center / old, high: range.high * center / old } : { low: center, high: center };
|
|
216
|
+
}
|
|
217
|
+
function buildScenario(count: number, totalOutput: number, totalToolMs: number, initialInput: number | null, route: RouteIdentity, kind: TaskKind, sourceKind: SourceKind, config: EstimatorConfig, high: boolean, finalOutput: number | null): PlanScenario {
|
|
218
|
+
const requests: RequestBudget[] = [];
|
|
219
|
+
const tools: ToolBudget[] = [];
|
|
220
|
+
const toolCount = totalToolMs > 0 ? Math.max(1, count - 1) : 0;
|
|
221
|
+
let retained = 0;
|
|
222
|
+
let dependency: string[] = [];
|
|
223
|
+
const finalBudget = count === 1 ? totalOutput : Math.min(totalOutput, Math.max(finalOutput ?? 0, totalOutput * 0.6));
|
|
224
|
+
const intermediateBudget = count > 1 ? (totalOutput - finalBudget) / (count - 1) : 0;
|
|
225
|
+
for (let index = 0; index < count; index++) {
|
|
226
|
+
const id = `request-${index + 1}`;
|
|
227
|
+
const final = index === count - 1;
|
|
228
|
+
const visible = Math.ceil(final ? finalBudget : intermediateBudget);
|
|
229
|
+
// A known mode supplied by the current route must survive classification:
|
|
230
|
+
// otherwise the live tool profile is discarded for unknown/text priors.
|
|
231
|
+
const mode = route.requestMode !== 'unknown' ? route.requestMode
|
|
232
|
+
: kind === 'unknown' ? 'unknown' : final || ['question', 'writing'].includes(kind) ? 'text' : 'mixed';
|
|
233
|
+
const current = initialInput === null ? null : { low: Math.floor(initialInput + retained), high: Math.ceil(initialInput + retained) };
|
|
234
|
+
requests.push({ id, route: { ...route, requestMode: mode }, inputTokens: current, visibleTextTokens: mode === 'text' ? { low: visible, high: visible } : null, visibleOutputTokens: { low: visible, high: visible }, reasoningTokens: null, cacheReadRatio: null, dependsOn: [...dependency], sourceKind });
|
|
235
|
+
retained += visible;
|
|
236
|
+
dependency = [id];
|
|
237
|
+
if (index < toolCount) {
|
|
238
|
+
const toolId = `tool-${index + 1}`;
|
|
239
|
+
tools.push({ id: toolId, durationMs: { low: totalToolMs / toolCount, high: totalToolMs / toolCount }, dependsOn: [id], resource: 'tool', sourceKind });
|
|
240
|
+
retained += high ? config.toolResultTokensPerCall.high : config.toolResultTokensPerCall.low;
|
|
241
|
+
dependency = [toolId];
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return { requests, tools };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function updateWorkload(previous: WorkloadHistory | null, observation: WorkloadObservation, alpha = 0.2): { history: WorkloadHistory | null; accepted: boolean; reasons: string[] } {
|
|
248
|
+
// Validate alpha even when the observation is excluded.
|
|
249
|
+
ewma(0, 0, alpha);
|
|
250
|
+
const reasons: string[] = [];
|
|
251
|
+
if (observation.outcome !== 'completed') reasons.push(`outcome:${observation.outcome}`);
|
|
252
|
+
if (observation.scopeChanged || observation.appendedRequirements) reasons.push('task-scope-changed');
|
|
253
|
+
if (observation.dataComplete === false || observation.visibleOutputTokens === null || observation.toolMs === null) reasons.push('workload-data-incomplete');
|
|
254
|
+
if (reasons.length) return { history: previous ? structuredClone(previous) : null, accepted: false, reasons };
|
|
255
|
+
if (!Number.isSafeInteger(observation.requestCount) || observation.requestCount < 1) throw new TypeError('Invalid observed request count');
|
|
256
|
+
nonnegative(observation.visibleOutputTokens!, 'visibleOutputTokens');
|
|
257
|
+
nonnegative(observation.toolMs!, 'toolMs');
|
|
258
|
+
if (observation.observedAtMs !== undefined) nonnegative(observation.observedAtMs, 'observedAtMs');
|
|
259
|
+
if (previous && previous.kind !== observation.kind) throw new TypeError('Workload kind mismatch');
|
|
260
|
+
const template = DEFAULT_TEMPLATES.find(template => template.kind === observation.kind);
|
|
261
|
+
if (!template) throw new TypeError('Unknown workload kind');
|
|
262
|
+
const center = (range: Span) => (range.low + range.high) / 2;
|
|
263
|
+
const base = previous ?? { requestCount: center(template.requestCount), visibleOutputTokens: center(template.visibleOutputTokens), toolMs: center(template.toolMs), samples: 0 };
|
|
264
|
+
return { history: { kind: observation.kind, requestCount: ewma(base.requestCount, observation.requestCount, alpha), visibleOutputTokens: ewma(base.visibleOutputTokens, observation.visibleOutputTokens!, alpha), toolMs: ewma(base.toolMs, observation.toolMs!, alpha), samples: base.samples + 1, lastObservedAtMs: observation.observedAtMs ?? null, sourceKind: 'local-measured' }, accepted: true, reasons: [] };
|
|
265
|
+
}
|