@trazum/cli 2.5.1 → 2.6.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/README.md +75 -6
- package/dist/filter.d.ts +2 -0
- package/dist/filter.d.ts.map +1 -0
- package/dist/filter.js +187 -0
- package/dist/filter.js.map +1 -0
- package/dist/gateway-server.d.ts +2 -0
- package/dist/gateway-server.d.ts.map +1 -1
- package/dist/gateway-server.js +49 -9
- package/dist/gateway-server.js.map +1 -1
- package/dist/gateway-spend.d.ts +32 -0
- package/dist/gateway-spend.d.ts.map +1 -0
- package/dist/gateway-spend.js +116 -0
- package/dist/gateway-spend.js.map +1 -0
- package/dist/html.d.ts.map +1 -1
- package/dist/html.js +22 -1
- package/dist/html.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +45 -3
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +45 -3
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/types.d.ts +13 -1
- package/dist/i18n/types.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +125 -61
- package/dist/index.js.map +1 -1
- package/dist/markdown.d.ts.map +1 -1
- package/dist/markdown.js +19 -1
- package/dist/markdown.js.map +1 -1
- package/dist/pdf.d.ts.map +1 -1
- package/dist/pdf.js +38 -1
- package/dist/pdf.js.map +1 -1
- package/dist/serve-import-schema.d.ts +34 -0
- package/dist/serve-import-schema.d.ts.map +1 -0
- package/dist/serve-import-schema.js +31 -0
- package/dist/serve-import-schema.js.map +1 -0
- package/dist/serve-import.d.ts +43 -0
- package/dist/serve-import.d.ts.map +1 -0
- package/dist/serve-import.js +49 -0
- package/dist/serve-import.js.map +1 -0
- package/dist/serve-savings-schema.d.ts +65 -0
- package/dist/serve-savings-schema.d.ts.map +1 -0
- package/dist/serve-savings-schema.js +54 -0
- package/dist/serve-savings-schema.js.map +1 -0
- package/dist/serve-savings.d.ts +55 -0
- package/dist/serve-savings.d.ts.map +1 -0
- package/dist/serve-savings.js +144 -0
- package/dist/serve-savings.js.map +1 -0
- package/dist/serve-schema.d.ts +606 -0
- package/dist/serve-schema.d.ts.map +1 -0
- package/dist/serve-schema.js +151 -0
- package/dist/serve-schema.js.map +1 -0
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +37 -5
- package/dist/serve.js.map +1 -1
- package/dist/task-files.d.ts +9 -0
- package/dist/task-files.d.ts.map +1 -0
- package/dist/task-files.js +136 -0
- package/dist/task-files.js.map +1 -0
- package/dist/task.d.ts +2 -0
- package/dist/task.d.ts.map +1 -0
- package/dist/task.js +137 -0
- package/dist/task.js.map +1 -0
- package/package.json +2 -2
- package/src/filter.ts +150 -0
- package/src/gateway-server.ts +46 -10
- package/src/gateway-spend.ts +120 -0
- package/src/html.ts +25 -1
- package/src/i18n/en.ts +47 -4
- package/src/i18n/es.ts +47 -4
- package/src/i18n/types.ts +14 -1
- package/src/index.ts +115 -63
- package/src/markdown.ts +20 -1
- package/src/pdf.ts +36 -1
- package/src/serve-import-schema.ts +31 -0
- package/src/serve-import.ts +57 -0
- package/src/serve-savings-schema.ts +53 -0
- package/src/serve-savings.ts +140 -0
- package/src/serve-schema.ts +155 -0
- package/src/serve.ts +38 -5
- package/src/task-files.ts +114 -0
- package/src/task.ts +119 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** OpenAPI 3.1 schemas for the text-only savings lifecycle. */
|
|
2
|
+
const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` });
|
|
3
|
+
const nullable = (schema: object) => ({ anyOf: [schema, { type: 'null' }] });
|
|
4
|
+
const object = (properties: Record<string, unknown>, required = Object.keys(properties)) => ({
|
|
5
|
+
type: 'object', properties, required, additionalProperties: false,
|
|
6
|
+
});
|
|
7
|
+
const amount = { type: 'number', minimum: 0 };
|
|
8
|
+
const text = { type: 'string' };
|
|
9
|
+
const count = { type: 'integer', minimum: 0 };
|
|
10
|
+
const log = { type: 'string', minLength: 1, maxLength: 1_000_000, description: 'Non-whitespace normalized usage JSONL text, never a path. Whole request is limited to 1,000,000 UTF-8 bytes.' };
|
|
11
|
+
const pair = object({ before: amount, after: amount });
|
|
12
|
+
export const SAVINGS_SCHEMAS = {
|
|
13
|
+
SavingsPlanRequest: object({ log }),
|
|
14
|
+
SavingsVerifyRequest: object({ log, plan: { ...log, description: 'Serialized Trazum PlanDocument JSON text, never a path or response envelope. Subject to defensive nested validation and the shared whole-body byte cap.' } }),
|
|
15
|
+
SavingsEvidence: object({
|
|
16
|
+
basis: text, pricedCalls: count, pricedUsd: amount, unpricedCalls: count,
|
|
17
|
+
unpricedModels: { type: 'array', items: text }, skippedLines: { type: 'array', items: { type: 'integer', minimum: 1 } },
|
|
18
|
+
span: nullable(ref('Window')), pricingLastReviewed: text, pricingOverlay: { type: 'boolean' },
|
|
19
|
+
complete: { type: 'boolean', description: 'No unpriced calls or skipped lines; not proof of a complete invoice, comparable periods or task quality.' },
|
|
20
|
+
}),
|
|
21
|
+
SavingsAssumption: { oneOf: [
|
|
22
|
+
object({ kind: { const: 'model-capability' }, model: text }),
|
|
23
|
+
object({ kind: { enum: ['batch-window', 'retry-pattern-real', 'max-tokens-fits', 'traffic-pattern-holds'] } }),
|
|
24
|
+
] },
|
|
25
|
+
SavingsAction: object({
|
|
26
|
+
kind: { enum: ['route', 'batch', 'route+batch', 'fix-truncation', 'fix-caching'] }, label: text, model: text,
|
|
27
|
+
savingUsd: nullable(amount), stakeUsd: nullable(amount), assumes: { type: 'array', items: ref('SavingsAssumption') },
|
|
28
|
+
check: nullable(text), detail: object({
|
|
29
|
+
routeTo: object({ id: text, displayName: text }),
|
|
30
|
+
measured: { type: 'object', additionalProperties: amount },
|
|
31
|
+
baseline: object({ calls: amount, usd: amount, inputPerCallTokens: amount, outputPerCallTokens: amount }),
|
|
32
|
+
}, []),
|
|
33
|
+
}),
|
|
34
|
+
SavingsPlan: object({
|
|
35
|
+
schemaVersion: { const: 1 }, span: nullable(ref('Window')), pricingLastReviewed: text,
|
|
36
|
+
actions: { type: 'array', items: ref('SavingsAction') }, projectedSavingUsd: amount, measuredStakeUsd: amount, totalUsd: amount,
|
|
37
|
+
createdAt: text,
|
|
38
|
+
}, ['schemaVersion', 'span', 'pricingLastReviewed', 'actions', 'projectedSavingUsd', 'measuredStakeUsd', 'totalUsd']),
|
|
39
|
+
SavingsVerifiedAction: object({
|
|
40
|
+
action: ref('SavingsAction'), outcome: { enum: ['arrived', 'not-arrived', 'cannot-tell'] },
|
|
41
|
+
reason: { enum: ['workload-vanished', 'fields-stopped', 'tier-not-recorded', null] },
|
|
42
|
+
observed: { type: 'object', additionalProperties: { type: ['number', 'string', 'null'] } },
|
|
43
|
+
attribution: nullable(object({ calls: pair, inputPerCallTokens: pair, outputPerCallTokens: pair }, [])),
|
|
44
|
+
gateFailing: { type: 'boolean' },
|
|
45
|
+
}),
|
|
46
|
+
SavingsVerification: object({
|
|
47
|
+
schemaVersion: { const: 1 }, planCreatedAt: nullable(text), planPricing: text, currentPricing: text,
|
|
48
|
+
pricesChanged: { type: 'boolean' }, actions: { type: 'array', items: ref('SavingsVerifiedAction') },
|
|
49
|
+
arrived: count, notArrived: count, cannotTell: count, gateFailures: count,
|
|
50
|
+
}),
|
|
51
|
+
SavingsPlanAnswer: object({ schemaVersion: { const: 1 }, plan: ref('SavingsPlan'), evidence: ref('SavingsEvidence'), limitations: { type: 'array', items: text } }),
|
|
52
|
+
SavingsVerifyAnswer: object({ schemaVersion: { const: 1 }, verification: ref('SavingsVerification'), evidence: ref('SavingsEvidence'), limitations: { type: 'array', items: text } }),
|
|
53
|
+
};
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/** Pure HTTP savings handlers. Text only; never paths, provider calls or writes. */
|
|
2
|
+
import { BUNDLED_CATALOGUE, profileUsage, billLevers, buildPlan, parsePlanDocument, verifyPlan } from '@trazum/core';
|
|
3
|
+
import type { PricingCatalogue } from '@trazum/core';
|
|
4
|
+
|
|
5
|
+
export class SavingsInputError extends Error {}
|
|
6
|
+
export interface SavingsPlanPayload { log: string }
|
|
7
|
+
export interface SavingsVerifyPayload extends SavingsPlanPayload { plan: string }
|
|
8
|
+
|
|
9
|
+
export function validateSavingsPayload(value: unknown, verify: false): asserts value is SavingsPlanPayload;
|
|
10
|
+
export function validateSavingsPayload(value: unknown, verify: true): asserts value is SavingsVerifyPayload;
|
|
11
|
+
export function validateSavingsPayload(value: unknown, verify: boolean): asserts value is SavingsPlanPayload | SavingsVerifyPayload;
|
|
12
|
+
export function validateSavingsPayload(value: unknown, verify: boolean): void {
|
|
13
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new SavingsInputError('The body must be a JSON object.');
|
|
14
|
+
const payload = value as Record<string, unknown>;
|
|
15
|
+
const fields = verify ? ['log', 'plan'] : ['log'];
|
|
16
|
+
if (Object.keys(payload).some((key) => !fields.includes(key))) throw new SavingsInputError('Unknown properties are not accepted for savings requests.');
|
|
17
|
+
for (const key of fields) {
|
|
18
|
+
if (typeof payload[key] !== 'string' || payload[key].trim() === '') throw new SavingsInputError(`${key} must be non-empty text, not a file path.`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function savingsReport(log: string, catalogue: PricingCatalogue) {
|
|
23
|
+
const report = profileUsage(log, { catalogue });
|
|
24
|
+
if (report.total.calls + report.unpriced.calls === 0) {
|
|
25
|
+
throw new SavingsInputError('log contains no readable usage records; pass normalized JSONL text with model and token counts');
|
|
26
|
+
}
|
|
27
|
+
if (!Number.isFinite(report.total.totalUsd)) throw new SavingsInputError('log totals exceed finite pricing bounds');
|
|
28
|
+
return report;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function savingsEvidence(report: ReturnType<typeof profileUsage>, catalogue: PricingCatalogue) {
|
|
32
|
+
return {
|
|
33
|
+
basis: 'Recorded token counts priced with the selected catalogue; not a reconciled provider invoice.',
|
|
34
|
+
pricedCalls: report.total.calls,
|
|
35
|
+
pricedUsd: report.total.totalUsd,
|
|
36
|
+
unpricedCalls: report.unpriced.calls,
|
|
37
|
+
unpricedModels: report.unpricedModels,
|
|
38
|
+
skippedLines: report.skippedLines,
|
|
39
|
+
span: report.span,
|
|
40
|
+
pricingLastReviewed: catalogue.lastReviewed,
|
|
41
|
+
pricingOverlay: catalogue !== BUNDLED_CATALOGUE,
|
|
42
|
+
complete: report.unpriced.calls === 0 && report.skippedLines.length === 0,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The shared parser accepts older plans. Check the nested fields verification dereferences too. */
|
|
47
|
+
function savingsPlan(text: string) {
|
|
48
|
+
const parsed = parsePlanDocument(text);
|
|
49
|
+
if (!parsed.ok) {
|
|
50
|
+
const detail = parsed.why.kind === 'action-malformed'
|
|
51
|
+
? ` at action ${parsed.why.index}: ${parsed.why.because}` : '';
|
|
52
|
+
throw new SavingsInputError(`plan is not a valid Trazum plan: ${parsed.why.kind}${detail}`);
|
|
53
|
+
}
|
|
54
|
+
const plan = parsed.plan;
|
|
55
|
+
const finite = (value: unknown): value is number =>
|
|
56
|
+
typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
57
|
+
const object = (value: unknown): value is Record<string, unknown> =>
|
|
58
|
+
typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
59
|
+
const keys = (value: object, allowed: readonly string[], field: string) => {
|
|
60
|
+
if (Object.keys(value).some((key) => !allowed.includes(key))) throw new SavingsInputError(`${field} has unknown properties`);
|
|
61
|
+
};
|
|
62
|
+
keys(plan, ['schemaVersion', 'span', 'pricingLastReviewed', 'actions', 'projectedSavingUsd', 'measuredStakeUsd', 'totalUsd', 'createdAt'], 'plan');
|
|
63
|
+
if (typeof plan.pricingLastReviewed !== 'string' || plan.pricingLastReviewed.trim() === '' ||
|
|
64
|
+
!finite(plan.projectedSavingUsd) || !finite(plan.measuredStakeUsd) || !finite(plan.totalUsd)) {
|
|
65
|
+
throw new SavingsInputError('plan needs pricingLastReviewed and finite non-negative projectedSavingUsd, measuredStakeUsd and totalUsd');
|
|
66
|
+
}
|
|
67
|
+
if (plan.span !== null && (!object(plan.span) || !finite(plan.span.fromMs) || !finite(plan.span.toMs) || plan.span.fromMs > plan.span.toMs)) {
|
|
68
|
+
throw new SavingsInputError('plan.span must be null or an ordered fromMs/toMs window');
|
|
69
|
+
}
|
|
70
|
+
if (plan.span !== null) keys(plan.span, ['fromMs', 'toMs'], 'plan.span');
|
|
71
|
+
if (plan.createdAt !== undefined && (typeof plan.createdAt !== 'string' || !Number.isFinite(Date.parse(plan.createdAt)))) {
|
|
72
|
+
throw new SavingsInputError('plan.createdAt must be an ISO date when supplied');
|
|
73
|
+
}
|
|
74
|
+
for (const [index, action] of plan.actions.entries()) {
|
|
75
|
+
const fail = (why: string): never => { throw new SavingsInputError(`plan action ${index}: ${why}`); };
|
|
76
|
+
keys(action, ['kind', 'label', 'model', 'savingUsd', 'stakeUsd', 'assumes', 'check', 'detail'], `plan action ${index}`);
|
|
77
|
+
if (!object(action.detail)) fail('detail must be an object');
|
|
78
|
+
keys(action.detail, ['routeTo', 'measured', 'baseline'], `plan action ${index} detail`);
|
|
79
|
+
if (!Array.isArray(action.assumes)) fail('assumes must be a list');
|
|
80
|
+
for (const assumption of action.assumes) {
|
|
81
|
+
if (!object(assumption) || !['model-capability', 'batch-window', 'retry-pattern-real', 'max-tokens-fits', 'traffic-pattern-holds'].includes(assumption.kind as string)) fail('unknown assumption');
|
|
82
|
+
keys(assumption, assumption.kind === 'model-capability' ? ['kind', 'model'] : ['kind'], `plan action ${index} assumption`);
|
|
83
|
+
if (assumption.kind === 'model-capability' && typeof assumption.model !== 'string') fail('model-capability needs a model');
|
|
84
|
+
}
|
|
85
|
+
if (action.check !== null && typeof action.check !== 'string') fail('check must be text or null');
|
|
86
|
+
if (action.savingUsd !== null && !finite(action.savingUsd)) fail('savingUsd must be a non-negative number or null');
|
|
87
|
+
if (action.stakeUsd !== null && !finite(action.stakeUsd)) fail('stakeUsd must be a non-negative number or null');
|
|
88
|
+
const projected = ['route', 'batch', 'route+batch'].includes(action.kind);
|
|
89
|
+
if (projected ? action.savingUsd === null || action.stakeUsd !== null : action.stakeUsd === null || action.savingUsd !== null) {
|
|
90
|
+
fail('projected savings and measured stakes must remain separate');
|
|
91
|
+
}
|
|
92
|
+
if (action.kind === 'route' || action.kind === 'route+batch') {
|
|
93
|
+
const target = action.detail.routeTo;
|
|
94
|
+
if (!object(target) || typeof target.id !== 'string' || target.id.length === 0 || typeof target.displayName !== 'string') fail('routeTo needs an id and displayName');
|
|
95
|
+
}
|
|
96
|
+
if (action.detail.routeTo !== undefined) {
|
|
97
|
+
const target = action.detail.routeTo;
|
|
98
|
+
if (!object(target) || typeof target.id !== 'string' || typeof target.displayName !== 'string') fail('routeTo must contain text id and displayName');
|
|
99
|
+
keys(target, ['id', 'displayName'], `plan action ${index} routeTo`);
|
|
100
|
+
}
|
|
101
|
+
const baseline = action.detail.baseline;
|
|
102
|
+
if (baseline !== undefined && (!object(baseline) ||
|
|
103
|
+
!(['calls', 'usd', 'inputPerCallTokens', 'outputPerCallTokens'] as const).every((key) => finite(baseline[key])))) fail('baseline needs finite non-negative counts and costs');
|
|
104
|
+
if (baseline !== undefined) keys(baseline, ['calls', 'usd', 'inputPerCallTokens', 'outputPerCallTokens'], `plan action ${index} baseline`);
|
|
105
|
+
const measured = action.detail.measured;
|
|
106
|
+
if (measured !== undefined && (!object(measured) || !Object.values(measured).every(finite))) fail('measured values must be finite non-negative numbers');
|
|
107
|
+
}
|
|
108
|
+
return plan;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
export function planSavings(payload: SavingsPlanPayload, catalogue: PricingCatalogue) {
|
|
113
|
+
const report = savingsReport(payload.log, catalogue);
|
|
114
|
+
return {
|
|
115
|
+
schemaVersion: 1 as const,
|
|
116
|
+
plan: buildPlan(report, billLevers(report, { catalogue }), catalogue.lastReviewed),
|
|
117
|
+
evidence: savingsEvidence(report, catalogue),
|
|
118
|
+
limitations: [
|
|
119
|
+
'Projected savings are not measured savings. Do not add projectedSavingUsd to measuredStakeUsd.',
|
|
120
|
+
'Model capability, batch latency and other action assumptions require independent validation.',
|
|
121
|
+
'Missing or unpriced records are excluded from priced totals, not free usage.',
|
|
122
|
+
],
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function verifySavings(payload: SavingsVerifyPayload, catalogue: PricingCatalogue) {
|
|
127
|
+
const plan = savingsPlan(payload.plan);
|
|
128
|
+
const report = savingsReport(payload.log, catalogue);
|
|
129
|
+
return {
|
|
130
|
+
schemaVersion: 1 as const,
|
|
131
|
+
verification: verifyPlan(plan, report, { currentPricingLastReviewed: catalogue.lastReviewed }),
|
|
132
|
+
evidence: savingsEvidence(report, catalogue),
|
|
133
|
+
limitations: [
|
|
134
|
+
'Arrived describes the observable action, not proof of equal answer quality or realized net savings.',
|
|
135
|
+
'A route+batch action only verifies routing; batch billing is not observable from token counts.',
|
|
136
|
+
'Use matching workloads and comparable periods. Missing, skipped and unpriced data limit verification.',
|
|
137
|
+
'Use the same pricing overlay for both runs; matching review dates do not prove identical custom rates.',
|
|
138
|
+
],
|
|
139
|
+
};
|
|
140
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { SAVINGS_SCHEMAS } from './serve-savings-schema.js';
|
|
2
|
+
import { IMPORT_SCHEMAS } from './serve-import-schema.js';
|
|
3
|
+
/** Public contract for local, read-only cost and savings analysis. No provider calls occur here. */
|
|
4
|
+
const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` });
|
|
5
|
+
const nullable = (schema: object) => ({ anyOf: [schema, { type: 'null' }] });
|
|
6
|
+
const object = (properties: Record<string, unknown>) => ({
|
|
7
|
+
type: 'object', properties, required: Object.keys(properties), additionalProperties: false,
|
|
8
|
+
});
|
|
9
|
+
const amount = { type: 'number', minimum: 0 };
|
|
10
|
+
const verdict = { enum: ['within', 'over', 'cannot-tell'] };
|
|
11
|
+
const restsOn = { enum: ['measured', 'measured+estimated', null] };
|
|
12
|
+
|
|
13
|
+
export const COST_REQUEST_SCHEMA = {
|
|
14
|
+
type: 'object',
|
|
15
|
+
description: 'All fields are optional. Missing counts default to zero. Unknown fields are ignored. An empty body is equivalent to {}.',
|
|
16
|
+
additionalProperties: true,
|
|
17
|
+
properties: {
|
|
18
|
+
model: { type: 'string', description: 'Catalogue model identifier. Unknown models produce an unpriced call, not a substitute.' },
|
|
19
|
+
inputTokens: { ...amount, description: 'Finite non-negative count; fractional counts remain accepted for compatibility.', default: 0 },
|
|
20
|
+
outputTokens: { ...amount, description: 'Finite non-negative count; fractional counts remain accepted for compatibility.', default: 0 },
|
|
21
|
+
basis: { type: 'string', enum: ['heuristic', 'token-count'], default: 'token-count' },
|
|
22
|
+
label: { type: 'string', description: 'Optional policy scope. Empty string means absent.' },
|
|
23
|
+
session: { type: 'string', description: 'Optional policy lookup key. Empty string means absent. Never echoed in the answer.' },
|
|
24
|
+
},
|
|
25
|
+
} as const;
|
|
26
|
+
|
|
27
|
+
/** Same accepted fields as the published schema; invalid shapes never reach the core. */
|
|
28
|
+
export function validateCostPayload(value: unknown): asserts value is Record<string, unknown> {
|
|
29
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
30
|
+
throw new Error('The body must be a JSON object.');
|
|
31
|
+
}
|
|
32
|
+
const payload = value as Record<string, unknown>;
|
|
33
|
+
for (const field of ['model', 'label', 'session'] as const) {
|
|
34
|
+
if (payload[field] !== undefined && typeof payload[field] !== 'string') {
|
|
35
|
+
throw new Error(`${field} must be a string.`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
for (const field of ['inputTokens', 'outputTokens'] as const) {
|
|
39
|
+
const count = payload[field];
|
|
40
|
+
if (count !== undefined && (typeof count !== 'number' || !Number.isFinite(count) || count < 0)) {
|
|
41
|
+
throw new Error(`${field} must be a non-negative finite number.`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (payload.basis !== undefined && payload.basis !== 'heuristic' && payload.basis !== 'token-count') {
|
|
45
|
+
throw new Error('basis must be heuristic or token-count.');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const schemas = {
|
|
50
|
+
...SAVINGS_SCHEMAS,
|
|
51
|
+
...IMPORT_SCHEMAS,
|
|
52
|
+
CostRequest: COST_REQUEST_SCHEMA,
|
|
53
|
+
HarnessCapabilities: object({
|
|
54
|
+
schemaVersion: { const: 1 },
|
|
55
|
+
accessChannels: { type: 'array', items: { enum: ['cli', 'mcp', 'http'] }, description: 'Trazum entry points, not installed or automatically connected harness integrations.' },
|
|
56
|
+
taskQuality: { const: 'not-measured' },
|
|
57
|
+
harnesses: { type: 'array', items: ref('HarnessCapability') },
|
|
58
|
+
}),
|
|
59
|
+
HarnessCapability: object({
|
|
60
|
+
id: { type: 'string' }, name: { type: 'string' },
|
|
61
|
+
nativeImport: nullable({
|
|
62
|
+
oneOf: [
|
|
63
|
+
object({ command: { const: 'from-claude-code' }, format: { const: 'claude-code-transcript-jsonl' } }),
|
|
64
|
+
object({ command: { const: 'from-codex' }, format: { const: 'codex-session-jsonl' } }),
|
|
65
|
+
],
|
|
66
|
+
}),
|
|
67
|
+
normalizedUsage: object({ command: { const: 'bill' }, format: { const: 'trazum-usage-jsonl' } }),
|
|
68
|
+
billingMode: { const: 'unknown', description: 'The harness does not determine subscription, API billing, or actual invoice amounts.' },
|
|
69
|
+
automaticInterception: { const: false, description: 'Gateway use is explicit; native hooks are not installed automatically.' },
|
|
70
|
+
}),
|
|
71
|
+
Health: object({ ok: { const: true }, schemaVersion: { const: 1 } }),
|
|
72
|
+
Error: object({ error: { enum: ['bad-request', 'not-found'] }, detail: { type: 'string' } }),
|
|
73
|
+
Window: object({ fromMs: { type: 'number' }, toMs: { type: 'number' } }),
|
|
74
|
+
CallEstimate: object({
|
|
75
|
+
model: { type: 'string' }, inputTokens: amount, outputTokens: amount, estimatedUsd: amount,
|
|
76
|
+
provenance: { const: 'estimated' }, basis: { enum: ['heuristic', 'token-count'] },
|
|
77
|
+
}),
|
|
78
|
+
BudgetPosition: object({
|
|
79
|
+
limitUsd: amount, consumedUsd: amount, remainingUsd: { type: 'number' },
|
|
80
|
+
provenance: { const: 'measured' }, window: nullable(ref('Window')),
|
|
81
|
+
}),
|
|
82
|
+
AfterCall: object({ usd: amount, halves: object({ measuredUsd: amount, estimatedUsd: amount }) }),
|
|
83
|
+
LimitJudgement: {
|
|
84
|
+
...object({
|
|
85
|
+
scope: { enum: ['day', 'session', 'label'] }, label: { type: ['string', 'null'] },
|
|
86
|
+
limitUsd: amount, verdict, restsOn,
|
|
87
|
+
reason: { enum: ['nothing-measured', 'model-unpriced', 'no-label-on-call', 'no-session-on-call', null] },
|
|
88
|
+
measuredUsd: nullable(amount), window: nullable(ref('Window')), afterCallUsd: nullable(amount),
|
|
89
|
+
waived: nullable(object({ reason: { type: 'string' }, until: { type: 'string' } })),
|
|
90
|
+
}),
|
|
91
|
+
oneOf: [
|
|
92
|
+
{ properties: { verdict: { const: 'cannot-tell' }, restsOn: { type: 'null' }, reason: { type: 'string' }, afterCallUsd: { type: 'null' } } },
|
|
93
|
+
{ properties: { verdict: { enum: ['within', 'over'] }, restsOn: { enum: ['measured', 'measured+estimated'] }, reason: { type: 'null' }, afterCallUsd: amount } },
|
|
94
|
+
],
|
|
95
|
+
},
|
|
96
|
+
PolicyJudgement: {
|
|
97
|
+
...object({ schemaVersion: { const: 1 }, verdict, reason: { enum: ['no-policy', null] }, judgements: { type: 'array', items: ref('LimitJudgement') } }),
|
|
98
|
+
oneOf: [
|
|
99
|
+
{ properties: { verdict: { const: 'cannot-tell' }, reason: { const: 'no-policy' }, judgements: { maxItems: 0 } } },
|
|
100
|
+
{ properties: { reason: { type: 'null' }, judgements: { minItems: 1 } } },
|
|
101
|
+
],
|
|
102
|
+
},
|
|
103
|
+
CostAnswer: {
|
|
104
|
+
...object({
|
|
105
|
+
schemaVersion: { const: 1 }, call: nullable(ref('CallEstimate')), budget: nullable(ref('BudgetPosition')),
|
|
106
|
+
verdict, restsOn, reason: { enum: ['no-budget-configured', 'nothing-measured', 'model-unpriced', null] },
|
|
107
|
+
afterCall: nullable(ref('AfterCall')), policy: ref('PolicyJudgement'),
|
|
108
|
+
}),
|
|
109
|
+
oneOf: [
|
|
110
|
+
{ properties: { verdict: { const: 'cannot-tell' }, reason: { enum: ['no-budget-configured', 'nothing-measured'] }, budget: { type: 'null' }, restsOn: { type: 'null' }, afterCall: { type: 'null' } } },
|
|
111
|
+
{ properties: { verdict: { const: 'cannot-tell' }, reason: { const: 'model-unpriced' }, budget: ref('BudgetPosition'), call: { type: 'null' }, restsOn: { type: 'null' }, afterCall: { type: 'null' } } },
|
|
112
|
+
{ properties: { verdict: { enum: ['within', 'over'] }, reason: { type: 'null' }, budget: ref('BudgetPosition'), restsOn: { enum: ['measured', 'measured+estimated'] }, afterCall: ref('AfterCall') } },
|
|
113
|
+
],
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const response = (name: string, description: string) => ({ description, content: { 'application/json': { schema: ref(name) } } });
|
|
118
|
+
|
|
119
|
+
export const SERVE_OPENAPI = {
|
|
120
|
+
openapi: '3.1.0',
|
|
121
|
+
jsonSchemaDialect: 'https://json-schema.org/draft/2020-12/schema',
|
|
122
|
+
info: { title: 'Trazum local cost and savings API', version: '1.0.0', description: 'Loopback-only read-only estimates, policy judgements and savings analysis. No authentication or CORS. Does not reserve budget, send model calls, or enforce an upstream decision. Measured positions are snapshots supplied by the CLI; inspect their windows.' },
|
|
123
|
+
servers: [{ url: 'http://127.0.0.1:7317', description: 'Default TCP listener. Substitute the chosen --port, or use the Unix socket transport.' }],
|
|
124
|
+
paths: {
|
|
125
|
+
'/usage/import': { post: {
|
|
126
|
+
operationId: 'importUsage', summary: 'Normalize explicit Claude Code or Codex transcript text',
|
|
127
|
+
description: 'Read-only conversion with explicit source format. No files, provider calls or measured-budget lookup. Prompts, tool content and cwd are excluded; session identifiers remain. Whole request and complete response each have a 1,000,000-byte UTF-8 limit, including JSON escaping. Unknown properties and blank inputs are refused. Conversion success does not certify source completeness or subscription billing.',
|
|
128
|
+
requestBody: { required: true, content: { 'application/json': { schema: ref('UsageImportRequest') } } },
|
|
129
|
+
responses: { '200': response('UsageImportAnswer', 'Normalized JSONL and conversion diagnostics, including zero-record imports.'), '400': response('Error', 'Malformed request, unsupported format, or input/output exceeding its byte limit.') },
|
|
130
|
+
} },
|
|
131
|
+
'/capabilities': { get: { operationId: 'getCapabilities', summary: 'Discover native import formats and Trazum access channels', responses: { '200': response('HarnessCapabilities', 'Static metadata; no environment, filesystem, session or network discovery.') } } },
|
|
132
|
+
'/health': { get: { operationId: 'getHealth', summary: 'Check the local process', responses: { '200': response('Health', 'Process is available.') } } },
|
|
133
|
+
'/openapi.json': { get: { operationId: 'getOpenApi', summary: 'Read this OpenAPI document', responses: { '200': { description: 'OpenAPI 3.1 document.', content: { 'application/json': { schema: { type: 'object', required: ['openapi', 'info', 'paths', 'components'] } } } } } } },
|
|
134
|
+
'/savings/plan': { post: {
|
|
135
|
+
operationId: 'planSavings', summary: 'Rank savings actions from normalized usage',
|
|
136
|
+
description: 'Read-only text inputs, priced using the server catalogue. No filesystem, provider or network calls. Unknown properties and empty text are refused. Whole-body limit: 1,000,000 UTF-8 bytes, including JSON escaping. Evidence gaps remain explicit; success does not certify realized savings or task quality.',
|
|
137
|
+
requestBody: { required: true, content: { 'application/json': { schema: ref('SavingsPlanRequest') } } },
|
|
138
|
+
responses: { '200': response('SavingsPlanAnswer', 'Savings analysis with evidence and limitations.'), '400': response('Error', 'Malformed, unreadable or oversized inputs.') },
|
|
139
|
+
} },
|
|
140
|
+
'/savings/verify': { post: {
|
|
141
|
+
operationId: 'verifySavings', summary: 'Verify a saved plan against later normalized usage',
|
|
142
|
+
description: 'Read-only text inputs, priced using the server catalogue. No filesystem, provider or network calls. Unknown properties and empty text are refused. Whole-body limit: 1,000,000 UTF-8 bytes, including JSON escaping. Evidence gaps remain explicit; success does not certify realized savings or task quality.',
|
|
143
|
+
requestBody: { required: true, content: { 'application/json': { schema: ref('SavingsVerifyRequest') } } },
|
|
144
|
+
responses: { '200': response('SavingsVerifyAnswer', 'Savings analysis with evidence and limitations.'), '400': response('Error', 'Malformed, unreadable or oversized inputs.') },
|
|
145
|
+
} },
|
|
146
|
+
'/cost': { post: {
|
|
147
|
+
operationId: 'estimateCost', summary: 'Estimate a proposed call against measured budget and scoped policy',
|
|
148
|
+
description: 'Body limit: 1,000,000 bytes; violations return 400. Missing or whitespace-only body is {}. Unknown properties are ignored. Content-Type is not enforced by the server; send application/json. All successful judgements, including over and cannot-tell, return 200. A judgement does not reserve or spend funds.',
|
|
149
|
+
requestBody: { required: false, content: { 'application/json': { schema: ref('CostRequest') } } },
|
|
150
|
+
responses: { '200': response('CostAnswer', 'A judgement, not permission to invoke a provider.'), '400': response('Error', 'Invalid JSON, invalid field types or values, or body over the byte limit.') },
|
|
151
|
+
} },
|
|
152
|
+
},
|
|
153
|
+
components: { schemas },
|
|
154
|
+
'x-unmatched-routes': { status: 404, schema: ref('Error'), description: 'All other path and method combinations, including OPTIONS, return 404. No CORS headers are emitted.' },
|
|
155
|
+
} as const;
|
package/src/serve.ts
CHANGED
|
@@ -24,8 +24,11 @@
|
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
import { createServer } from 'node:http';
|
|
27
|
+
import { importUsage, validateImportPayload } from './serve-import.js';
|
|
28
|
+
import { planSavings, verifySavings, validateSavingsPayload } from './serve-savings.js';
|
|
29
|
+
import { SERVE_OPENAPI, validateCostPayload } from './serve-schema.js';
|
|
27
30
|
import type { IncomingMessage, Server, ServerResponse } from 'node:http';
|
|
28
|
-
import { answerCost, judgeLimits } from '@trazum/core';
|
|
31
|
+
import { answerCost, judgeLimits, HARNESS_CAPABILITIES } from '@trazum/core';
|
|
29
32
|
import type { CostAnswer, LimitsConfig, MeasuredPosition, PricingCatalogue, WaiveEntry } from '@trazum/core';
|
|
30
33
|
|
|
31
34
|
/** Compiled in. See the module note: this is the inbound SSRF posture. */
|
|
@@ -93,15 +96,27 @@ export function buildServer(context: ServeContext): Server {
|
|
|
93
96
|
void (async () => {
|
|
94
97
|
const url = new URL(request.url ?? '/', `http://${BIND_HOST}`);
|
|
95
98
|
|
|
99
|
+
if (request.method === 'GET' && url.pathname === '/capabilities') {
|
|
100
|
+
send(response, 200, HARNESS_CAPABILITIES);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (request.method === 'GET' && url.pathname === '/openapi.json') {
|
|
105
|
+
send(response, 200, SERVE_OPENAPI);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
96
109
|
if (request.method === 'GET' && url.pathname === '/health') {
|
|
97
110
|
send(response, 200, { ok: true, schemaVersion: 1 });
|
|
98
111
|
return;
|
|
99
112
|
}
|
|
100
113
|
|
|
101
|
-
|
|
114
|
+
const savings = url.pathname === '/savings/plan' || url.pathname === '/savings/verify';
|
|
115
|
+
const importing = url.pathname === '/usage/import';
|
|
116
|
+
if (request.method !== 'POST' || (url.pathname !== '/cost' && !savings && !importing)) {
|
|
102
117
|
send(response, 404, {
|
|
103
118
|
error: 'not-found',
|
|
104
|
-
detail: 'POST /cost, or GET /
|
|
119
|
+
detail: 'POST /cost, POST /usage/import, POST /savings/plan, POST /savings/verify, GET /health, GET /capabilities, or GET /openapi.json.',
|
|
105
120
|
});
|
|
106
121
|
return;
|
|
107
122
|
}
|
|
@@ -109,13 +124,31 @@ export function buildServer(context: ServeContext): Server {
|
|
|
109
124
|
let payload: Record<string, unknown>;
|
|
110
125
|
try {
|
|
111
126
|
const raw = await readBody(request);
|
|
112
|
-
|
|
127
|
+
const parsed: unknown = raw.trim() === '' ? {} : JSON.parse(raw);
|
|
128
|
+
if (importing) {
|
|
129
|
+
validateImportPayload(parsed);
|
|
130
|
+
send(response, 200, importUsage(parsed));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (savings) {
|
|
134
|
+
if (url.pathname === '/savings/verify') {
|
|
135
|
+
validateSavingsPayload(parsed, true);
|
|
136
|
+
send(response, 200, verifySavings(parsed, context.catalogue));
|
|
137
|
+
} else {
|
|
138
|
+
validateSavingsPayload(parsed, false);
|
|
139
|
+
send(response, 200, planSavings(parsed, context.catalogue));
|
|
140
|
+
}
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
validateCostPayload(parsed);
|
|
144
|
+
payload = parsed;
|
|
113
145
|
} catch (error) {
|
|
114
146
|
send(response, 400, {
|
|
115
147
|
error: 'bad-request',
|
|
116
148
|
detail: error instanceof Error && error.message === 'body too large'
|
|
117
149
|
? `A request body may be at most ${MAX_BODY_BYTES} bytes.`
|
|
118
|
-
: 'The body must be JSON.'
|
|
150
|
+
: error instanceof SyntaxError ? 'The body must be JSON.'
|
|
151
|
+
: error instanceof Error ? error.message : 'The body must be JSON.',
|
|
119
152
|
});
|
|
120
153
|
return;
|
|
121
154
|
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { link, lstat, open, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { MAX_INPUT_CHARS, TASK_POLICY_INSTRUCTIONS } from '@trazum/core';
|
|
6
|
+
|
|
7
|
+
const START = '<!-- trazum:repeat-review-v1:start -->';
|
|
8
|
+
const END = '<!-- trazum:repeat-review-v1:end -->';
|
|
9
|
+
const BLOCK = `\n\n${START}\n${TASK_POLICY_INSTRUCTIONS}\n${END}\n`;
|
|
10
|
+
|
|
11
|
+
export class TaskFileError extends Error {}
|
|
12
|
+
|
|
13
|
+
/** Read bounded, stable regular files; a FIFO must not block before fstat. */
|
|
14
|
+
export async function readTaskText(path: string, maxChars = MAX_INPUT_CHARS): Promise<string> {
|
|
15
|
+
let file;
|
|
16
|
+
try {
|
|
17
|
+
file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
18
|
+
const before = await file.stat();
|
|
19
|
+
const maxBytes = maxChars * 4;
|
|
20
|
+
if (!before.isFile() || before.size > maxBytes) throw new TaskFileError('Input must be a bounded regular file, not a symlink or stream.');
|
|
21
|
+
const entry = await lstat(path);
|
|
22
|
+
if (!entry.isFile() || entry.isSymbolicLink()) throw new TaskFileError('Input must be a regular file, not a symlink or stream.');
|
|
23
|
+
if (before.dev !== entry.dev || before.ino !== entry.ino || before.mtimeMs !== entry.mtimeMs || before.size !== entry.size) {
|
|
24
|
+
throw new TaskFileError('Input changed while opening; retry after other edits finish.');
|
|
25
|
+
}
|
|
26
|
+
const buffer = Buffer.alloc(Math.min(before.size + 1, maxBytes + 1));
|
|
27
|
+
let length = 0;
|
|
28
|
+
while (length < buffer.length) {
|
|
29
|
+
const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
|
|
30
|
+
if (bytesRead === 0) break;
|
|
31
|
+
length += bytesRead;
|
|
32
|
+
}
|
|
33
|
+
const after = await file.stat();
|
|
34
|
+
const currentEntry = await lstat(path);
|
|
35
|
+
if (length !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
|
|
36
|
+
throw new TaskFileError('Input changed while reading; finish the task and retry with a stable transcript.');
|
|
37
|
+
}
|
|
38
|
+
if (currentEntry.isSymbolicLink() || currentEntry.dev !== before.dev || currentEntry.ino !== before.ino) {
|
|
39
|
+
throw new TaskFileError('Input was replaced while reading; retry after other edits finish.');
|
|
40
|
+
}
|
|
41
|
+
const bytes = buffer.subarray(0, length);
|
|
42
|
+
const text = bytes.toString('utf8');
|
|
43
|
+
if (!Buffer.from(text, 'utf8').equals(bytes) || text.includes('\0')) throw new TaskFileError('Input must be UTF-8 text without NUL bytes.');
|
|
44
|
+
if (text.length > maxChars) throw new TaskFileError(`Input exceeds ${maxChars} characters; use a smaller complete task source.`);
|
|
45
|
+
return text;
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (error instanceof TaskFileError) throw error;
|
|
48
|
+
throw new TaskFileError('Cannot read input; provide an existing, readable regular file without a symlink.');
|
|
49
|
+
} finally { await file?.close(); }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Reports are explicit opt-in files. Existing data is never overwritten. */
|
|
53
|
+
export async function writeTaskText(path: string, text: string): Promise<void> {
|
|
54
|
+
let temporary: string | undefined;
|
|
55
|
+
try {
|
|
56
|
+
const candidate = join(dirname(path), `.trazum-task-report-${randomUUID()}.tmp`);
|
|
57
|
+
const file = await open(candidate, 'wx', 0o600);
|
|
58
|
+
temporary = candidate;
|
|
59
|
+
try {
|
|
60
|
+
await file.writeFile(text, 'utf8');
|
|
61
|
+
await file.sync();
|
|
62
|
+
} finally { await file.close(); }
|
|
63
|
+
// Publish a complete file atomically, without replacing an existing destination.
|
|
64
|
+
await link(temporary, path);
|
|
65
|
+
} catch {
|
|
66
|
+
throw new TaskFileError('Cannot create output; choose a new file in an existing writable directory.');
|
|
67
|
+
} finally {
|
|
68
|
+
if (temporary !== undefined) await unlink(temporary).catch(() => {});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Change only the exact, versioned block. No transcript content becomes instructions. */
|
|
73
|
+
export async function changeTaskInstructions(path: string, operation: 'apply' | 'revert'): Promise<boolean> {
|
|
74
|
+
let temporary: string | undefined;
|
|
75
|
+
try {
|
|
76
|
+
const before = await lstat(path);
|
|
77
|
+
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 ||
|
|
78
|
+
(process.platform !== 'win32' && before.uid !== process.getuid?.())) {
|
|
79
|
+
throw new TaskFileError('Instructions must be a regular file owned by you, without symlinks or hard links.');
|
|
80
|
+
}
|
|
81
|
+
const text = await readTaskText(path);
|
|
82
|
+
const starts = text.split(START).length - 1;
|
|
83
|
+
const ends = text.split(END).length - 1;
|
|
84
|
+
const hasBlock = text.includes(BLOCK);
|
|
85
|
+
if (starts !== ends || starts > 1 || (starts === 1 && !hasBlock)) {
|
|
86
|
+
throw new TaskFileError('The managed policy block was edited or is malformed; review it manually before retrying.');
|
|
87
|
+
}
|
|
88
|
+
if ((operation === 'apply' && hasBlock) || (operation === 'revert' && !hasBlock)) return false;
|
|
89
|
+
const updated = operation === 'apply' ? text + BLOCK : text.replace(BLOCK, '');
|
|
90
|
+
if (updated.length > MAX_INPUT_CHARS) throw new TaskFileError('Instructions would exceed the input limit.');
|
|
91
|
+
const candidate = join(dirname(path), `.trazum-task-${randomUUID()}.tmp`);
|
|
92
|
+
const file = await open(candidate, 'wx', 0o600);
|
|
93
|
+
temporary = candidate;
|
|
94
|
+
try {
|
|
95
|
+
await file.writeFile(updated, 'utf8');
|
|
96
|
+
await file.chmod(before.mode & 0o777);
|
|
97
|
+
await file.sync();
|
|
98
|
+
} finally { await file.close(); }
|
|
99
|
+
const current = await lstat(path);
|
|
100
|
+
if (current.dev !== before.dev || current.ino !== before.ino || current.nlink !== 1 ||
|
|
101
|
+
current.size !== before.size || current.mtimeMs !== before.mtimeMs || current.ctimeMs !== before.ctimeMs ||
|
|
102
|
+
await readTaskText(path) !== text) {
|
|
103
|
+
throw new TaskFileError('Instructions changed while preparing the policy; retry after other edits finish.');
|
|
104
|
+
}
|
|
105
|
+
await rename(temporary, path);
|
|
106
|
+
temporary = undefined;
|
|
107
|
+
return true;
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error instanceof TaskFileError) throw error;
|
|
110
|
+
throw new TaskFileError('Cannot update instructions; choose an existing writable file in a writable directory.');
|
|
111
|
+
} finally {
|
|
112
|
+
if (temporary !== undefined) await unlink(temporary).catch(() => {});
|
|
113
|
+
}
|
|
114
|
+
}
|