@trazum/cli 2.5.0 → 2.5.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 (64) hide show
  1. package/README.md +75 -6
  2. package/dist/filter.d.ts +2 -0
  3. package/dist/filter.d.ts.map +1 -0
  4. package/dist/filter.js +151 -0
  5. package/dist/filter.js.map +1 -0
  6. package/dist/gateway-server.d.ts +2 -0
  7. package/dist/gateway-server.d.ts.map +1 -1
  8. package/dist/gateway-server.js +49 -9
  9. package/dist/gateway-server.js.map +1 -1
  10. package/dist/gateway-spend.d.ts +32 -0
  11. package/dist/gateway-spend.d.ts.map +1 -0
  12. package/dist/gateway-spend.js +116 -0
  13. package/dist/gateway-spend.js.map +1 -0
  14. package/dist/html.d.ts.map +1 -1
  15. package/dist/html.js +25 -2
  16. package/dist/html.js.map +1 -1
  17. package/dist/i18n/en.d.ts.map +1 -1
  18. package/dist/i18n/en.js +50 -6
  19. package/dist/i18n/en.js.map +1 -1
  20. package/dist/i18n/es.d.ts.map +1 -1
  21. package/dist/i18n/es.js +51 -6
  22. package/dist/i18n/es.js.map +1 -1
  23. package/dist/i18n/types.d.ts +28 -1
  24. package/dist/i18n/types.d.ts.map +1 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +225 -41
  27. package/dist/index.js.map +1 -1
  28. package/dist/markdown.d.ts +7 -0
  29. package/dist/markdown.d.ts.map +1 -1
  30. package/dist/markdown.js +24 -2
  31. package/dist/markdown.js.map +1 -1
  32. package/dist/pdf.d.ts.map +1 -1
  33. package/dist/pdf.js +41 -2
  34. package/dist/pdf.js.map +1 -1
  35. package/dist/serve-savings-schema.d.ts +65 -0
  36. package/dist/serve-savings-schema.d.ts.map +1 -0
  37. package/dist/serve-savings-schema.js +54 -0
  38. package/dist/serve-savings-schema.js.map +1 -0
  39. package/dist/serve-savings.d.ts +55 -0
  40. package/dist/serve-savings.d.ts.map +1 -0
  41. package/dist/serve-savings.js +144 -0
  42. package/dist/serve-savings.js.map +1 -0
  43. package/dist/serve-schema.d.ts +536 -0
  44. package/dist/serve-schema.d.ts.map +1 -0
  45. package/dist/serve-schema.js +143 -0
  46. package/dist/serve-schema.js.map +1 -0
  47. package/dist/serve.d.ts.map +1 -1
  48. package/dist/serve.js +30 -5
  49. package/dist/serve.js.map +1 -1
  50. package/package.json +2 -2
  51. package/src/filter.ts +114 -0
  52. package/src/gateway-server.ts +46 -10
  53. package/src/gateway-spend.ts +120 -0
  54. package/src/html.ts +27 -2
  55. package/src/i18n/en.ts +57 -7
  56. package/src/i18n/es.ts +58 -7
  57. package/src/i18n/types.ts +29 -1
  58. package/src/index.ts +227 -43
  59. package/src/markdown.ts +32 -2
  60. package/src/pdf.ts +38 -2
  61. package/src/serve-savings-schema.ts +53 -0
  62. package/src/serve-savings.ts +140 -0
  63. package/src/serve-schema.ts +147 -0
  64. package/src/serve.ts +31 -5
@@ -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,147 @@
1
+ import { SAVINGS_SCHEMAS } from './serve-savings-schema.js';
2
+ /** Public contract for local, read-only cost and savings analysis. No provider calls occur here. */
3
+ const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` });
4
+ const nullable = (schema: object) => ({ anyOf: [schema, { type: 'null' }] });
5
+ const object = (properties: Record<string, unknown>) => ({
6
+ type: 'object', properties, required: Object.keys(properties), additionalProperties: false,
7
+ });
8
+ const amount = { type: 'number', minimum: 0 };
9
+ const verdict = { enum: ['within', 'over', 'cannot-tell'] };
10
+ const restsOn = { enum: ['measured', 'measured+estimated', null] };
11
+
12
+ export const COST_REQUEST_SCHEMA = {
13
+ type: 'object',
14
+ description: 'All fields are optional. Missing counts default to zero. Unknown fields are ignored. An empty body is equivalent to {}.',
15
+ additionalProperties: true,
16
+ properties: {
17
+ model: { type: 'string', description: 'Catalogue model identifier. Unknown models produce an unpriced call, not a substitute.' },
18
+ inputTokens: { ...amount, description: 'Finite non-negative count; fractional counts remain accepted for compatibility.', default: 0 },
19
+ outputTokens: { ...amount, description: 'Finite non-negative count; fractional counts remain accepted for compatibility.', default: 0 },
20
+ basis: { type: 'string', enum: ['heuristic', 'token-count'], default: 'token-count' },
21
+ label: { type: 'string', description: 'Optional policy scope. Empty string means absent.' },
22
+ session: { type: 'string', description: 'Optional policy lookup key. Empty string means absent. Never echoed in the answer.' },
23
+ },
24
+ } as const;
25
+
26
+ /** Same accepted fields as the published schema; invalid shapes never reach the core. */
27
+ export function validateCostPayload(value: unknown): asserts value is Record<string, unknown> {
28
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
29
+ throw new Error('The body must be a JSON object.');
30
+ }
31
+ const payload = value as Record<string, unknown>;
32
+ for (const field of ['model', 'label', 'session'] as const) {
33
+ if (payload[field] !== undefined && typeof payload[field] !== 'string') {
34
+ throw new Error(`${field} must be a string.`);
35
+ }
36
+ }
37
+ for (const field of ['inputTokens', 'outputTokens'] as const) {
38
+ const count = payload[field];
39
+ if (count !== undefined && (typeof count !== 'number' || !Number.isFinite(count) || count < 0)) {
40
+ throw new Error(`${field} must be a non-negative finite number.`);
41
+ }
42
+ }
43
+ if (payload.basis !== undefined && payload.basis !== 'heuristic' && payload.basis !== 'token-count') {
44
+ throw new Error('basis must be heuristic or token-count.');
45
+ }
46
+ }
47
+
48
+ const schemas = {
49
+ ...SAVINGS_SCHEMAS,
50
+ CostRequest: COST_REQUEST_SCHEMA,
51
+ HarnessCapabilities: object({
52
+ schemaVersion: { const: 1 },
53
+ accessChannels: { type: 'array', items: { enum: ['cli', 'mcp', 'http'] }, description: 'Trazum entry points, not installed or automatically connected harness integrations.' },
54
+ taskQuality: { const: 'not-measured' },
55
+ harnesses: { type: 'array', items: ref('HarnessCapability') },
56
+ }),
57
+ HarnessCapability: object({
58
+ id: { type: 'string' }, name: { type: 'string' },
59
+ nativeImport: nullable({
60
+ oneOf: [
61
+ object({ command: { const: 'from-claude-code' }, format: { const: 'claude-code-transcript-jsonl' } }),
62
+ object({ command: { const: 'from-codex' }, format: { const: 'codex-session-jsonl' } }),
63
+ ],
64
+ }),
65
+ normalizedUsage: object({ command: { const: 'bill' }, format: { const: 'trazum-usage-jsonl' } }),
66
+ billingMode: { const: 'unknown', description: 'The harness does not determine subscription, API billing, or actual invoice amounts.' },
67
+ automaticInterception: { const: false, description: 'Gateway use is explicit; native hooks are not installed automatically.' },
68
+ }),
69
+ Health: object({ ok: { const: true }, schemaVersion: { const: 1 } }),
70
+ Error: object({ error: { enum: ['bad-request', 'not-found'] }, detail: { type: 'string' } }),
71
+ Window: object({ fromMs: { type: 'number' }, toMs: { type: 'number' } }),
72
+ CallEstimate: object({
73
+ model: { type: 'string' }, inputTokens: amount, outputTokens: amount, estimatedUsd: amount,
74
+ provenance: { const: 'estimated' }, basis: { enum: ['heuristic', 'token-count'] },
75
+ }),
76
+ BudgetPosition: object({
77
+ limitUsd: amount, consumedUsd: amount, remainingUsd: { type: 'number' },
78
+ provenance: { const: 'measured' }, window: nullable(ref('Window')),
79
+ }),
80
+ AfterCall: object({ usd: amount, halves: object({ measuredUsd: amount, estimatedUsd: amount }) }),
81
+ LimitJudgement: {
82
+ ...object({
83
+ scope: { enum: ['day', 'session', 'label'] }, label: { type: ['string', 'null'] },
84
+ limitUsd: amount, verdict, restsOn,
85
+ reason: { enum: ['nothing-measured', 'model-unpriced', 'no-label-on-call', 'no-session-on-call', null] },
86
+ measuredUsd: nullable(amount), window: nullable(ref('Window')), afterCallUsd: nullable(amount),
87
+ waived: nullable(object({ reason: { type: 'string' }, until: { type: 'string' } })),
88
+ }),
89
+ oneOf: [
90
+ { properties: { verdict: { const: 'cannot-tell' }, restsOn: { type: 'null' }, reason: { type: 'string' }, afterCallUsd: { type: 'null' } } },
91
+ { properties: { verdict: { enum: ['within', 'over'] }, restsOn: { enum: ['measured', 'measured+estimated'] }, reason: { type: 'null' }, afterCallUsd: amount } },
92
+ ],
93
+ },
94
+ PolicyJudgement: {
95
+ ...object({ schemaVersion: { const: 1 }, verdict, reason: { enum: ['no-policy', null] }, judgements: { type: 'array', items: ref('LimitJudgement') } }),
96
+ oneOf: [
97
+ { properties: { verdict: { const: 'cannot-tell' }, reason: { const: 'no-policy' }, judgements: { maxItems: 0 } } },
98
+ { properties: { reason: { type: 'null' }, judgements: { minItems: 1 } } },
99
+ ],
100
+ },
101
+ CostAnswer: {
102
+ ...object({
103
+ schemaVersion: { const: 1 }, call: nullable(ref('CallEstimate')), budget: nullable(ref('BudgetPosition')),
104
+ verdict, restsOn, reason: { enum: ['no-budget-configured', 'nothing-measured', 'model-unpriced', null] },
105
+ afterCall: nullable(ref('AfterCall')), policy: ref('PolicyJudgement'),
106
+ }),
107
+ oneOf: [
108
+ { properties: { verdict: { const: 'cannot-tell' }, reason: { enum: ['no-budget-configured', 'nothing-measured'] }, budget: { type: 'null' }, restsOn: { type: 'null' }, afterCall: { type: 'null' } } },
109
+ { properties: { verdict: { const: 'cannot-tell' }, reason: { const: 'model-unpriced' }, budget: ref('BudgetPosition'), call: { type: 'null' }, restsOn: { type: 'null' }, afterCall: { type: 'null' } } },
110
+ { properties: { verdict: { enum: ['within', 'over'] }, reason: { type: 'null' }, budget: ref('BudgetPosition'), restsOn: { enum: ['measured', 'measured+estimated'] }, afterCall: ref('AfterCall') } },
111
+ ],
112
+ },
113
+ };
114
+
115
+ const response = (name: string, description: string) => ({ description, content: { 'application/json': { schema: ref(name) } } });
116
+
117
+ export const SERVE_OPENAPI = {
118
+ openapi: '3.1.0',
119
+ jsonSchemaDialect: 'https://json-schema.org/draft/2020-12/schema',
120
+ 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.' },
121
+ servers: [{ url: 'http://127.0.0.1:7317', description: 'Default TCP listener. Substitute the chosen --port, or use the Unix socket transport.' }],
122
+ paths: {
123
+ '/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.') } } },
124
+ '/health': { get: { operationId: 'getHealth', summary: 'Check the local process', responses: { '200': response('Health', 'Process is available.') } } },
125
+ '/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'] } } } } } } },
126
+ '/savings/plan': { post: {
127
+ operationId: 'planSavings', summary: 'Rank savings actions from normalized usage',
128
+ 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.',
129
+ requestBody: { required: true, content: { 'application/json': { schema: ref('SavingsPlanRequest') } } },
130
+ responses: { '200': response('SavingsPlanAnswer', 'Savings analysis with evidence and limitations.'), '400': response('Error', 'Malformed, unreadable or oversized inputs.') },
131
+ } },
132
+ '/savings/verify': { post: {
133
+ operationId: 'verifySavings', summary: 'Verify a saved plan against later normalized usage',
134
+ 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.',
135
+ requestBody: { required: true, content: { 'application/json': { schema: ref('SavingsVerifyRequest') } } },
136
+ responses: { '200': response('SavingsVerifyAnswer', 'Savings analysis with evidence and limitations.'), '400': response('Error', 'Malformed, unreadable or oversized inputs.') },
137
+ } },
138
+ '/cost': { post: {
139
+ operationId: 'estimateCost', summary: 'Estimate a proposed call against measured budget and scoped policy',
140
+ 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.',
141
+ requestBody: { required: false, content: { 'application/json': { schema: ref('CostRequest') } } },
142
+ 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.') },
143
+ } },
144
+ },
145
+ components: { schemas },
146
+ 'x-unmatched-routes': { status: 404, schema: ref('Error'), description: 'All other path and method combinations, including OPTIONS, return 404. No CORS headers are emitted.' },
147
+ } as const;
package/src/serve.ts CHANGED
@@ -24,8 +24,10 @@
24
24
  */
25
25
 
26
26
  import { createServer } from 'node:http';
27
+ import { planSavings, verifySavings, validateSavingsPayload } from './serve-savings.js';
28
+ import { SERVE_OPENAPI, validateCostPayload } from './serve-schema.js';
27
29
  import type { IncomingMessage, Server, ServerResponse } from 'node:http';
28
- import { answerCost, judgeLimits } from '@trazum/core';
30
+ import { answerCost, judgeLimits, HARNESS_CAPABILITIES } from '@trazum/core';
29
31
  import type { CostAnswer, LimitsConfig, MeasuredPosition, PricingCatalogue, WaiveEntry } from '@trazum/core';
30
32
 
31
33
  /** Compiled in. See the module note: this is the inbound SSRF posture. */
@@ -93,15 +95,26 @@ export function buildServer(context: ServeContext): Server {
93
95
  void (async () => {
94
96
  const url = new URL(request.url ?? '/', `http://${BIND_HOST}`);
95
97
 
98
+ if (request.method === 'GET' && url.pathname === '/capabilities') {
99
+ send(response, 200, HARNESS_CAPABILITIES);
100
+ return;
101
+ }
102
+
103
+ if (request.method === 'GET' && url.pathname === '/openapi.json') {
104
+ send(response, 200, SERVE_OPENAPI);
105
+ return;
106
+ }
107
+
96
108
  if (request.method === 'GET' && url.pathname === '/health') {
97
109
  send(response, 200, { ok: true, schemaVersion: 1 });
98
110
  return;
99
111
  }
100
112
 
101
- if (request.method !== 'POST' || url.pathname !== '/cost') {
113
+ const savings = url.pathname === '/savings/plan' || url.pathname === '/savings/verify';
114
+ if (request.method !== 'POST' || (url.pathname !== '/cost' && !savings)) {
102
115
  send(response, 404, {
103
116
  error: 'not-found',
104
- detail: 'POST /cost, or GET /health.',
117
+ detail: 'POST /cost, POST /savings/plan, POST /savings/verify, GET /health, GET /capabilities, or GET /openapi.json.',
105
118
  });
106
119
  return;
107
120
  }
@@ -109,13 +122,26 @@ export function buildServer(context: ServeContext): Server {
109
122
  let payload: Record<string, unknown>;
110
123
  try {
111
124
  const raw = await readBody(request);
112
- payload = raw.trim() === '' ? {} : (JSON.parse(raw) as Record<string, unknown>);
125
+ const parsed: unknown = raw.trim() === '' ? {} : JSON.parse(raw);
126
+ if (savings) {
127
+ if (url.pathname === '/savings/verify') {
128
+ validateSavingsPayload(parsed, true);
129
+ send(response, 200, verifySavings(parsed, context.catalogue));
130
+ } else {
131
+ validateSavingsPayload(parsed, false);
132
+ send(response, 200, planSavings(parsed, context.catalogue));
133
+ }
134
+ return;
135
+ }
136
+ validateCostPayload(parsed);
137
+ payload = parsed;
113
138
  } catch (error) {
114
139
  send(response, 400, {
115
140
  error: 'bad-request',
116
141
  detail: error instanceof Error && error.message === 'body too large'
117
142
  ? `A request body may be at most ${MAX_BODY_BYTES} bytes.`
118
- : 'The body must be JSON.',
143
+ : error instanceof SyntaxError ? 'The body must be JSON.'
144
+ : error instanceof Error ? error.message : 'The body must be JSON.',
119
145
  });
120
146
  return;
121
147
  }