@trazum/cli 2.5.1 → 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 (63) 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 +22 -1
  16. package/dist/html.js.map +1 -1
  17. package/dist/i18n/en.d.ts.map +1 -1
  18. package/dist/i18n/en.js +29 -3
  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 +29 -3
  22. package/dist/i18n/es.js.map +1 -1
  23. package/dist/i18n/types.d.ts +13 -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 +118 -61
  27. package/dist/index.js.map +1 -1
  28. package/dist/markdown.d.ts.map +1 -1
  29. package/dist/markdown.js +19 -1
  30. package/dist/markdown.js.map +1 -1
  31. package/dist/pdf.d.ts.map +1 -1
  32. package/dist/pdf.js +38 -1
  33. package/dist/pdf.js.map +1 -1
  34. package/dist/serve-savings-schema.d.ts +65 -0
  35. package/dist/serve-savings-schema.d.ts.map +1 -0
  36. package/dist/serve-savings-schema.js +54 -0
  37. package/dist/serve-savings-schema.js.map +1 -0
  38. package/dist/serve-savings.d.ts +55 -0
  39. package/dist/serve-savings.d.ts.map +1 -0
  40. package/dist/serve-savings.js +144 -0
  41. package/dist/serve-savings.js.map +1 -0
  42. package/dist/serve-schema.d.ts +536 -0
  43. package/dist/serve-schema.d.ts.map +1 -0
  44. package/dist/serve-schema.js +143 -0
  45. package/dist/serve-schema.js.map +1 -0
  46. package/dist/serve.d.ts.map +1 -1
  47. package/dist/serve.js +30 -5
  48. package/dist/serve.js.map +1 -1
  49. package/package.json +2 -2
  50. package/src/filter.ts +114 -0
  51. package/src/gateway-server.ts +46 -10
  52. package/src/gateway-spend.ts +120 -0
  53. package/src/html.ts +25 -1
  54. package/src/i18n/en.ts +31 -4
  55. package/src/i18n/es.ts +31 -4
  56. package/src/i18n/types.ts +14 -1
  57. package/src/index.ts +108 -63
  58. package/src/markdown.ts +20 -1
  59. package/src/pdf.ts +36 -1
  60. package/src/serve-savings-schema.ts +53 -0
  61. package/src/serve-savings.ts +140 -0
  62. package/src/serve-schema.ts +147 -0
  63. package/src/serve.ts +31 -5
@@ -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
  }