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.
Files changed (70) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/COMPATIBILITY.md +26 -0
  3. package/CONTRIBUTING.md +11 -0
  4. package/LICENSE +21 -0
  5. package/README.en.md +60 -0
  6. package/README.md +59 -2
  7. package/THIRD_PARTY_NOTICES.md +113 -0
  8. package/cordis.patch.yml +4 -0
  9. package/data/baselines.json +12 -0
  10. package/data/defaults.json +21 -0
  11. package/data/models-dev-prices.json +1 -0
  12. package/data/prices.json +7 -0
  13. package/data/sources.json +15 -0
  14. package/docs/public/DETAIL.md +1 -0
  15. package/docs/public/DETAIL.zh.md +1 -0
  16. package/docs/public/acceptance.md +26 -0
  17. package/docs/public/guide.en.md +33 -0
  18. package/docs/public/guide.zh.md +35 -0
  19. package/docs/public/preview.svg +1 -0
  20. package/docs/public/privacy.md +13 -0
  21. package/docs/public/publishing.md +9 -0
  22. package/icon.svg +1 -0
  23. package/lib/client.js +175 -0
  24. package/lib/index.js +22948 -0
  25. package/lib/index.js.map +7 -0
  26. package/locale/en.json +7 -0
  27. package/locale/zh.json +7 -0
  28. package/package.json +122 -4
  29. package/scripts/import-public-prices.mjs +35 -0
  30. package/src/client/INTEGRATION.md +61 -0
  31. package/src/client/config.ts +24 -0
  32. package/src/client/details.tsx +126 -0
  33. package/src/client/format.ts +218 -0
  34. package/src/client/index.tsx +225 -0
  35. package/src/client/locale.ts +353 -0
  36. package/src/client/management.tsx +246 -0
  37. package/src/client/placement.ts +26 -0
  38. package/src/client/remote.ts +59 -0
  39. package/src/client/store.ts +210 -0
  40. package/src/client/styles.ts +94 -0
  41. package/src/client/use-panel-placement.ts +54 -0
  42. package/src/client-entry.ts +12 -0
  43. package/src/host/config-entry.ts +47 -0
  44. package/src/host/config.ts +85 -0
  45. package/src/host/engine.ts +580 -0
  46. package/src/host/facts.ts +170 -0
  47. package/src/host/forecast-cost.ts +16 -0
  48. package/src/host/index.ts +269 -0
  49. package/src/host/record-schema.ts +175 -0
  50. package/src/host/repository.ts +167 -0
  51. package/src/host/runtime.ts +99 -0
  52. package/src/shared/ai-plan.ts +45 -0
  53. package/src/shared/baseline-selection.ts +43 -0
  54. package/src/shared/baselines.ts +135 -0
  55. package/src/shared/call-size.ts +32 -0
  56. package/src/shared/config.ts +65 -0
  57. package/src/shared/forecast.ts +91 -0
  58. package/src/shared/index.ts +12 -0
  59. package/src/shared/ledger.ts +38 -0
  60. package/src/shared/money.ts +46 -0
  61. package/src/shared/performance.ts +216 -0
  62. package/src/shared/pricing.ts +293 -0
  63. package/src/shared/public-prices.ts +57 -0
  64. package/src/shared/remote-contract.ts +72 -0
  65. package/src/shared/retained-time.ts +14 -0
  66. package/src/shared/time.ts +207 -0
  67. package/src/shared/types.ts +66 -0
  68. package/src/shared/usage.ts +232 -0
  69. package/src/shared/wire.ts +134 -0
  70. package/src/shared/workload.ts +265 -0
@@ -0,0 +1,170 @@
1
+ import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session';
2
+ import type {} from '@deepseek-ai/dsh-agent';
3
+ import type { AssistantStreamRecord, StreamChunk, TokenUsage } from '@deepseek-ai/dsh-llm';
4
+ import type { TaskState } from '../shared/wire.ts';
5
+ import type { TaskKind, RequestMode } from '../shared/types.ts';
6
+ import type { RawUsage } from '../shared/usage.ts';
7
+ import { readAiPlanResult } from '../shared/ai-plan.ts';
8
+ import type { AiPlan } from '../shared/ai-plan.ts';
9
+
10
+ export interface RouteFact { providerId: string; modelId: string; reasoningEffort: string }
11
+ export interface StreamStats {
12
+ firstContentAt: number | null; firstTextAt: number | null; lastContentAt: number | null;
13
+ textChars: number; reasoningChars: number; toolChars: number; textDeltas: number;
14
+ usage: RawUsage | null; finish: string | null;
15
+ }
16
+ export interface CallFact extends StreamStats {
17
+ id: string; seq: number; turn: number; step: number;
18
+ startedAt: number; endedAt: number; route: RouteFact; mode: RequestMode;
19
+ outcome: 'completed' | 'failed' | 'cancelled' | 'truncated' | 'interrupted';
20
+ timingSource: 'step-boundary' | 'live-attempt';
21
+ }
22
+ export interface ToolFact { id: string; name: string; startedAt: number; endedAt: number | null; failed: boolean }
23
+ export interface TaskFact {
24
+ turn: number; startSeq: number; startedAt: number; endedAt: number | null; lastAt: number;
25
+ state: TaskState; taskType: TaskKind; promptChars: number; attachmentCount: number;
26
+ explicitOutputWords: number | null; userMessages: number; scopeChanged: boolean;
27
+ step: number; stepStartedAt: number; route: RouteFact | null;
28
+ calls: CallFact[]; tools: Record<string, ToolFact>;
29
+ aiPlan?: AiPlan;
30
+ }
31
+ type PromptFeatures = Pick<TaskFact, 'taskType' | 'promptChars' | 'attachmentCount' | 'explicitOutputWords' | 'userMessages'>;
32
+ export interface FactsState {
33
+ sessionId: string; inheritedEventCount: number; lastSeq: number; currentTurn: number | null;
34
+ pendingPrompt: PromptFeatures | null;
35
+ route: RouteFact | null; tasks: Record<string, TaskFact>;
36
+ view: { revision: number; currentTurn: number | null };
37
+ error: string | null;
38
+ }
39
+ export type Classifier = (prompt: string) => TaskKind;
40
+
41
+ export function initialFacts(header: SessionHeader, inheritedEventCount: number): FactsState {
42
+ return { sessionId: header.id, inheritedEventCount, lastSeq: -1, currentTurn: null, pendingPrompt: null, route: null, tasks: {}, view: { revision: -1, currentTurn: null }, error: null };
43
+ }
44
+ export function emptyStreamStats(): StreamStats {
45
+ return { firstContentAt: null, firstTextAt: null, lastContentAt: null, textChars: 0, reasoningChars: 0, toolChars: 0, textDeltas: 0, usage: null, finish: null };
46
+ }
47
+ export function rawDshUsage(usage: TokenUsage): RawUsage {
48
+ return { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens,
49
+ ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),
50
+ ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),
51
+ ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),
52
+ ...(usage.totalTokens !== undefined ? { totalTokens: usage.totalTokens } : {}) };
53
+ }
54
+ /** Counts metadata only; model text and tool arguments are never retained. */
55
+ export function observeChunk(previous: StreamStats, chunk: StreamChunk, at: number): StreamStats {
56
+ const next = { ...previous };
57
+ if (chunk.type === 'text-delta' && chunk.text) {
58
+ next.firstContentAt ??= at; next.firstTextAt ??= at; next.lastContentAt = at;
59
+ next.textChars += chunk.text.length; next.textDeltas++;
60
+ } else if (chunk.type === 'reasoning-delta' && chunk.text) {
61
+ next.firstContentAt ??= at; next.lastContentAt = at; next.reasoningChars += chunk.text.length;
62
+ } else if (chunk.type === 'tool-call-delta' && (chunk.argumentsDelta || chunk.name)) {
63
+ next.firstContentAt ??= at; next.lastContentAt = at; next.toolChars += chunk.argumentsDelta.length;
64
+ } else if (chunk.type === 'usage') next.usage = rawDshUsage(chunk.usage);
65
+ else if (chunk.type === 'finish') next.finish = chunk.reason.kind;
66
+ return next;
67
+ }
68
+ export function durableStreamStats(stream: readonly AssistantStreamRecord[]): StreamStats {
69
+ let stats = emptyStreamStats();
70
+ for (const record of stream) {
71
+ if (record.type === 'chunk') { stats = observeChunk(stats, record.chunk, record.time); continue; }
72
+ const values = record.type === 'tool-call-chunks' ? record.args : record.texts;
73
+ let time = record.time0;
74
+ for (let i = 0; i < values.length; i++) {
75
+ if (i) time += record.dt[i - 1];
76
+ if (record.type === 'text-chunks') stats = observeChunk(stats, { type: 'text-delta', index: record.index, text: values[i] }, time);
77
+ else if (record.type === 'reasoning-chunks') stats = observeChunk(stats, { type: 'reasoning-delta', index: record.index, text: values[i] }, time);
78
+ else stats = observeChunk(stats, { type: 'tool-call-delta', index: record.index, id: record.id, argumentsDelta: values[i], ...(record.name ? { name: record.name } : {}) }, time);
79
+ }
80
+ }
81
+ return stats;
82
+ }
83
+ export function streamMode(stats: StreamStats): RequestMode {
84
+ return stats.toolChars > 0 ? stats.textChars > 0 ? 'mixed' : 'tool' : stats.textChars > 0 ? 'text' : 'unknown';
85
+ }
86
+ export function turnEndState(kind: string): TaskState {
87
+ if (kind === 'completed') return 'completed';
88
+ if (kind === 'aborted') return 'cancelled';
89
+ if (kind === 'interrupted' || kind === 'forked') return 'interrupted';
90
+ return 'failed';
91
+ }
92
+
93
+ function mergePrompt(previous: PromptFeatures | null, incoming: PromptFeatures): PromptFeatures {
94
+ return { taskType: incoming.taskType === 'unknown' ? previous?.taskType ?? 'unknown' : incoming.taskType,
95
+ promptChars: (previous?.promptChars ?? 0) + incoming.promptChars,
96
+ attachmentCount: (previous?.attachmentCount ?? 0) + incoming.attachmentCount,
97
+ explicitOutputWords: incoming.explicitOutputWords ?? previous?.explicitOutputWords ?? null,
98
+ userMessages: (previous?.userMessages ?? 0) + incoming.userMessages };
99
+ }
100
+
101
+ /** Pure incremental projection. Ignored events keep reference identity. */
102
+ export function foldFacts(state: FactsState, event: SessionEvent, classify: Classifier): FactsState {
103
+ if (event.seq <= state.lastSeq || event.seq < state.inheritedEventCount) return state;
104
+ const kind = event.type;
105
+ const interested = ['turn/start', 'turn/end', 'step/start', 'user/message', 'assistant/message', 'assistant/attempt', 'tool/call', 'tool/result', 'request/header', 'model/selection'];
106
+ if (!interested.includes(kind)) return state;
107
+ let next: FactsState = { ...state, tasks: { ...state.tasks }, lastSeq: event.seq };
108
+ if (event.type === 'request/header' || event.type === 'model/selection') {
109
+ const config = event.type === 'request/header' ? event.data.header.config : event.data;
110
+ next.route = { providerId: config.provider, modelId: config.model, reasoningEffort: config.reasoningEffort ?? 'unknown' };
111
+ }
112
+ let incoming: PromptFeatures | null = null;
113
+ if (event.type === 'user/message' && event.data.source.kind === 'user') {
114
+ const prompt = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
115
+ const count = /(?:\b|约|写|生成|输出)(\d{1,6})\s*(?:字|words?\b)/i.exec(prompt);
116
+ incoming = { taskType: classify(prompt), promptChars: prompt.length,
117
+ attachmentCount: event.data.content.filter(block => block.type === 'file' || block.type === 'image').length,
118
+ explicitOutputWords: count ? Number(count[1]) : null, userMessages: 1 };
119
+ }
120
+ if (event.type === 'turn/start') {
121
+ const turn = event.data.turn;
122
+ next.currentTurn = turn;
123
+ next.tasks[String(turn)] = { turn, startSeq: event.seq, startedAt: event.time, endedAt: null, lastAt: event.time, state: 'running', taskType: 'unknown', promptChars: 0, attachmentCount: 0, explicitOutputWords: null, userMessages: 0, scopeChanged: false, step: 0, stepStartedAt: event.time, route: next.route, calls: [], tools: {}, ...(next.pendingPrompt ?? {}) };
124
+ next.pendingPrompt = null;
125
+ // Bound the per-session checkpoint. Older completed snapshots remain in plugin storage.
126
+ const old = Object.keys(next.tasks).sort((a, b) => Number(a) - Number(b));
127
+ for (const key of old.slice(0, Math.max(0, old.length - 200))) delete next.tasks[key];
128
+ } else {
129
+ const data = event.data;
130
+ const eventTurn = data && typeof data === 'object' && 'turn' in data && typeof data.turn === 'number' ? data.turn : next.currentTurn;
131
+ const previous = eventTurn === null ? undefined : next.tasks[String(eventTurn)];
132
+ if (incoming && (!previous || previous.endedAt !== null)) next.pendingPrompt = mergePrompt(next.pendingPrompt, incoming);
133
+ if (previous) {
134
+ const task: TaskFact = { ...previous, lastAt: event.time };
135
+ next.tasks[String(task.turn)] = task;
136
+ if (event.type === 'step/start') {
137
+ task.step = event.data.step; task.stepStartedAt = event.time; task.route = next.route;
138
+ } else if (event.type === 'request/header' || event.type === 'model/selection') task.route = next.route;
139
+ else if (incoming && task.endedAt === null) {
140
+ Object.assign(task, mergePrompt(task, incoming));
141
+ task.scopeChanged ||= task.userMessages > 1;
142
+ // New human scope invalidates an earlier AI forecast until it is revised.
143
+ delete task.aiPlan;
144
+ } else if (event.type === 'assistant/message' || event.type === 'assistant/attempt') {
145
+ let stats = durableStreamStats(event.data.stream);
146
+ if (event.type === 'assistant/message' && event.data.usage) stats = { ...stats, usage: rawDshUsage(event.data.usage) };
147
+ const source = event.type === 'assistant/message' ? event.data.message.source : null;
148
+ const route = source ? { providerId: source.provider, modelId: source.model, reasoningEffort: task.route?.reasoningEffort ?? 'unknown' } : task.route ?? { providerId: 'unknown', modelId: 'unknown', reasoningEffort: 'unknown' };
149
+ const outcome: CallFact['outcome'] = event.type === 'assistant/message' && event.data.interrupted ? 'interrupted' : stats.finish === 'aborted' ? 'cancelled' : stats.finish === 'error' ? 'failed' : stats.finish === 'max-tokens' ? 'truncated' : event.type === 'assistant/attempt' ? 'failed' : 'completed';
150
+ task.calls = [...task.calls, { ...stats, id: `${state.sessionId}:${event.seq}`, seq: event.seq, turn: task.turn, step: event.data.step, startedAt: task.stepStartedAt, endedAt: event.time, route, mode: streamMode(stats), outcome, timingSource: 'step-boundary' }];
151
+ } else if (event.type === 'tool/call') {
152
+ task.tools = { ...task.tools, [event.data.callId]: { id: event.data.callId, name: event.data.name, startedAt: event.time, endedAt: null, failed: false } };
153
+ } else if (event.type === 'tool/result') {
154
+ const id = event.data.message.toolCallId;
155
+ const tool = task.tools[id];
156
+ if (tool) task.tools = { ...task.tools, [id]: { ...tool, endedAt: event.time, failed: !!event.data.message.isError } };
157
+ if (tool?.name === 'task_estimate_plan' && !event.data.message.isError) {
158
+ const text = event.data.message.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
159
+ const plan = readAiPlanResult(text, task.calls.length, event.time);
160
+ if (plan) task.aiPlan = plan;
161
+ }
162
+ } else if (event.type === 'turn/end') {
163
+ task.endedAt = event.time; task.state = turnEndState(event.data.reason.kind);
164
+ if (next.currentTurn === task.turn) next.currentTurn = null;
165
+ }
166
+ }
167
+ }
168
+ next.view = { revision: event.seq, currentTurn: next.currentTurn };
169
+ return next;
170
+ }
@@ -0,0 +1,16 @@
1
+ import { estimateRequestCostRange } from '../shared/forecast.ts';
2
+ import { resolveWithPublicPrices } from '../shared/public-prices.ts';
3
+ import type { ForecastCostUnit } from '../shared/pricing.ts';
4
+ import type { RequestBudget } from '../shared/workload.ts';
5
+ import type { PluginConfig, RouteOverride } from './config.ts';
6
+
7
+ export function forecastCall(request: RequestBudget, config: PluginConfig, route: RouteOverride | undefined, at: string): ForecastCostUnit {
8
+ const resolution = resolveWithPublicPrices({ providerId: request.route.providerId, requestedModelId: request.route.modelId, endpointFingerprint: request.route.endpointFingerprint }, config.prices, config.sameAs, at, config.usePublicPriceCatalog);
9
+ return estimateRequestCostRange(request, resolution, {
10
+ ...(route?.forecastCacheReadRatio ? { cacheReadRatio: route.forecastCacheReadRatio } : {}),
11
+ ...(route?.forecastCacheWrite5mTokens ? { cacheWrite5mTokens: route.forecastCacheWrite5mTokens } : {}),
12
+ ...(route?.forecastCacheWrite1hTokens ? { cacheWrite1hTokens: route.forecastCacheWrite1hTokens } : {}),
13
+ ...(route?.forecastReasoningTokens ? { reasoningTokens: route.forecastReasoningTokens } : {}),
14
+ outputIncludesReasoning: true,
15
+ }, { at, serviceTier: request.route.serviceTier });
16
+ }
@@ -0,0 +1,269 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
3
+ import type { Session, SessionId } from '@deepseek-ai/dsh-session';
4
+ import type { Agent } from '@deepseek-ai/dsh-agent';
5
+ import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-session-projection';
6
+ import type {} from '@deepseek-ai/dsh-llm';
7
+ import type {} from '@deepseek-ai/dsh-tools';
8
+ import type {} from '@deepseek-ai/dsh-system-prompt';
9
+ import { aiPlanSchema } from '../shared/ai-plan.ts';
10
+ import type {} from '@deepseek-ai/dsh-token-meter';
11
+ import type {} from '@deepseek-ai/dsh-storage-domain';
12
+ import type {} from '@deepseek-ai/dsh-config-editor';
13
+ import type {} from '@deepseek-ai/dsh-user-questions';
14
+ import type {} from '@deepseek-ai/dsh-user-approval';
15
+ import type {} from '@deepseek-ai/dsh-typert-registry';
16
+ import { readFile } from 'node:fs/promises';
17
+ import { z } from 'zod';
18
+ import { classifyTask } from '../shared/workload.ts';
19
+ import { importBaselines } from '../shared/baselines.ts';
20
+ import type { BaselineRecord } from '../shared/baselines.ts';
21
+ import { ALGORITHM_VERSION, PACKAGE_NAME } from '../shared/wire.ts';
22
+ import type { EstimateSnapshot, EstimatorView, ManagementAction, ManagementResult } from '../shared/wire.ts';
23
+ import { descriptors } from '../shared/remote-contract.ts';
24
+ import { retainedTimeForecast } from '../shared/retained-time.ts';
25
+ import { Config, validatePluginConfig } from './config.ts';
26
+ import type { PluginConfig } from './config.ts';
27
+ import { persistConfig } from './config-entry.ts';
28
+ import type { ConfigEditorLike, ConfigEntryLike } from './config-entry.ts';
29
+ import { initialFacts, foldFacts } from './facts.ts';
30
+ import type { FactsState } from './facts.ts';
31
+ import { Repository } from './repository.ts';
32
+ import { EstimatorEngine } from './engine.ts';
33
+
34
+ export { Config };
35
+ export const name = 'task-time-cost';
36
+ export const inject = ['agents', 'sessionProjections', 'storageDomain', 'tokenMeter', 'tools', 'typert', 'systemPrompt'];
37
+ declare module '@deepseek-ai/cordis' { interface Context { taskEstimator: TaskEstimatorService } }
38
+ declare module '@deepseek-ai/dsh-session-projection/types' { interface SessionProjectionMap { taskEstimator: { revision: number; currentTurn: number | null } } }
39
+
40
+ const factsSchema: z.ZodType<FactsState> = z.json().refine(value => {
41
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
42
+ return 'sessionId' in value && typeof value.sessionId === 'string' && 'tasks' in value && !!value.tasks && typeof value.tasks === 'object' && 'lastSeq' in value && typeof value.lastSeq === 'number';
43
+ }, 'Invalid estimator projection checkpoint').transform(value => value as unknown as FactsState);
44
+
45
+ export class TaskEstimatorService extends TypertRemoteService {
46
+ readonly engine: EstimatorEngine;
47
+ readonly projection: ProjectionHandle<FactsState>;
48
+ constructor(ctx: Context, engine: EstimatorEngine, projection: ProjectionHandle<FactsState>) {
49
+ super(ctx, 'taskEstimator'); this.engine = engine; this.projection = projection;
50
+ }
51
+ /** Attach whole-session totals so the Client can show one ETA for the conversation. */
52
+ private withSession(snapshot: EstimateSnapshot | null): EstimateSnapshot | null {
53
+ if (!snapshot) return snapshot;
54
+ let elapsed = 0;
55
+ let turns = 1;
56
+ for (const record of this.engine.repository.tasks.values()) {
57
+ const task = record.current;
58
+ if (task.sessionId !== snapshot.sessionId || task.turn === snapshot.turn) continue;
59
+ turns += 1;
60
+ elapsed += Number.isFinite(task.elapsedActiveMs) ? task.elapsedActiveMs : 0;
61
+ }
62
+ return { ...snapshot, sessionElapsedMs: elapsed + snapshot.elapsedActiveMs, sessionRemainingMs: snapshot.remainingMs, sessionTurns: turns };
63
+ }
64
+ private withRetained(snapshot: EstimateSnapshot | null): Pick<EstimatorView, 'snapshot' | 'lastForecast'> {
65
+ if (!snapshot || ['completed', 'failed', 'cancelled', 'interrupted'].includes(snapshot.state) || snapshot.remainingMs !== null) return { snapshot };
66
+ const previous = retainedTimeForecast(snapshot, this.engine.repository.tasks.get(snapshot.taskKey));
67
+ return previous ? { snapshot, lastForecast: previous } : { snapshot };
68
+ }
69
+ @Remote({ resources: { session: (sessionId: string) => sessionId as SessionId } })
70
+ async snapshot(sessionId: string, turn: number | null, signal: AbortSignal): Promise<EstimatorView> {
71
+ signal.throwIfAborted();
72
+ if (typeof sessionId !== 'string' || !sessionId || (turn !== null && (!Number.isSafeInteger(turn) || turn < 0))) throw new TypeError('Invalid session or turn');
73
+ const agent = this.ctx.agents.get(sessionId as SessionId);
74
+ if (!agent) {
75
+ const history = [...this.engine.repository.tasks.values()].filter(record => record.current.sessionId === sessionId && (turn === null || record.current.turn === turn)).sort((a, b) => b.savedAt - a.savedAt)[0];
76
+ const stale = history && history.current.algorithmVersion !== ALGORITHM_VERSION;
77
+ return { ...this.withRetained(this.withSession(history?.current ?? null)), available: this.engine.repository.available,
78
+ error: this.engine.repository.error ?? (stale ? 'History uses an earlier estimator version. Open this session to refresh its summary from the original events.' : null) };
79
+ }
80
+ const state = this.projection.stateOf(agent.session);
81
+ const target = turn ?? state.currentTurn ?? Math.max(-1, ...Object.keys(state.tasks).map(Number));
82
+ const task = state.tasks[String(target)];
83
+ if (!task) return { snapshot: null, available: this.engine.repository.available, error: this.engine.repository.error };
84
+ try {
85
+ if (state.error) this.engine.onDurable(sessionId, state, 'projection/error');
86
+ const snapshot = this.withSession(this.engine.estimate(sessionId, task, state.lastSeq))!;
87
+ return { ...this.withRetained(snapshot), available: this.engine.repository.available && !snapshot.error, error: snapshot.error ?? this.engine.repository.error };
88
+ } catch (error) {
89
+ this.engine.observerFailed(sessionId, task.turn, error);
90
+ return { snapshot: null, available: false, error: 'Estimation failed. The original task is unaffected; see plugin diagnostics.' };
91
+ }
92
+ }
93
+ @Remote
94
+ async manage(action: ManagementAction, payload: string, signal: AbortSignal): Promise<ManagementResult> {
95
+ signal.throwIfAborted();
96
+ if (this.ctx.invocation && this.ctx.invocation.peer.principal.kind !== 'owner') return { ok: false, message: 'Only the local owner can manage estimator data.' };
97
+ if (typeof payload !== 'string' || payload.length > 2_000_000) return { ok: false, message: 'Payload must be a string of at most 2 MB.' };
98
+ const repository = this.engine.repository;
99
+ try {
100
+ if (action === 'read') return { ok: true, message: '', data: this.engine.view() };
101
+ if (action === 'export') {
102
+ await repository.flush();
103
+ const tasks = [...repository.tasks.values()];
104
+ return { ok: true, message: 'Export contains local statistics only; no prompts or credentials.', exported: JSON.stringify({ schemaVersion: 1, exportedAt: new Date().toISOString(), algorithmVersion: ALGORITHM_VERSION,
105
+ historyDerivation: { pendingTasks: tasks.filter(task => task.current.algorithmVersion !== ALGORITHM_VERSION).length,
106
+ note: 'algorithmVersion identifies the exporter. Each snapshot retains its own algorithmVersion; summaries from earlier versions refresh when the original session events are loaded. Initial forecasts and historical price resolutions are retained.' },
107
+ config: this.engine.config, baselines: this.engine.baselines, resetAt: repository.resetAt, calls: [...repository.calls.values()], tasks }, null, 2) };
108
+ }
109
+ if (!repository.available) return { ok: false, message: repository.error ?? 'Local storage is unavailable.' };
110
+ if (action === 'saveConfig') {
111
+ const config = validatePluginConfig(JSON.parse(payload));
112
+ const editor = this.ctx.get('configEditor') as ConfigEditorLike | undefined;
113
+ if (!editor) return { ok: false, message: 'Configuration cannot be saved in this profile: configEditor is unavailable.' };
114
+ await persistConfig(editor, this.ctx.fiber.entry as ConfigEntryLike | undefined, config as unknown as Record<string, unknown>,
115
+ value => validatePluginConfig(value) as unknown as Record<string, unknown>);
116
+ return { ok: true, message: 'Configuration saved. The plugin reloads through the DSH lifecycle.' };
117
+ }
118
+ if (action === 'resetCalibration') {
119
+ await repository.resetCalibration();
120
+ if (!repository.available) return { ok: false, message: repository.error ?? 'Calibration reset could not be saved.' };
121
+ this.engine.rebuildCalibration();
122
+ return { ok: true, message: 'Local performance and workload calibration reset. History, configuration and DSH sessions were retained.', data: this.engine.view() };
123
+ }
124
+ if (action === 'importBaselines') {
125
+ const format = /^[\s\uFEFF]*[\[{]/.test(payload) ? 'json' : 'csv';
126
+ const imported = importBaselines(payload, format, this.engine.baselines);
127
+ const serialized = JSON.stringify({ schemaVersion: 1, records: imported.records });
128
+ await repository.saveBaselineImport(serialized);
129
+ if (!repository.available) return { ok: false, message: repository.error ?? 'Baseline import could not be saved.' };
130
+ this.engine.updateBaselines(imported.records);
131
+ return { ok: true, message: `Imported ${imported.imported} baseline records.`, data: this.engine.view() };
132
+ }
133
+ return { ok: false, message: 'Unknown management action.' };
134
+ } catch (error) {
135
+ const message = error instanceof Error ? error.message : String(error);
136
+ // Validation errors refer to package-owned fields, never model request bodies.
137
+ return { ok: false, message };
138
+ }
139
+ }
140
+ }
141
+
142
+ export async function apply(ctx: Context, rawConfig: unknown): Promise<void> {
143
+ const config: PluginConfig = validatePluginConfig(rawConfig);
144
+ const repository = new Repository(message => ctx.logger.warn(message));
145
+ await repository.open(ctx.storageDomain);
146
+ let baselines: BaselineRecord[] = [];
147
+ try {
148
+ const text = repository.baselineImport ?? await readFile(new URL('../data/baselines.json', import.meta.url), 'utf8');
149
+ baselines = importBaselines(text, 'json').records;
150
+ } catch (error) { repository.diagnose('baseline-load', 'Baseline data unavailable; engineering defaults remain active.'); ctx.logger.warn(error); }
151
+ const engine = new EstimatorEngine(config, repository, baselines);
152
+ const definition = {
153
+ key: 'taskEstimator', stateVersion: 3, stateSchema: factsSchema,
154
+ init: initialFacts,
155
+ apply(state, event) {
156
+ try { return foldFacts(state, event, prompt => classifyTask({ prompt, currentInputTokens: null }, config.classificationRules).kind); }
157
+ catch (error) {
158
+ repository.diagnose('projection-fold', 'A session observation could not be folded; this estimate is unavailable.');
159
+ return { ...state, lastSeq: event.seq, error: 'projection-fold-failed', view: { revision: event.seq, currentTurn: state.currentTurn } };
160
+ }
161
+ },
162
+ wire: { summary: false, viewSchema: z.object({ revision: z.number().int(), currentTurn: z.number().int().nullable() }), view: state => state.view },
163
+ } satisfies ProjectionDefinition<'taskEstimator', FactsState>;
164
+ const projection = await ctx.sessionProjections.register(definition);
165
+ const service = new TaskEstimatorService(ctx, engine, projection);
166
+ ctx.typert.register({ package: PACKAGE_NAME, face: 'host', schemas: [], invocations: descriptors,
167
+ model: { services: [{ key: 'taskEstimator', exportName: 'TaskEstimatorService', tags: [], members: [
168
+ { kind: 'method', name: 'snapshot', signature: 'async snapshot(sessionId: string, turn: number | null, signal: AbortSignal): Promise<EstimatorView>' },
169
+ { kind: 'method', name: 'manage', signature: 'async manage(action: ManagementAction, payload: string, signal: AbortSignal): Promise<ManagementResult>' },
170
+ ], types: [] }], events: [], objects: [] } });
171
+
172
+ function safe(agent: Agent | undefined, operation: () => void): void {
173
+ try { operation(); }
174
+ catch (error) {
175
+ if (agent) { const boundary = ctx.agents.turnBoundaryOf(agent.session); engine.observerFailed(agent.id, boundary.lastTurn, error); }
176
+ else repository.diagnose('observer-failed', 'An estimator observer failed; the original operation continues.');
177
+ }
178
+ }
179
+ function checkpoint(agent: Agent): void {
180
+ const state = projection.stateOf(agent.session);
181
+ const task = state.currentTurn === null ? Object.values(state.tasks).at(-1) : state.tasks[String(state.currentTurn)];
182
+ if (task) engine.persist(agent.id, task, state.lastSeq);
183
+ }
184
+ ctx.on('session/event', (session, event) => {
185
+ const agent = ctx.agents.get(session.id);
186
+ safe(agent, () => {
187
+ const state = projection.stateOf(session);
188
+ engine.onDurable(session.id, state, event.type);
189
+ // Persist at semantic checkpoints, never per streamed character.
190
+ if (['turn/start', 'turn/end', 'assistant/message', 'assistant/attempt', 'tool/result', 'user/message', 'model/selection'].includes(event.type) && agent) checkpoint(agent);
191
+ if (event.type === 'turn/end') void repository.prune(config);
192
+ });
193
+ });
194
+ ctx.on('agent/assistant-stream', ({ agent, frame }) => safe(agent, () => {
195
+ const state = projection.stateOf(agent.session);
196
+ if (frame.type === 'start') {
197
+ try { engine.setInput(agent.id, frame.turn, ctx.tokenMeter.measure(agent.session).totalTokens); }
198
+ catch { engine.setInput(agent.id, frame.turn, null); }
199
+ }
200
+ engine.onStream(agent.id, frame, state);
201
+ if (frame.type === 'end') checkpoint(agent);
202
+ }));
203
+ ctx.on('tools/execute', async (exec, next) => {
204
+ let ticket: ReturnType<typeof engine.runtime.beginTool> | undefined;
205
+ if (exec.agent && !exec.parent) safe(exec.agent, () => { const boundary = ctx.agents.turnBoundaryOf(exec.agent!.session); ticket = engine.runtime.beginTool(exec.agent!.id, boundary.lastTurn, exec.callId); });
206
+ try { return await next(); }
207
+ finally { if (ticket) safe(exec.agent, () => { engine.runtime.endTool(ticket!); engine.invalidate(ticket!.sessionId, ticket!.turn); }); }
208
+ });
209
+ ctx.on('user-questions/request', async (request, next) => {
210
+ const agent = request.agent;
211
+ let resume: (() => void) | undefined;
212
+ if (agent) safe(agent, () => { const turn = ctx.agents.turnBoundaryOf(agent.session).lastTurn; resume = engine.runtime.pause(agent.id, turn); engine.invalidate(agent.id, turn); checkpoint(agent); });
213
+ try { return await next(); }
214
+ finally { if (resume) safe(agent, () => { resume!(); if (agent) { engine.invalidate(agent.id, ctx.agents.turnBoundaryOf(agent.session).lastTurn); checkpoint(agent); } }); }
215
+ });
216
+ ctx.on('approval/request', async (request, next) => {
217
+ let resume: (() => void) | undefined;
218
+ safe(request.agent, () => { const turn = ctx.agents.turnBoundaryOf(request.agent.session).lastTurn; resume = engine.runtime.pause(request.agent.id, turn); engine.invalidate(request.agent.id, turn); checkpoint(request.agent); });
219
+ try { return await next(); }
220
+ finally { if (resume) safe(request.agent, () => { resume!(); engine.invalidate(request.agent.id, ctx.agents.turnBoundaryOf(request.agent.session).lastTurn); checkpoint(request.agent); }); }
221
+ });
222
+ ctx.on('session/flush', async () => { await repository.flush(); });
223
+ ctx.on('agent/disposed', ({ agent }) => { safe(agent, () => checkpoint(agent)); engine.cleanupSession(agent.id); });
224
+ ctx.tools.register({
225
+ name: 'task_estimator', description: 'Read task time/cost estimates or manage this plugin’s local configuration, calibration, and JSON/CSV baselines. Export returns redacted statistics. Reset preserves history and DSH sessions.',
226
+ parameters: { type: 'object', properties: {
227
+ action: { type: 'string', enum: ['snapshot', 'read', 'saveConfig', 'export', 'resetCalibration', 'importBaselines'] },
228
+ turn: { type: 'integer', minimum: 0, description: 'Completed turn number; omit for the current or latest turn.' },
229
+ payload: { type: 'string', description: 'Full JSON config for saveConfig, JSON/CSV contents for importBaselines; omit for other actions.' },
230
+ }, required: ['action'], additionalProperties: false },
231
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => {
232
+ const text = JSON.stringify(value, null, 2);
233
+ return [{ type: 'text', text }];
234
+ } },
235
+ async execute(args, exec) {
236
+ const input = z.object({ action: z.enum(['snapshot', 'read', 'saveConfig', 'export', 'resetCalibration', 'importBaselines']), turn: z.number().int().nonnegative().optional(), payload: z.string().max(2_000_000).optional() }).strict().parse(args);
237
+ if (input.action === 'snapshot') {
238
+ if (!exec.agent) return { available: false, snapshot: null, error: 'A session is required.' };
239
+ return await service.snapshot(exec.agent.id, input.turn ?? null, exec.signal);
240
+ }
241
+ return await service.manage(input.action, input.payload ?? '', exec.signal);
242
+ },
243
+ });
244
+ ctx.tools.register({
245
+ name: 'task_estimate_plan',
246
+ description: 'Update the current task ETA from your assessment of the work still needed. Submit after understanding a multi-step task, and revise when its scope or remaining work materially changes. The Host combines the plan with this route’s observed response times. These are reference estimates, not completion promises.',
247
+ parameters: { type: 'object', properties: {
248
+ remainingCalls: { type: 'object', description: 'Future model requests after this reporting call, including final answer and verification; ordered integer bounds, 1–500.', properties: { low: { type: 'integer', minimum: 1, maximum: 500 }, high: { type: 'integer', minimum: 1, maximum: 500 } }, required: ['low', 'high'], additionalProperties: false },
249
+ remainingOutputTokens: { type: 'object', description: 'Total future visible text/tool-argument tokens, excluding hidden reasoning; ordered bounds, 0–2000000.', properties: { low: { type: 'integer', minimum: 0, maximum: 2000000 }, high: { type: 'integer', minimum: 0, maximum: 2000000 } }, required: ['low', 'high'], additionalProperties: false },
250
+ remainingToolSeconds: { type: 'object', description: 'Future tool execution time, excluding model requests and human waits; ordered bounds, 0–86400 seconds.', properties: { low: { type: 'integer', minimum: 0, maximum: 86400 }, high: { type: 'integer', minimum: 0, maximum: 86400 } }, required: ['low', 'high'], additionalProperties: false },
251
+ stage: { type: 'string', enum: ['planning', 'implementation', 'verification', 'finishing'] },
252
+ }, required: ['remainingCalls', 'remainingOutputTokens', 'remainingToolSeconds', 'stage'], additionalProperties: false },
253
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
254
+ async execute(args, exec) {
255
+ if (!exec.agent || exec.signal.aborted) throw new Error('An active task is required.');
256
+ const state = projection.stateOf(exec.agent.session);
257
+ if (state.currentTurn === null || !state.tasks[String(state.currentTurn)] || state.tasks[String(state.currentTurn)].endedAt !== null) throw new Error('An active task is required.');
258
+ return { kind: 'task-estimate-plan', version: 1, plan: aiPlanSchema.parse(args) };
259
+ },
260
+ });
261
+ ctx.systemPrompt.section({ name: 'task-estimate-planning', order: 1_000,
262
+ text: 'For a multi-step user task, submit a task_estimate_plan after understanding the scope, preferably alongside your initial work tools. Include implementation, verification and delivery. Revise it only when scope or remaining work materially changes or the budget is exceeded. Count work remaining after the reporting call. Use task_estimator snapshot route timings when useful; never invent measured performance or treat call count as percentage complete. Skip planning for trivial answers. This uses the executing agent; do not start another model request just to estimate or poll.' });
263
+ // Existing sessions are folded once on demand by the projection owner. No log rescans per frame.
264
+ for (const agent of ctx.agents.list()) safe(agent, () => { projection.stateOf(agent.session); engine.runtime.task(agent.id, ctx.agents.turnBoundaryOf(agent.session).lastTurn); });
265
+ ctx.effect(() => async () => {
266
+ for (const agent of ctx.agents.list()) safe(agent, () => checkpoint(agent));
267
+ engine.dispose(); await repository.close();
268
+ });
269
+ }
@@ -0,0 +1,175 @@
1
+ import { z } from 'zod';
2
+ import type { CallRecord } from './repository.ts';
3
+ import type { CallFact } from './facts.ts';
4
+ import type { CallObservation } from '../shared/performance.ts';
5
+ import type { RouteIdentity } from '../shared/types.ts';
6
+ import type { RawUsage, NormalizedUsage } from '../shared/usage.ts';
7
+ import { BILLABLE_CATEGORIES, INPUT_CATEGORIES, sumKnown } from '../shared/usage.ts';
8
+ import type { CallCost, PriceEntry, PriceResolution } from '../shared/pricing.ts';
9
+ import { validatePrices } from '../shared/pricing.ts';
10
+ import { MONEY_DECIMALS, RATE_DECIMALS, parseFixed } from '../shared/money.ts';
11
+
12
+ const identifier = z.string().min(1).max(1024);
13
+ const metadata = z.string().max(16_384);
14
+ const messages = z.array(metadata).max(10_000);
15
+ const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
16
+ // Real stream timestamps include fractional performance.now() deltas. Counts do not.
17
+ const milliseconds = z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER);
18
+ const mode = z.enum(['text', 'tool', 'mixed', 'unknown', 'non-streaming']);
19
+ const sourceKind = z.enum(['public-measured', 'local-measured', 'heuristic']);
20
+ const priority = z.enum(['user-exact', 'provider-wildcard', 'provider-catalog', 'public-catalog']);
21
+ const currency = z.string().regex(/^[A-Z]{3}$/);
22
+ const date = z.string().min(1).max(128).refine(value => Number.isFinite(Date.parse(value)), 'Invalid pricing date');
23
+
24
+ function decimal(places: number) {
25
+ return z.string().min(1).max(1024).refine(value => {
26
+ try { parseFixed(value, places); return true; } catch { return false; }
27
+ }, `Expected a nonnegative fixed decimal with at most ${places} significant fractional places`);
28
+ }
29
+ const amount = decimal(MONEY_DECIMALS);
30
+ const rate = decimal(RATE_DECIMALS);
31
+
32
+ const routeSchema: z.ZodType<RouteIdentity> = z.object({
33
+ providerId: identifier, endpointFingerprint: identifier, modelId: identifier,
34
+ requestMode: mode, reasoningEffort: identifier, serviceTier: identifier,
35
+ inputBucket: identifier.optional(), cacheBucket: identifier.optional(), concurrencyBucket: identifier.optional(),
36
+ mixedRoute: z.boolean().optional(),
37
+ }).strict();
38
+ const factRouteSchema = z.object({ providerId: identifier, modelId: identifier, reasoningEffort: identifier }).strict();
39
+ const rawUsageSchema: z.ZodType<RawUsage> = z.object({
40
+ inputTokens: count.nullable().optional(), cacheReadTokens: count.nullable().optional(),
41
+ cacheWriteTokens: count.nullable().optional(), cacheWrite5mTokens: count.nullable().optional(),
42
+ cacheWrite1hTokens: count.nullable().optional(), outputTokens: count.nullable().optional(),
43
+ reasoningTokens: count.nullable().optional(), visibleOutputTokens: count.nullable().optional(),
44
+ totalTokens: count.nullable().optional(),
45
+ }).strict();
46
+
47
+ const normalizedUsageSchema: z.ZodType<NormalizedUsage> = z.object({
48
+ inputTokens: count.nullable(), cacheReadTokens: count.nullable(), cacheWrite5mTokens: count.nullable(),
49
+ cacheWrite1hTokens: count.nullable(), cacheWriteUnknownTokens: count.nullable(), outputTokens: count.nullable(),
50
+ reasoningTokens: count.nullable(), visibleOutputTokens: count.nullable(), promptTokens: count.nullable(), totalTokens: count.nullable(),
51
+ status: z.enum(['complete', 'partial', 'unknown']), exact: z.boolean(), diagnostics: messages,
52
+ }).strict().superRefine((usage, ctx) => {
53
+ const conflict = usage.diagnostics.some(message => message.startsWith('conflict:'));
54
+ const invalid = usage.diagnostics.some(message => message.startsWith('invalid:'));
55
+ const complete = BILLABLE_CATEGORIES.every(key => usage[key] !== null);
56
+ const anyKnown = BILLABLE_CATEGORIES.some(key => usage[key] !== null);
57
+ const expectedStatus = complete && !conflict ? 'complete' : anyKnown ? 'partial' : 'unknown';
58
+ if (usage.status !== expectedStatus) ctx.addIssue({ code: 'custom', path: ['status'], message: 'Usage status disagrees with known categories' });
59
+ if (usage.exact !== (complete && !conflict && !invalid)) ctx.addIssue({ code: 'custom', path: ['exact'], message: 'Usage exactness disagrees with known categories and diagnostics' });
60
+ const prompt = sumKnown(INPUT_CATEGORIES.map(key => usage[key]));
61
+ if (usage.promptTokens !== prompt) ctx.addIssue({ code: 'custom', path: ['promptTokens'], message: 'Prompt tokens disagree with exclusive input categories' });
62
+ const total = conflict ? null : sumKnown([prompt, usage.outputTokens]);
63
+ if (usage.totalTokens !== total) ctx.addIssue({ code: 'custom', path: ['totalTokens'], message: 'Total tokens disagree with normalized usage' });
64
+ });
65
+
66
+ const factSchema: z.ZodType<CallFact> = z.object({
67
+ id: identifier, seq: count, turn: count, step: count,
68
+ startedAt: milliseconds, endedAt: milliseconds, route: factRouteSchema, mode,
69
+ firstContentAt: milliseconds.nullable(), firstTextAt: milliseconds.nullable(), lastContentAt: milliseconds.nullable(),
70
+ textChars: count, reasoningChars: count, toolChars: count, textDeltas: count,
71
+ usage: rawUsageSchema.nullable(),
72
+ // The official FinishReasonMap is merge-extensible. A closed enum would discard valid adapters.
73
+ finish: identifier.nullable(),
74
+ outcome: z.enum(['completed', 'failed', 'cancelled', 'truncated', 'interrupted']),
75
+ timingSource: z.enum(['step-boundary', 'live-attempt']),
76
+ // A first-release spread also persisted these harmless LiveAttempt fields. Admit only this
77
+ // bounded, typed whitelist, then remove it; all other extra fields still fail strict parsing.
78
+ startedMono: milliseconds.optional(),
79
+ lastIndex: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER).optional(),
80
+ sessionId: identifier.optional(),
81
+ }).strict().transform(({ startedMono: _mono, lastIndex: _index, sessionId: _session, ...fact }) => fact);
82
+
83
+ const unitPricesSchema = z.object({
84
+ inputTokens: rate.nullable().optional(), cacheReadTokens: rate.nullable().optional(),
85
+ cacheWrite5mTokens: rate.nullable().optional(), cacheWrite1hTokens: rate.nullable().optional(),
86
+ cacheWriteUnknownTokens: rate.nullable().optional(), outputTokens: rate.nullable().optional(),
87
+ }).strict();
88
+ const ruleSchema = z.object({
89
+ id: identifier,
90
+ when: z.object({
91
+ promptTokensAbove: count.optional(), serviceTier: identifier.optional(),
92
+ utcHours: z.object({ start: z.number().int().min(0).max(23), end: z.number().int().min(0).max(23) }).strict().optional(),
93
+ }).strict(),
94
+ mode: z.enum(['whole-request', 'excess-only']).optional(),
95
+ allocationOrder: z.array(z.enum(INPUT_CATEGORIES)).max(INPUT_CATEGORIES.length).optional(),
96
+ prices: unitPricesSchema.optional(), multiplier: rate.optional(),
97
+ }).strict();
98
+ const entrySchema: z.ZodType<PriceEntry> = z.object({
99
+ id: identifier, providerId: identifier, endpointFingerprint: identifier.optional(), modelId: identifier,
100
+ priority, currency, unit: z.literal('per-million-tokens'), prices: unitPricesSchema,
101
+ explicitFree: z.boolean().optional(), multiplier: rate.optional(), rules: z.array(ruleSchema).max(10_000).optional(),
102
+ sourceKind, sourceUrl: metadata.nullable(), version: identifier, effectiveFrom: date, effectiveUntil: date.optional(),
103
+ }).strict().superRefine((entry, ctx) => {
104
+ // Reuse the actual tier/free/rate/date rules; do not maintain a weaker storage-only variant.
105
+ try { validatePrices([entry]); } catch {
106
+ ctx.addIssue({ code: 'custom', message: 'Invalid persisted pricing rules' });
107
+ }
108
+ });
109
+ const resolutionSchema: z.ZodType<PriceResolution> = z.object({
110
+ entry: entrySchema.nullable(),
111
+ match: z.enum(['user-exact', 'provider-wildcard', 'provider-catalog', 'public-catalog', 'same-as', 'unpriced']),
112
+ billingModelId: identifier, reasons: messages,
113
+ }).strict().superRefine((resolution, ctx) => {
114
+ if (resolution.entry === null ? resolution.match !== 'unpriced' : resolution.match !== 'same-as' && resolution.match !== resolution.entry.priority) {
115
+ ctx.addIssue({ code: 'custom', path: ['match'], message: 'Price match disagrees with the resolved entry' });
116
+ }
117
+ });
118
+
119
+ const costSchema: z.ZodType<CallCost> = z.object({
120
+ status: z.enum(['complete', 'partial', 'unpriced', 'free']), currency: currency.nullable(),
121
+ amount: amount.nullable(), knownAmount: amount.nullable(), priceId: identifier.nullable(), priceVersion: identifier.nullable(),
122
+ appliedRuleIds: z.array(identifier).max(10_000), unpricedItems: messages, reasons: messages,
123
+ }).strict().superRefine((cost, ctx) => {
124
+ if (cost.status === 'complete' || cost.status === 'free') {
125
+ if (cost.currency === null || cost.amount === null || cost.knownAmount === null || cost.unpricedItems.length) {
126
+ ctx.addIssue({ code: 'custom', message: 'A complete or free cost needs currency, both amounts, and no unpriced items' });
127
+ return;
128
+ }
129
+ // Decimal refinements can already have failed. safeParse must still return failure, never throw.
130
+ try {
131
+ const total = parseFixed(cost.amount, MONEY_DECIMALS);
132
+ if (total !== parseFixed(cost.knownAmount, MONEY_DECIMALS) || (cost.status === 'free' ? total !== 0n : total === 0n)) {
133
+ ctx.addIssue({ code: 'custom', path: ['amount'], message: 'Cost amount disagrees with status or known amount' });
134
+ }
135
+ } catch { /* The decimal schema owns the validation issue. */ }
136
+ } else if (cost.amount !== null) {
137
+ ctx.addIssue({ code: 'custom', path: ['amount'], message: 'An incomplete cost cannot claim a complete amount' });
138
+ }
139
+ if (cost.knownAmount !== null && cost.currency === null) ctx.addIssue({ code: 'custom', path: ['currency'], message: 'A known amount needs a currency' });
140
+ });
141
+
142
+ const observationSchema: z.ZodType<CallObservation> = z.object({
143
+ attemptId: identifier, route: routeSchema, startedAtMs: milliseconds, endedAtMs: milliseconds,
144
+ firstContentAtMs: milliseconds.nullable(), firstTextAtMs: milliseconds.nullable(), lastContentAtMs: milliseconds.nullable(),
145
+ outcome: z.enum(['completed', 'failed', 'cancelled', 'interrupted', 'timeout', 'truncated']),
146
+ streaming: z.boolean(), buffered: z.boolean().optional(), hiddenReasoningSeparable: z.boolean(), toolOnly: z.boolean().optional(),
147
+ visibleTextTokens: count.nullable(), tokenMeasurement: z.enum(['reported', 'tokenizer-approximate']).optional(),
148
+ userPausedMs: milliseconds.optional(), processGapMs: milliseconds.optional(), includedInternalRetryMs: milliseconds.optional(),
149
+ timingSource: identifier,
150
+ }).strict();
151
+ const routeFields = ['providerId', 'endpointFingerprint', 'modelId', 'requestMode', 'reasoningEffort', 'serviceTier', 'inputBucket', 'cacheBucket', 'concurrencyBucket', 'mixedRoute'] as const;
152
+
153
+ /** Strict, lossless admission for immutable historical call facts and their original valuation.
154
+ * No repricing, coercion, null defaults, or raw-content passthrough occurs at this boundary.
155
+ * Clock/window anomalies are retained for the performance core to exclude, without losing usage/cost.
156
+ */
157
+ export const callRecordSchema: z.ZodType<CallRecord> = z.object({
158
+ id: identifier, savedAt: milliseconds, fact: factSchema, route: routeSchema,
159
+ usage: normalizedUsageSchema, cost: costSchema, resolution: resolutionSchema,
160
+ observation: observationSchema.nullable(),
161
+ }).strict().superRefine((record, ctx) => {
162
+ for (const field of ['providerId', 'modelId', 'reasoningEffort'] as const) {
163
+ if (record.fact.route[field] !== record.route[field]) ctx.addIssue({ code: 'custom', path: ['fact', 'route', field], message: 'Fact belongs to a different route' });
164
+ }
165
+ if (record.fact.mode !== record.route.requestMode) ctx.addIssue({ code: 'custom', path: ['route', 'requestMode'], message: 'Request mode disagrees with the fact' });
166
+ if (record.observation && routeFields.some(field => record.observation!.route[field] !== record.route[field])) {
167
+ ctx.addIssue({ code: 'custom', path: ['observation', 'route'], message: 'Observation belongs to a different provider/configuration bucket' });
168
+ }
169
+ const entry = record.resolution.entry;
170
+ if (record.cost.priceId !== (entry?.id ?? null) || record.cost.priceVersion !== (entry?.version ?? null)) {
171
+ ctx.addIssue({ code: 'custom', path: ['cost', 'priceVersion'], message: 'Historical cost and resolved price identity disagree' });
172
+ }
173
+ if (record.cost.currency !== (entry?.currency ?? null)) ctx.addIssue({ code: 'custom', path: ['cost', 'currency'], message: 'Historical cost currency disagrees with the resolved price' });
174
+ if (entry === null && record.cost.status !== 'unpriced') ctx.addIssue({ code: 'custom', path: ['cost', 'status'], message: 'A missing price cannot be presented as priced or free' });
175
+ });