@trazum/cli 2.7.7 → 2.7.8

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.
@@ -1 +1 @@
1
- {"version":3,"file":"serve-savings.d.ts","sourceRoot":"","sources":["../src/serve-savings.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,qBAAa,iBAAkB,SAAQ,KAAK;CAAG;AAC/C,MAAM,WAAW,kBAAkB;IAAG,GAAG,EAAE,MAAM,CAAA;CAAE;AACnD,MAAM,WAAW,oBAAqB,SAAQ,kBAAkB;IAAG,IAAI,EAAE,MAAM,CAAA;CAAE;AAEjF,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,kBAAkB,CAAC;AAC3G,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,oBAAoB,CAAC;AAC5G,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,kBAAkB,GAAG,oBAAoB,CAAC;AAqGpI,wBAAgB,WAAW,CAAC,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,gBAAgB;IAGhF,aAAa,EAAE,CAAC;IAChB,IAAI;IACJ,QAAQ;;;;;;;;;;;;;;;;IACR,WAAW;EAMd;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,EAAE,SAAS,EAAE,gBAAgB;IAIpF,aAAa,EAAE,CAAC;IAChB,YAAY;IACZ,QAAQ;;;;;;;;;;;;;;;;IACR,WAAW;EAOd"}
1
+ {"version":3,"file":"serve-savings.d.ts","sourceRoot":"","sources":["../src/serve-savings.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,qBAAa,iBAAkB,SAAQ,KAAK;CAAG;AAC/C,MAAM,WAAW,kBAAkB;IAAG,GAAG,EAAE,MAAM,CAAA;CAAE;AACnD,MAAM,WAAW,oBAAqB,SAAQ,kBAAkB;IAAG,IAAI,EAAE,MAAM,CAAA;CAAE;AAEjF,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,kBAAkB,CAAC;AAC3G,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,oBAAoB,CAAC;AAC5G,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,kBAAkB,GAAG,oBAAoB,CAAC;AA+HpI,wBAAgB,WAAW,CAAC,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,gBAAgB;IAGhF,aAAa,EAAE,CAAC;IAChB,IAAI;IACJ,QAAQ;;;;;;;;;;;;;;;;IACR,WAAW;EAMd;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,EAAE,SAAS,EAAE,gBAAgB;IAIpF,aAAa,EAAE,CAAC;IAChB,YAAY;IACZ,QAAQ;;;;;;;;;;;;;;;;IACR,WAAW;EAOd"}
@@ -1,5 +1,5 @@
1
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';
2
+ import { AGENT_SHAPES, BUNDLED_CATALOGUE, billLevers, buildPlan, notAUsageLog, parsePlanDocument, profileUsage, verifyPlan, } from '@trazum/core';
3
3
  export class SavingsInputError extends Error {
4
4
  }
5
5
  export function validateSavingsPayload(value, verify) {
@@ -14,7 +14,29 @@ export function validateSavingsPayload(value, verify) {
14
14
  throw new SavingsInputError(`${key} must be non-empty text, not a file path.`);
15
15
  }
16
16
  }
17
+ /**
18
+ * A coding agent's session sent as `log` was refused as "no readable usage
19
+ * records", which reads as a broken file when `/usage/import` converts it in
20
+ * one request. Named instead, through the same verdict the CLI and the MCP
21
+ * server use, with the request or command that reads it.
22
+ */
23
+ function refuseOtherShape(log) {
24
+ const not = notAUsageLog(log);
25
+ if (not === null)
26
+ return;
27
+ if (not.kind === 'shape' && AGENT_SHAPES.includes(not.shape)) {
28
+ throw new SavingsInputError(`log is a ${not.shape} session, not a usage log. POST it to /usage/import with format "${not.shape}", then send the log that returns.`);
29
+ }
30
+ if (not.kind === 'shape') {
31
+ throw new SavingsInputError(`log is ${not.shape} data, not a usage log. ${not.command === null ? '' : `trazum ${not.command} turns it into one; `}trazum bill reads it as it is.`);
32
+ }
33
+ if (not.kind === 'ambiguous') {
34
+ throw new SavingsInputError(`log is not a usage log, and more than one format claims it (${not.shapes.join(', ')}), so it was not converted.`);
35
+ }
36
+ throw new SavingsInputError("log is a provider's cost report, a bill rather than usage. trazum reconcile sets it beside a receipt.");
37
+ }
17
38
  function savingsReport(log, catalogue) {
39
+ refuseOtherShape(log);
18
40
  const report = profileUsage(log, { catalogue });
19
41
  if (report.total.calls + report.unpriced.calls === 0) {
20
42
  throw new SavingsInputError('log contains no readable usage records; pass normalized JSONL text with model and token counts');
@@ -1 +1 @@
1
- {"version":3,"file":"serve-savings.js","sourceRoot":"","sources":["../src/serve-savings.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAGrH,MAAM,OAAO,iBAAkB,SAAQ,KAAK;CAAG;AAO/C,MAAM,UAAU,sBAAsB,CAAC,KAAc,EAAE,MAAe;IACpE,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAA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AAC,IAAI,EAAE,MAAM,EAAE,EAAE,0BAA0B,EAAE,SAAS,CAAC,YAAY,EAAE,CAAC;QAC9F,QAAQ,EAAE,eAAe,CAAC,MAAM,EAAE,SAAS,CAAC;QAC5C,WAAW,EAAE;YACX,qGAAqG;YACrG,gGAAgG;YAChG,uGAAuG;YACvG,wGAAwG;SACzG;KACF,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trazum/cli",
3
- "version": "2.7.7",
3
+ "version": "2.7.8",
4
4
  "description": "What your AI agents cost, per project, offline: one bill across Claude Code, Codex and Gemini CLI sessions, plus Anthropic, OpenAI, Gemini, OpenRouter, OTel and LiteLLM usage, written as PDF, HTML or CSV, with budgets enforced in CI.",
5
5
  "license": "MIT",
6
6
  "author": "David Mu\u00f1oz Rey",
@@ -53,7 +53,7 @@
53
53
  "prepublishOnly": "npm run build && npm test"
54
54
  },
55
55
  "dependencies": {
56
- "@trazum/core": "2.7.7"
56
+ "@trazum/core": "2.7.8"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@types/node": "^26.6.6",
package/src/i18n/en.ts CHANGED
@@ -65,7 +65,7 @@ ${bold('USAGE')}
65
65
  trazum schema <contract>
66
66
  trazum rollup <document...|dir> [--json] [--html-out <file>]
67
67
  trazum position <usage.jsonl>
68
- trazum receipt <usage.jsonl|dir> [--stamp] [--since <when>] [--until <when>] [-o <file>]
68
+ trazum receipt <usage.jsonl> [--stamp] [--since <when>] [--until <when>] [-o <file>]
69
69
  trazum bill [<file|dir>...] [--label <name>] [--no-label-from-project] [--receipt|--table] [--stamp] [-o <file>]
70
70
  [--since <when>] [--until <when>] [--by day|week|month] [--pdf-out|--html-out|--markdown-out|--csv-out <file>]
71
71
  trazum from-claude-code <file|dir> [--label <name>] [-o <file>]
@@ -1204,6 +1204,14 @@ ${bold('EXAMPLES')}
1204
1204
  'that path is a directory, and this command reads a file. Name the file inside it, or use a command that walks a folder.',
1205
1205
  fileNotReadable: (path) =>
1206
1206
  `${path}: no permission to read it. Check the file's owner and mode, then run this again.`,
1207
+ logIsDirectory: (path) =>
1208
+ `${path} is a directory, and this command reads one usage log. trazum bill ${path} reads every usage log and coding-agent session under it.`,
1209
+ logIsOtherShape: (path, shape, command, billPath) =>
1210
+ `${path} is ${shape} data, not a usage log, so this command would find no calls in it. trazum bill ${billPath} reads it as it is${command === null ? '.' : `, and trazum ${command} ${path} -o usage.jsonl writes a usage log this command reads.`}`,
1211
+ logIsAmbiguous: (path, shapes) =>
1212
+ `${path} is not a usage log, and more than one shape claims it (${shapes}). Convert it with the from- command for the one it is, then point this command at the usage log that writes.`,
1213
+ logIsCostReport: (path) =>
1214
+ `${path} is a provider's cost report, a bill rather than usage, so this command would find no calls in it. Set it beside a receipt with trazum reconcile.`,
1207
1215
  livePricingFailed: (url: string, detail: string) =>
1208
1216
  `Could not load live prices from ${url}: ${detail}. The bundled prices are still there. Drop --pricing-live to use them.`,
1209
1217
  optionNeedsValue: (name) => `Option --${name} needs a value.`,
@@ -2133,8 +2141,8 @@ ${bold('EXAMPLES')}
2133
2141
  unknownMore: (count) => `${count} more file(s) no shape claims, not guessed at and not in the bill.`,
2134
2142
  sessionSideFiles: (count) =>
2135
2143
  `${count} file(s) Claude Code keeps inside its sessions' folders (subagent metadata, workflow journals, long tool output) are not usage, and were passed over.`,
2136
- shapeSummary: (shape, files, records, leftOut) =>
2137
- `${files} file(s): ${shape}${records === null ? ', read as they are' : `, ${records} record(s)`}${leftOut > 0 ? `, ${leftOut} row(s) left out. trazum from-${shape} on a file says why.` : '.'}`,
2144
+ shapeSummary: (shape, files, records, leftOut, command) =>
2145
+ `${files} file(s): ${shape}${records === null ? ', read as they are' : `, ${records} record(s)`}${leftOut > 0 ? `, ${leftOut} row(s) left out${command === null ? '.' : `. trazum ${command} on a file says why.`}` : '.'}`,
2138
2146
  statementHeading: () => 'Your bill',
2139
2147
  statementTotal: (usd, calls) => `${usd} across ${calls.toLocaleString('en-US')} priced call(s)`,
2140
2148
  colProject: () => 'project',
@@ -2162,8 +2170,8 @@ ${bold('EXAMPLES')}
2162
2170
  'The receipt as data: --receipt, or -o receipt.json. The document for whoever pays: --pdf-out bill.pdf.',
2163
2171
  notFound: (path) => `${path}: not found`,
2164
2172
  noFiles: (path) => `${path}: no .json, .jsonl, .ndjson or .log files under it, plain or gzipped.`,
2165
- file: (path, shape, records, leftOut) =>
2166
- `${path}: ${shape}${records === null ? ', read as it is' : `, ${records} record(s)`}${leftOut > 0 ? `, ${leftOut} row(s) left out. Run trazum from-${shape} on it for the reasons.` : '.'}`,
2173
+ file: (path, shape, records, leftOut, command) =>
2174
+ `${path}: ${shape}${records === null ? ', read as it is' : `, ${records} record(s)`}${leftOut > 0 ? `, ${leftOut} row(s) left out${command === null ? '.' : `. Run trazum ${command} on it for the reasons.`}` : '.'}`,
2167
2175
  unknown: (path) =>
2168
2176
  `${path}: no shape this tool reads claims it, so it was not guessed at and is not in the bill.`,
2169
2177
  ambiguous: (path, shapes) =>
@@ -3150,8 +3158,8 @@ ${bold('EXAMPLES')}
3150
3158
  `95% of the answers that finished fit within ${p95} output tokens, so a cap around there would stop cutting them off. Measured on these calls, promised for nothing.`,
3151
3159
  readFiles: (files, directory) =>
3152
3160
  `Read ${count(files)} log files from ${directory}, in name order, as one bill. Every figure below covers all of them.`,
3153
- noLogsInDirectory: (directory, extensions) =>
3154
- `No usage logs in "${directory}". Looked for files ending in ${extensions}. A directory with nothing readable in it is an error rather than an empty report, which would read as "you spent nothing".`,
3161
+ noLogsInDirectory: (directory, extensions, folders) =>
3162
+ `No usage logs in "${directory}". Looked for files ending in ${extensions}. A directory with nothing readable in it is an error rather than an empty report, which would read as "you spent nothing".${folders ? ` It holds folders, which this command does not go into: trazum bill "${directory}" reads every usage log and coding-agent session under it.` : ''}`,
3155
3163
  sessionCostTail: (ratio) =>
3156
3164
  `The 95th percentile is ${ratio}x the median there: most sessions are cheap and a few are not, which is a tail a quota can catch. Where median and p95 sit close together the workload is simply expensive and there is no tail to hunt.`,
3157
3165
  sessionSpendOnly: (sessions, max) =>
package/src/i18n/es.ts CHANGED
@@ -52,7 +52,7 @@ ${bold('USO')}
52
52
  trazum schema <contrato>
53
53
  trazum rollup <documento...|dir> [--json] [--html-out <fichero>]
54
54
  trazum position <uso.jsonl>
55
- trazum receipt <uso.jsonl|dir> [--stamp] [--since <cuándo>] [--until <cuándo>] [-o <fichero>]
55
+ trazum receipt <uso.jsonl> [--stamp] [--since <cuándo>] [--until <cuándo>] [-o <fichero>]
56
56
  trazum bill [<fichero|dir>...] [--label <nombre>] [--no-label-from-project] [--receipt|--table] [--stamp] [-o <fichero>]
57
57
  [--since <cuándo>] [--until <cuándo>] [--by day|week|month] [--pdf-out|--html-out|--markdown-out|--csv-out <fichero>]
58
58
  trazum from-claude-code <fichero|dir> [--label <nombre>] [-o <fichero>]
@@ -1251,6 +1251,14 @@ ${bold('EJEMPLOS')}
1251
1251
  'esa ruta es un directorio, y este comando lee un fichero. Nombra el fichero de dentro, o usa un comando que recorra una carpeta.',
1252
1252
  fileNotReadable: (path) =>
1253
1253
  `${path}: sin permiso de lectura. Revisa el dueño y los permisos del fichero, y vuelve a ejecutarlo.`,
1254
+ logIsDirectory: (path) =>
1255
+ `${path} es un directorio, y este comando lee un registro de uso. trazum bill ${path} lee todos los registros de uso y sesiones de agentes de código que hay dentro.`,
1256
+ logIsOtherShape: (path, shape, command, billPath) =>
1257
+ `${path} son datos de ${shape}, no un registro de uso, así que este comando no encontraría ninguna llamada en él. trazum bill ${billPath} lo lee tal cual${command === null ? '.' : `, y trazum ${command} ${path} -o uso.jsonl escribe un registro de uso que este comando lee.`}`,
1258
+ logIsAmbiguous: (path, shapes) =>
1259
+ `${path} no es un registro de uso, y lo reclama más de una forma (${shapes}). Conviértelo con el comando from- de la que sea, y apunta este comando al registro de uso que escriba.`,
1260
+ logIsCostReport: (path) =>
1261
+ `${path} es un informe de costes de un proveedor, una factura y no uso, así que este comando no encontraría ninguna llamada en él. Ponlo junto a un recibo con trazum reconcile.`,
1254
1262
  livePricingFailed: (url: string, detail: string) =>
1255
1263
  `No se han podido cargar los precios en vivo desde ${url}: ${detail}. Los precios incluidos siguen ahí: quita --pricing-live para usarlos.`,
1256
1264
  optionNeedsValue: (name) => `La opción --${name} necesita un valor.`,
@@ -2163,8 +2171,8 @@ ${bold('EJEMPLOS')}
2163
2171
  unknownMore: (count) => `${count} archivo(s) más que ninguna forma reclama, sin adivinar y fuera de la factura.`,
2164
2172
  sessionSideFiles: (count) =>
2165
2173
  `${count} archivo(s) que Claude Code guarda dentro de las carpetas de sus sesiones (metadatos de subagentes, diarios de workflows, salidas largas de herramientas) no son uso, y se han pasado por alto.`,
2166
- shapeSummary: (shape, files, records, leftOut) =>
2167
- `${files} archivo(s): ${shape}${records === null ? ', leídos tal cual' : `, ${records} registro(s)`}${leftOut > 0 ? `, ${leftOut} fila(s) fuera. trazum from-${shape} sobre un archivo dice por qué.` : '.'}`,
2174
+ shapeSummary: (shape, files, records, leftOut, command) =>
2175
+ `${files} archivo(s): ${shape}${records === null ? ', leídos tal cual' : `, ${records} registro(s)`}${leftOut > 0 ? `, ${leftOut} fila(s) fuera${command === null ? '.' : `. trazum ${command} sobre un archivo dice por qué.`}` : '.'}`,
2168
2176
  statementHeading: () => 'Tu factura',
2169
2177
  statementTotal: (usd, calls) => `${usd} en ${calls.toLocaleString('es-ES')} llamada(s) con precio`,
2170
2178
  colProject: () => 'proyecto',
@@ -2194,8 +2202,8 @@ ${bold('EJEMPLOS')}
2194
2202
  'El recibo como datos: --receipt, o -o recibo.json. El documento para quien paga: --pdf-out factura.pdf.',
2195
2203
  notFound: (path) => `${path}: no encontrado`,
2196
2204
  noFiles: (path) => `${path}: no hay archivos .json, .jsonl, .ndjson ni .log dentro, ni sin comprimir ni en .gz.`,
2197
- file: (path, shape, records, leftOut) =>
2198
- `${path}: ${shape}${records === null ? ', leído tal cual' : `, ${records} registro(s)`}${leftOut > 0 ? `, ${leftOut} fila(s) fuera. Ejecuta trazum from-${shape} sobre él para ver por qué.` : '.'}`,
2205
+ file: (path, shape, records, leftOut, command) =>
2206
+ `${path}: ${shape}${records === null ? ', leído tal cual' : `, ${records} registro(s)`}${leftOut > 0 ? `, ${leftOut} fila(s) fuera${command === null ? '.' : `. Ejecuta trazum ${command} sobre él para ver por qué.`}` : '.'}`,
2199
2207
  unknown: (path) =>
2200
2208
  `${path}: ninguna forma que esta herramienta lee lo reclama, así que no se adivinó y no está en la factura.`,
2201
2209
  ambiguous: (path, shapes) =>
@@ -3180,8 +3188,8 @@ ${bold('EJEMPLOS')}
3180
3188
  `El 95% de las respuestas que sí terminaron cabe en ${p95} tokens de salida, así que un tope por ahí dejaría de cortarlas. Medido en estas llamadas, prometido para ninguna.`,
3181
3189
  readFiles: (files, directory) =>
3182
3190
  `Leídos ${count(files)} ficheros de registro de ${directory}, en orden de nombre, como una sola factura. Todas las cifras de abajo los cubren todos.`,
3183
- noLogsInDirectory: (directory, extensions) =>
3184
- `No hay registros de uso en "${directory}". Se buscaron ficheros terminados en ${extensions}. Un directorio sin nada legible es un error, no un informe vacío, que se leería como "no has gastado nada".`,
3191
+ noLogsInDirectory: (directory, extensions, folders) =>
3192
+ `No hay registros de uso en "${directory}". Se buscaron ficheros terminados en ${extensions}. Un directorio sin nada legible es un error, no un informe vacío, que se leería como "no has gastado nada".${folders ? ` Contiene carpetas, en las que este comando no entra: trazum bill "${directory}" lee todos los registros de uso y sesiones de agentes de código que hay dentro.` : ''}`,
3185
3193
  sessionCostTail: (ratio) =>
3186
3194
  `El percentil 95 es ${ratio}x la mediana ahí: casi todas las sesiones son baratas y unas pocas no, y esa es una cola que una cuota puede cazar. Cuando mediana y p95 quedan cerca, la carga es cara sin más y no hay cola que perseguir.`,
3187
3195
  sessionSpendOnly: (sessions, max) =>
package/src/i18n/types.ts CHANGED
@@ -95,6 +95,16 @@ export interface CliMessages {
95
95
  /** Node reports EISDIR from `read` with no path on it, so this one names none. */
96
96
  fileIsDirectoryUnnamed(): string;
97
97
  fileNotReadable(path: string): string;
98
+ /**
99
+ * A command that reads one usage log, handed something else. Each names
100
+ * the file, what it is, and the command that reads it: a refusal that
101
+ * only said "no usage records" read as a broken file.
102
+ */
103
+ logIsDirectory(path: string): string;
104
+ /** `command` is the converter for the shape, null where none exists. `billPath` is what `bill` should be pointed at. */
105
+ logIsOtherShape(path: string, shape: string, command: string | null, billPath: string): string;
106
+ logIsAmbiguous(path: string, shapes: string): string;
107
+ logIsCostReport(path: string): string;
98
108
  livePricingFailed: (url: string, detail: string) => string;
99
109
  optionNeedsValue(name: string): string;
100
110
  mustBeNonNegative(name: string, raw: string): string;
@@ -783,7 +793,7 @@ export interface CliMessages {
783
793
  /** Files a Claude Code session keeps beside its transcript, inside its own folder: not usage. */
784
794
  sessionSideFiles(count: number): string;
785
795
  /** Many files of one shape: one line for the shape, not one per file. */
786
- shapeSummary(shape: string, files: number, records: number | null, leftOut: number): string;
796
+ shapeSummary(shape: string, files: number, records: number | null, leftOut: number, command: string | null): string;
787
797
  /** The human statement a terminal gets instead of the JSON receipt. */
788
798
  statementHeading(): string;
789
799
  statementTotal(usd: string, calls: number): string;
@@ -814,7 +824,7 @@ export interface CliMessages {
814
824
  notFound(path: string): string;
815
825
  noFiles(path: string): string;
816
826
  /** One line per file: its shape, what it became, what was left out. */
817
- file(path: string, shape: string, records: number | null, leftOut: number): string;
827
+ file(path: string, shape: string, records: number | null, leftOut: number, command: string | null): string;
818
828
  /** No shape claimed it: named, never guessed. */
819
829
  unknown(path: string): string;
820
830
  /** Two shapes claimed it: named, never picked between. */
@@ -1927,7 +1937,8 @@ export interface CliMessages {
1927
1937
  /** What the answers that finished actually needed, for setting the cap. */
1928
1938
  truncatedCeiling(p95: string): string;
1929
1939
  readFiles(files: number, directory: string): string;
1930
- noLogsInDirectory(directory: string, extensions: string): string;
1940
+ /** `folders`: it holds folders the walk did not go into, which is where coding agents keep their sessions. */
1941
+ noLogsInDirectory(directory: string, extensions: string, folders: boolean): string;
1931
1942
  /**
1932
1943
  * The time window — the drill-down in time. Every figure below the line
1933
1944
  * describes a slice, so the line prints before any of them; clockless
package/src/index.ts CHANGED
@@ -114,6 +114,10 @@ import {
114
114
  languagesWithStanding,
115
115
  indexUsage,
116
116
  parseUsageLine,
117
+ SHAPE_COMMAND,
118
+ notAUsageLog,
119
+ usageShapesOf,
120
+ type UsageShape,
117
121
  plannedCalls,
118
122
  claudeCodeRecords,
119
123
  codexRecords,
@@ -133,16 +137,7 @@ import {
133
137
  anthropicUsageRecords,
134
138
  looksLikeOpenaiCost,
135
139
  looksLikeAnthropicCost,
136
- looksLikeAnthropicUsage,
137
- looksLikeClaudeCodeTranscript,
138
- looksLikeHelicone,
139
- looksLikeLangsmith,
140
- looksLikeLiteLlm,
141
- looksLikeOpenaiUsage,
142
- looksLikeOpenrouterActivity,
143
- looksLikeBatchResults,
144
140
  batchResultRecords,
145
- looksLikeOtel,
146
141
  openaiCostReport,
147
142
  openaiUsageRecords,
148
143
  openrouterActivityRecords,
@@ -595,7 +590,7 @@ async function usageIndexFrom(
595
590
  ): Promise<ReturnType<typeof indexUsage> | null> {
596
591
  const logPath = stringFlag(args, 'log');
597
592
  if (logPath === undefined) return null;
598
- const text = await readUsageLog(logPath, t);
593
+ const text = await readUsageLogOnly(logPath, t);
599
594
  const records = text
600
595
  .split('\n')
601
596
  .filter((line) => line.trim() !== '')
@@ -2205,7 +2200,7 @@ async function commandInit(
2205
2200
  .sort()
2206
2201
  .map((name) => join(root, readable.where, name));
2207
2202
  if (files.length > 0) {
2208
- const texts = await Promise.all(files.map((file) => readUsageLog(file, t)));
2203
+ const texts = await Promise.all(files.map((file) => readUsageLogOnly(file, t)));
2209
2204
  measured = profileUsage(texts.join('\n'), { catalogue: pricing });
2210
2205
  }
2211
2206
  } catch (error) {
@@ -3318,7 +3313,7 @@ async function commandFromClaudeCode(args: Args, t: CliMessages): Promise<void>
3318
3313
  }
3319
3314
 
3320
3315
  /**
3321
- * `trazum receipt <usage.jsonl|dir>` — the bill's counts, with the provenance
3316
+ * `trazum receipt <usage.jsonl>` — the bill's counts, with the provenance
3322
3317
  * of every figure attached.
3323
3318
  *
3324
3319
  * A profile answers a question on the terminal that ran it. The same figures
@@ -3519,7 +3514,7 @@ async function commandReceipt(
3519
3514
  if (file === undefined) throw new Error(t.receipt.noLog());
3520
3515
  const period = billingPeriod(args, t);
3521
3516
 
3522
- const text = await readUsageLog(file, t);
3517
+ const text = await readUsageLogOnly(file, t);
3523
3518
  const report = profileUsage(text, {
3524
3519
  catalogue: pricing,
3525
3520
  ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
@@ -3582,45 +3577,37 @@ function printReceiptSummary(document: ReceiptDocument, t: CliMessages): void {
3582
3577
  if (searches > 0) console.error(t.receipt.webSearch(searches, formatUsd(searchUsd)));
3583
3578
  }
3584
3579
 
3585
- /** The shapes `bill` can tell apart from a file's own text. */
3586
- type UsageSource =
3587
- | 'claude-code'
3588
- | 'codex'
3589
- | 'gemini-cli'
3590
- | 'otel'
3591
- | 'litellm'
3592
- | 'helicone'
3593
- | 'langsmith'
3594
- | 'anthropic-usage'
3595
- | 'openai-usage'
3596
- | 'batch-results'
3597
- | 'openrouter'
3598
- | 'usage-log';
3599
-
3600
- /**
3601
- * Which shapes claim a text. Every sniffer is asked, not the first that says
3602
- * yes: a file two shapes claim is a file this must not convert, because
3603
- * whichever it picked would be a guess wearing a result's clothes.
3604
- */
3605
- function usageSourcesOf(text: string): UsageSource[] {
3606
- const claims: UsageSource[] = [];
3607
- if (looksLikeCodexTranscript(text)) claims.push('codex');
3608
- if (looksLikeGeminiCliSession(text)) claims.push('gemini-cli');
3609
- if (looksLikeClaudeCodeTranscript(text)) claims.push('claude-code');
3610
- if (looksLikeOtel(text)) claims.push('otel');
3611
- if (looksLikeAnthropicUsage(text)) claims.push('anthropic-usage');
3612
- if (looksLikeOpenaiUsage(text)) claims.push('openai-usage');
3613
- if (looksLikeBatchResults(text)) claims.push('batch-results');
3614
- if (looksLikeOpenrouterActivity(text)) claims.push('openrouter');
3615
- if (looksLikeHelicone(text)) claims.push('helicone');
3616
- if (looksLikeLangsmith(text)) claims.push('langsmith');
3617
- if (looksLikeLiteLlm(text)) claims.push('litellm');
3618
- if (claims.length > 0) return claims;
3619
- /* A plain usage log has no signature but its own lines: if the first
3620
- non-blank one parses as a usage line, that is what it is. */
3621
- const first = text.split('\n').find((line) => line.trim() !== '');
3622
- if (first !== undefined && parseUsageLine(first) !== null) claims.push('usage-log');
3623
- return claims;
3580
+ /**
3581
+ * A usage log, for a command that reads nothing else.
3582
+ *
3583
+ * `profile` handed a Claude Code session answered "No usage records in that
3584
+ * file, 84 lines could not be read", which reads as a broken file, while
3585
+ * `bill` reads the same file as it is. So the shapes `bill` tells apart are
3586
+ * asked here too, and a file one of them claims is refused by name, with the
3587
+ * two commands that do read it. A provider's cost report is pointed at
3588
+ * `reconcile`, and a directory at `bill`, which walks one.
3589
+ *
3590
+ * Asked only when the first line is not already a usage line, so a usage log
3591
+ * pays one parse for it. A file nothing claims is returned as before, and its
3592
+ * unreadable lines are counted where they always were.
3593
+ *
3594
+ * `billPath` is what to name after `trazum bill`: the directory somebody
3595
+ * gave, when the file came out of one.
3596
+ */
3597
+ async function readUsageLogOnly(file: string, t: CliMessages, billPath: string = file): Promise<string> {
3598
+ const handle = await open(file, 'r');
3599
+ let text: string;
3600
+ try {
3601
+ if ((await handle.stat()).isDirectory()) throw new Error(t.errors.logIsDirectory(file));
3602
+ text = await readUsageHandle(handle, file, t);
3603
+ } finally {
3604
+ await handle.close();
3605
+ }
3606
+ const not = notAUsageLog(text);
3607
+ if (not === null) return text;
3608
+ if (not.kind === 'shape') throw new Error(t.errors.logIsOtherShape(file, not.shape, not.command, billPath));
3609
+ if (not.kind === 'ambiguous') throw new Error(t.errors.logIsAmbiguous(file, not.shapes.join(', ')));
3610
+ throw new Error(t.errors.logIsCostReport(file));
3624
3611
  }
3625
3612
 
3626
3613
  /**
@@ -3743,11 +3730,11 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3743
3730
  const unclaimed: string[] = [];
3744
3731
  /* The folders of the Claude Code sessions read, `<project>/<session>`, where the session keeps its other files. */
3745
3732
  const sessionFolders = new Set<string>();
3746
- const byShape = new Map<string, { files: number; records: number | null; leftOut: number }>();
3733
+ const byShape = new Map<UsageShape, { files: number; records: number | null; leftOut: number }>();
3747
3734
 
3748
3735
  for (const file of files) {
3749
3736
  const text = await readUsageLog(file, t);
3750
- const claims = usageSourcesOf(text);
3737
+ const claims = usageShapesOf(text);
3751
3738
 
3752
3739
  if (claims.length === 0) {
3753
3740
  if (looksLikeAnthropicCost(text) || looksLikeOpenaiCost(text)) {
@@ -3869,7 +3856,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3869
3856
  sources += 1;
3870
3857
  const count = shape === 'usage-log' ? null : records.length;
3871
3858
  if (perFile) {
3872
- console.error(t.bill.file(file, shape, count, leftOut));
3859
+ console.error(t.bill.file(file, shape, count, leftOut, SHAPE_COMMAND[shape]));
3873
3860
  } else {
3874
3861
  const sum = byShape.get(shape) ?? { files: 0, records: count === null ? null : 0, leftOut: 0 };
3875
3862
  sum.files += 1;
@@ -3878,7 +3865,9 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3878
3865
  byShape.set(shape, sum);
3879
3866
  }
3880
3867
  }
3881
- for (const [shape, sum] of byShape) console.error(t.bill.shapeSummary(shape, sum.files, sum.records, sum.leftOut));
3868
+ for (const [shape, sum] of byShape) {
3869
+ console.error(t.bill.shapeSummary(shape, sum.files, sum.records, sum.leftOut, SHAPE_COMMAND[shape]));
3870
+ }
3882
3871
  /*
3883
3872
  A Claude Code session keeps more than its transcript in the folder named
3884
3873
  after it: each subagent's metadata and prompt prefix, each workflow's
@@ -4334,7 +4323,7 @@ async function commandSwitch(args: Args, pricing: PricingCatalogue, t: CliMessag
4334
4323
  const migrationUsd = optional('migration-usd');
4335
4324
  const cases = optional('cases');
4336
4325
 
4337
- const text = await readUsageLog(file, t);
4326
+ const text = await readUsageLogOnly(file, t);
4338
4327
  const report = profileUsage(text, { catalogue: pricing });
4339
4328
  const analysis = switchAnalysis(report, target, {
4340
4329
  catalogue: pricing,
@@ -5039,7 +5028,7 @@ async function commandPosition(
5039
5028
  const file = args.positional[0];
5040
5029
  if (file === undefined) throw new Error(t.position.noLog());
5041
5030
 
5042
- const text = await readUsageLog(file, t);
5031
+ const text = await readUsageLogOnly(file, t);
5043
5032
  const records = text
5044
5033
  .split('\n')
5045
5034
  .filter((line) => line.trim() !== '')
@@ -5891,7 +5880,7 @@ async function commandLadder(
5891
5880
  if (path === undefined) {
5892
5881
  throw new Error(t.errors.missingInputFile());
5893
5882
  }
5894
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
5883
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
5895
5884
  const ladders = config.ladders ?? {};
5896
5885
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
5897
5886
  const pct = (value: number): string => `${(value * 100).toFixed(1)}%`;
@@ -6031,7 +6020,7 @@ async function commandExperiment(
6031
6020
  throw new Error(t.experiment.needsRule());
6032
6021
  }
6033
6022
 
6034
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
6023
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
6035
6024
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
6036
6025
  const pct = (value: number): string => `${(value * 100).toFixed(1)}%`;
6037
6026
 
@@ -6170,7 +6159,7 @@ async function commandQuality(
6170
6159
  * this whole module exists to avoid: two files gathered under conditions
6171
6160
  * nobody wrote down.
6172
6161
  */
6173
- const raw = await readUsageLog(path, t);
6162
+ const raw = await readUsageLogOnly(path, t);
6174
6163
  const sideOf = (since: number | undefined, until: number | undefined): GateSide => {
6175
6164
  const report = profileUsage(raw, { catalogue: pricing, label, sinceMs: since, untilMs: until });
6176
6165
  const slice = report.outcomeTallyByLabel.find((entry) => entry.label === label);
@@ -6424,7 +6413,7 @@ async function commandOwners(
6424
6413
  return;
6425
6414
  }
6426
6415
 
6427
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
6416
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
6428
6417
  const result = allocate(
6429
6418
  report.byLabel.map((entry) => ({
6430
6419
  label: entry.label,
@@ -6571,7 +6560,7 @@ async function commandCommitment(
6571
6560
  const months = Number(stringFlag(args, 'months') ?? 12);
6572
6561
  const terms = { monthlyFloorUsd: floor, discount, months };
6573
6562
 
6574
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
6563
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
6575
6564
  /**
6576
6565
  * Whole calendar months only.
6577
6566
  *
@@ -6721,7 +6710,7 @@ async function commandReport(
6721
6710
  const year = stringFlag(args, 'year');
6722
6711
  if (year === undefined || !/^\d{4}$/.test(year)) throw new Error(t.annual.needsYear());
6723
6712
 
6724
- const report = profileUsage(await readUsageLog(path, t), { catalogue: pricing });
6713
+ const report = profileUsage(await readUsageLogOnly(path, t), { catalogue: pricing });
6725
6714
 
6726
6715
  /**
6727
6716
  * One period per calendar month, built from the day series.
@@ -7180,7 +7169,7 @@ async function commandOptimize(
7180
7169
  if (fromLogPath === undefined) throw new Error(t.errors.allLabelsNeedsLog());
7181
7170
  const labelsMap = config.labels ?? {};
7182
7171
  if (Object.keys(labelsMap).length === 0) throw new Error(t.errors.allLabelsNeedsMap());
7183
- const report = profileUsage(await readUsageLog(fromLogPath, t), { catalogue: pricing });
7172
+ const report = profileUsage(await readUsageLogOnly(fromLogPath, t), { catalogue: pricing });
7184
7173
  const coverage = labelCoverage(report, labelsMap);
7185
7174
  const level = levelFlag(args, config, t);
7186
7175
 
@@ -7296,7 +7285,7 @@ async function commandOptimize(
7296
7285
  throw new Error(t.errors.fromLogConflict(flag));
7297
7286
  }
7298
7287
  }
7299
- const report = profileUsage(await readUsageLog(fromLog, t), { catalogue: pricing });
7288
+ const report = profileUsage(await readUsageLogOnly(fromLog, t), { catalogue: pricing });
7300
7289
 
7301
7290
  /**
7302
7291
  * Which label this prompt is. `--label` says it outright; otherwise the
@@ -9098,9 +9087,12 @@ async function commandVerify(
9098
9087
  .filter((entry) => entry.isFile() && READABLE.some((ext) => entry.name.endsWith(ext)))
9099
9088
  .map((entry) => join(againstPath, entry.name))
9100
9089
  .sort((a, b) => a.localeCompare(b));
9101
- if (files.length === 0) throw new Error(t.profile.noLogsInDirectory(againstPath, READABLE.join(', ')));
9090
+ if (files.length === 0) {
9091
+ const folders = entries.some((entry) => entry.isDirectory());
9092
+ throw new Error(t.profile.noLogsInDirectory(againstPath, READABLE.join(', '), folders));
9093
+ }
9102
9094
  }
9103
- const texts = await Promise.all(files.map((file) => readUsageLog(file, t)));
9095
+ const texts = await Promise.all(files.map((file) => readUsageLogOnly(file, t, againstPath)));
9104
9096
  const raw = texts.map((text) => (text.endsWith('\n') ? text : `${text}\n`)).join('');
9105
9097
  const report = profileUsage(raw, { catalogue: pricing });
9106
9098
 
@@ -11352,9 +11344,12 @@ async function commandPlan(
11352
11344
  .filter((entry) => entry.isFile() && READABLE.some((ext) => entry.name.endsWith(ext)))
11353
11345
  .map((entry) => join(path, entry.name))
11354
11346
  .sort((a, b) => a.localeCompare(b));
11355
- if (files.length === 0) throw new Error(t.profile.noLogsInDirectory(path, READABLE.join(', ')));
11347
+ if (files.length === 0) {
11348
+ const folders = entries.some((entry) => entry.isDirectory());
11349
+ throw new Error(t.profile.noLogsInDirectory(path, READABLE.join(', '), folders));
11350
+ }
11356
11351
  }
11357
- const texts = await Promise.all(files.map((file) => readUsageLog(file, t)));
11352
+ const texts = await Promise.all(files.map((file) => readUsageLogOnly(file, t, path)));
11358
11353
  const raw = texts.map((text) => (text.endsWith('\n') ? text : `${text}\n`)).join('');
11359
11354
 
11360
11355
  const report = profileUsage(raw, { catalogue: pricing });
@@ -11517,7 +11512,9 @@ async function commandProfile(
11517
11512
  .map((entry) => join(entry.parentPath ?? path, entry.name))
11518
11513
  .sort((a, b) => a.localeCompare(b));
11519
11514
  if (logFiles.length === 0) {
11520
- throw new Error(t.profile.noLogsInDirectory(path, READABLE.join(', ')));
11515
+ /* Folders only matter to the flat walk: --by-source went into them. */
11516
+ const folders = !bySourceMode && entries.some((entry) => entry.isDirectory());
11517
+ throw new Error(t.profile.noLogsInDirectory(path, READABLE.join(', '), folders));
11521
11518
  }
11522
11519
  }
11523
11520
  /**
@@ -11532,7 +11529,7 @@ async function commandProfile(
11532
11529
  * alternative — skipping it — is a total quietly missing a day, which is
11533
11530
  * the failure this repository refuses in every other place it can occur.
11534
11531
  */
11535
- const logTexts = await Promise.all(logFiles.map((file) => readUsageLog(file, t)));
11532
+ const logTexts = await Promise.all(logFiles.map((file) => readUsageLogOnly(file, t, path)));
11536
11533
  // A file that does not end in a newline would otherwise glue its last record
11537
11534
  // to the next file's first one, and both would be reported as unreadable.
11538
11535
  const raw = logTexts.map((text) => (text.endsWith('\n') ? text : `${text}\n`)).join('');
@@ -11691,7 +11688,7 @@ async function commandProfile(
11691
11688
  // The same reader as the log itself, so `--against last-month.jsonl.gz`
11692
11689
  // works: a comparison that could only read one of the two formats would
11693
11690
  // be a flag that fails on exactly the rotated file it exists to read.
11694
- ? profileUsage(await readUsageLog(againstPath, t), {
11691
+ ? profileUsage(await readUsageLogOnly(againstPath, t), {
11695
11692
  catalogue: pricing,
11696
11693
  label: onlyLabel,
11697
11694
  // The same window on both sides, for the same reason as the label:
@@ -1,5 +1,14 @@
1
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';
2
+ import {
3
+ AGENT_SHAPES,
4
+ BUNDLED_CATALOGUE,
5
+ billLevers,
6
+ buildPlan,
7
+ notAUsageLog,
8
+ parsePlanDocument,
9
+ profileUsage,
10
+ verifyPlan,
11
+ } from '@trazum/core';
3
12
  import type { PricingCatalogue } from '@trazum/core';
4
13
 
5
14
  export class SavingsInputError extends Error {}
@@ -19,7 +28,33 @@ export function validateSavingsPayload(value: unknown, verify: boolean): void {
19
28
  }
20
29
  }
21
30
 
31
+ /**
32
+ * A coding agent's session sent as `log` was refused as "no readable usage
33
+ * records", which reads as a broken file when `/usage/import` converts it in
34
+ * one request. Named instead, through the same verdict the CLI and the MCP
35
+ * server use, with the request or command that reads it.
36
+ */
37
+ function refuseOtherShape(log: string): void {
38
+ const not = notAUsageLog(log);
39
+ if (not === null) return;
40
+ if (not.kind === 'shape' && AGENT_SHAPES.includes(not.shape)) {
41
+ throw new SavingsInputError(
42
+ `log is a ${not.shape} session, not a usage log. POST it to /usage/import with format "${not.shape}", then send the log that returns.`,
43
+ );
44
+ }
45
+ if (not.kind === 'shape') {
46
+ throw new SavingsInputError(
47
+ `log is ${not.shape} data, not a usage log. ${not.command === null ? '' : `trazum ${not.command} turns it into one; `}trazum bill reads it as it is.`,
48
+ );
49
+ }
50
+ if (not.kind === 'ambiguous') {
51
+ throw new SavingsInputError(`log is not a usage log, and more than one format claims it (${not.shapes.join(', ')}), so it was not converted.`);
52
+ }
53
+ throw new SavingsInputError("log is a provider's cost report, a bill rather than usage. trazum reconcile sets it beside a receipt.");
54
+ }
55
+
22
56
  function savingsReport(log: string, catalogue: PricingCatalogue) {
57
+ refuseOtherShape(log);
23
58
  const report = profileUsage(log, { catalogue });
24
59
  if (report.total.calls + report.unpriced.calls === 0) {
25
60
  throw new SavingsInputError('log contains no readable usage records; pass normalized JSONL text with model and token counts');