@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.
Files changed (83) 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 +187 -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 +45 -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 +45 -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 +125 -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-import-schema.d.ts +34 -0
  35. package/dist/serve-import-schema.d.ts.map +1 -0
  36. package/dist/serve-import-schema.js +31 -0
  37. package/dist/serve-import-schema.js.map +1 -0
  38. package/dist/serve-import.d.ts +43 -0
  39. package/dist/serve-import.d.ts.map +1 -0
  40. package/dist/serve-import.js +49 -0
  41. package/dist/serve-import.js.map +1 -0
  42. package/dist/serve-savings-schema.d.ts +65 -0
  43. package/dist/serve-savings-schema.d.ts.map +1 -0
  44. package/dist/serve-savings-schema.js +54 -0
  45. package/dist/serve-savings-schema.js.map +1 -0
  46. package/dist/serve-savings.d.ts +55 -0
  47. package/dist/serve-savings.d.ts.map +1 -0
  48. package/dist/serve-savings.js +144 -0
  49. package/dist/serve-savings.js.map +1 -0
  50. package/dist/serve-schema.d.ts +606 -0
  51. package/dist/serve-schema.d.ts.map +1 -0
  52. package/dist/serve-schema.js +151 -0
  53. package/dist/serve-schema.js.map +1 -0
  54. package/dist/serve.d.ts.map +1 -1
  55. package/dist/serve.js +37 -5
  56. package/dist/serve.js.map +1 -1
  57. package/dist/task-files.d.ts +9 -0
  58. package/dist/task-files.d.ts.map +1 -0
  59. package/dist/task-files.js +136 -0
  60. package/dist/task-files.js.map +1 -0
  61. package/dist/task.d.ts +2 -0
  62. package/dist/task.d.ts.map +1 -0
  63. package/dist/task.js +137 -0
  64. package/dist/task.js.map +1 -0
  65. package/package.json +2 -2
  66. package/src/filter.ts +150 -0
  67. package/src/gateway-server.ts +46 -10
  68. package/src/gateway-spend.ts +120 -0
  69. package/src/html.ts +25 -1
  70. package/src/i18n/en.ts +47 -4
  71. package/src/i18n/es.ts +47 -4
  72. package/src/i18n/types.ts +14 -1
  73. package/src/index.ts +115 -63
  74. package/src/markdown.ts +20 -1
  75. package/src/pdf.ts +36 -1
  76. package/src/serve-import-schema.ts +31 -0
  77. package/src/serve-import.ts +57 -0
  78. package/src/serve-savings-schema.ts +53 -0
  79. package/src/serve-savings.ts +140 -0
  80. package/src/serve-schema.ts +155 -0
  81. package/src/serve.ts +38 -5
  82. package/src/task-files.ts +114 -0
  83. package/src/task.ts +119 -0
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import { createInterface } from 'node:readline/promises';
7
7
  import { dirname, join, resolve as resolvePath } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { gunzipSync } from 'node:zlib';
10
- import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billLevers, bucketedCacheEconomics, bucketedProfile, buildHistory, buildPlan, connectorFor, CONNECTORS, normalizeAnthropicUsage, normalizeOpenAIUsage, bucketsFromRecords, evaluateWatch, firedKey, pruneRecords, recordsFromBuckets, storeInventory, storedReportFrom, verifyPlan, cacheEconomics, cacheHitRate, contextPressure, comparePrompts, compareToBaseline, computeSavings, bandGoverns, countTokensAnthropic, DEFAULT_USAGE, budgetPositions, conform, BREAK_EVEN_BAND, allocate, annualRecord, replayCommitment, coversTheTerm, runExperiment, qualityGate, semanticPassCost, verifySemanticProposals, SEMANTIC_SYSTEM_PROMPT, ladderPosition, validateLadder, outcomeReport, rankPerOutcome, FAILURE_POLICIES, detectFromSource, matchLocale, parsePlanDocument, waiverDay, waiverHistory, proposeInit, MIN_RATE_DAYS, parseConfig, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, rollUp, heartbeats, ruleYield, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, receiptFrom, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, matchGlob, MAX_INPUT_CHARS, moneyIsComparable, mostSpecificMatch, assemble, interview, nearestName, slot, SLOT_IDS, optimize, parseBaseline, PHRASE_LANGUAGES, detectTextLanguage, dictionaryStanding, languagesWithStanding, indexUsage, parseUsageLine, plannedCalls, claudeCodeRecords, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, looksLikeAnthropicUsage, looksLikeClaudeCodeTranscript, looksLikeHelicone, looksLikeLangsmith, looksLikeLiteLlm, looksLikeOpenaiUsage, looksLikeOpenrouterActivity, looksLikeOtel, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
10
+ import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billLevers, bucketedCacheEconomics, bucketedProfile, buildHistory, buildPlan, connectorFor, CONNECTORS, normalizeAnthropicUsage, normalizeOpenAIUsage, bucketsFromRecords, evaluateWatch, firedKey, pruneRecords, recordsFromBuckets, storeInventory, storedReportFrom, verifyPlan, cacheEconomics, cacheHitRate, contextPressure, comparePrompts, compareToBaseline, computeSavings, bandGoverns, countTokensAnthropic, DEFAULT_USAGE, budgetPositions, conform, BREAK_EVEN_BAND, allocate, annualRecord, replayCommitment, coversTheTerm, runExperiment, qualityGate, semanticPassCost, verifySemanticProposals, SEMANTIC_SYSTEM_PROMPT, ladderPosition, validateLadder, outcomeReport, rankPerOutcome, FAILURE_POLICIES, detectFromSource, matchLocale, parsePlanDocument, waiverDay, waiverHistory, proposeInit, MIN_RATE_DAYS, parseConfig, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, rollUp, heartbeats, ruleYield, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, receiptFrom, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, matchGlob, MAX_INPUT_CHARS, moneyIsComparable, mostSpecificMatch, assemble, interview, nearestName, slot, SLOT_IDS, optimize, parseBaseline, PHRASE_LANGUAGES, detectTextLanguage, dictionaryStanding, languagesWithStanding, indexUsage, parseUsageLine, plannedCalls, claudeCodeRecords, codexRecords, looksLikeCodexTranscript, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, looksLikeAnthropicUsage, looksLikeClaudeCodeTranscript, looksLikeHelicone, looksLikeLangsmith, looksLikeLiteLlm, looksLikeOpenaiUsage, looksLikeOpenrouterActivity, looksLikeOtel, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, spendByMonth, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
11
11
  import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cache.js';
12
12
  import { OPTIONAL_COUNTERS } from './optional-counters.js';
13
13
  import { dayOf, formatGap, median, spanDays } from './time.js';
@@ -34,6 +34,8 @@ import { renderProfilePdf } from './pdf.js';
34
34
  // to plain output, and a pipe stays plain.
35
35
  import { bar, c, sectionHeading, table } from './style.js';
36
36
  const VALUE_FLAGS = new Set([
37
+ 'id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions',
38
+ 'recovery-dir',
37
39
  'answers',
38
40
  'label-by-cwd',
39
41
  'label-by-workspace',
@@ -397,6 +399,8 @@ function disabledRules(args, config) {
397
399
  */
398
400
  const GLOBAL_FLAGS = ['help', 'h', 'version', 'v', 'locale', 'json', 'config', 'pricing', 'pricing-live', 'max-input'];
399
401
  const COMMAND_FLAGS = {
402
+ task: ['id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions', 'out', 'o', 'json'],
403
+ filter: ['recovery-dir', 'stats'],
400
404
  optimize: [
401
405
  'level', 'model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch',
402
406
  'disable', 'llm', 'exact-tokens', 'diff', 'reorder', 'out', 'o',
@@ -425,6 +429,7 @@ const COMMAND_FLAGS = {
425
429
  rollup: ['json', 'html-out'],
426
430
  position: ['json', 'html-out', 'pricing', 'pricing-live'],
427
431
  receipt: ['out', 'o', 'stamp', 'pricing', 'pricing-live', 'since', 'until'],
432
+ 'from-codex': ['label', 'out', 'o'],
428
433
  'from-claude-code': ['label', 'label-by-cwd', 'label-from-project', 'out', 'o', 'state'],
429
434
  'from-otel': ['label-from-service', 'out', 'o'],
430
435
  'from-litellm': ['out', 'o'],
@@ -890,6 +895,10 @@ measured = null) {
890
895
  * a measurable one, and it is the honest answer to "what did I gain" on a plan
891
896
  * that costs the same either way.
892
897
  */
898
+ /** A conservative display default, never evidence of a payment arrangement. */
899
+ function prefersTokenReport(host) {
900
+ return ['claude-code', 'codex', 'cursor'].includes(host.id);
901
+ }
893
902
  function printTokensOnly(result, host, t, n,
894
903
  /** Whether they named a scenario while the money was being withheld. */
895
904
  namedScenario = false) {
@@ -897,10 +906,7 @@ namedScenario = false) {
897
906
  const saved = result.tokensBefore - result.tokensAfter;
898
907
  console.log();
899
908
  console.log(sectionHeading(t.report.tokensOnlyHeading(host.displayName)));
900
- // Only claim the host bills by subscription when it does. Forced with the
901
- // flag on GitHub Actions, the first version said "GitHub Actions bills by
902
- // subscription", which is simply false.
903
- console.log(` ${host.billing === 'subscription'
909
+ console.log(` ${prefersTokenReport(host)
904
910
  ? t.report.tokensOnlyWhy(host.displayName)
905
911
  : t.report.tokensOnlyAsked()}`);
906
912
  console.log();
@@ -1142,12 +1148,7 @@ async function commandWhere(args, config, pricing, t) {
1142
1148
  console.log();
1143
1149
  console.log(c.bold(t.where.hostHeading()));
1144
1150
  console.log(` ${host.displayName}${host.evidence ? c.dim(` (${host.evidence})`) : ''}`);
1145
- // The reason this is worth printing at all. Inside a flat plan the monthly
1146
- // figure Trazum computes is arithmetic about tokens, not money anybody gets
1147
- // back, and saying so is more useful than saying nothing.
1148
- if (host.billing === 'subscription') {
1149
- console.log(` ${c.yellow(t.where.subscription(host.displayName))}`);
1150
- }
1151
+ console.log(` ${c.dim(t.where.billingUnknown(host.displayName))}`);
1151
1152
  const target = args.positional[0];
1152
1153
  if (target === undefined) {
1153
1154
  console.log();
@@ -1300,9 +1301,7 @@ function renderInit(proposal, ctx) {
1300
1301
  console.log();
1301
1302
  // 1. Where this is running.
1302
1303
  console.log(` ${t.init.host(ctx.host.displayName)}`);
1303
- if (ctx.host.billing === 'subscription') {
1304
- console.log(` ${c.yellow(t.where.subscription(ctx.host.displayName))}`);
1305
- }
1304
+ console.log(` ${c.dim(t.where.billingUnknown(ctx.host.displayName))}`);
1306
1305
  // 2. The prompts.
1307
1306
  console.log(` ${ctx.prompts.files.length === 0 ? c.dim(t.init.noPrompts()) : t.init.prompts(ctx.prompts.files.length)}`);
1308
1307
  if (ctx.truncated)
@@ -2749,6 +2748,8 @@ function printReceiptSummary(document, t) {
2749
2748
  */
2750
2749
  function usageSourcesOf(text) {
2751
2750
  const claims = [];
2751
+ if (looksLikeCodexTranscript(text))
2752
+ claims.push('codex');
2752
2753
  if (looksLikeClaudeCodeTranscript(text))
2753
2754
  claims.push('claude-code');
2754
2755
  if (looksLikeOtel(text))
@@ -2870,6 +2871,8 @@ async function commandBill(args, pricing, t) {
2870
2871
  let labelledByProject = 0;
2871
2872
  /* Claude Code transcripts read: their money is an API-rate equivalent. */
2872
2873
  let claudeCodeFiles = 0;
2874
+ let codexFiles = 0;
2875
+ const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
2873
2876
  const lines = [];
2874
2877
  let sources = 0;
2875
2878
  /*
@@ -2902,6 +2905,20 @@ async function commandBill(args, pricing, t) {
2902
2905
  let records = [];
2903
2906
  let leftOut = 0;
2904
2907
  switch (shape) {
2908
+ case 'codex': {
2909
+ codexFiles += 1;
2910
+ const c = codexRecords(text, withLabel);
2911
+ codexEvidence.files += 1;
2912
+ codexEvidence.duplicates += c.duplicates;
2913
+ codexEvidence.missingModel += c.missingModel;
2914
+ codexEvidence.unsupported += c.unsupported;
2915
+ codexEvidence.unparseable += c.unparseable;
2916
+ records = c.records;
2917
+ leftOut = c.missingModel + c.unsupported + c.unparseable;
2918
+ if (leftOut > 0)
2919
+ console.error(t.fromCodex.gaps(c.missingModel, c.unsupported, c.unparseable));
2920
+ break;
2921
+ }
2905
2922
  case 'claude-code': {
2906
2923
  claudeCodeFiles += 1;
2907
2924
  const project = label === undefined && labelFromProject && walked.has(file) ? projectLabelFor(file) : undefined;
@@ -2998,7 +3015,11 @@ async function commandBill(args, pricing, t) {
2998
3015
  });
2999
3016
  refuseEmptyPeriod(text, report, period, pricing, t);
3000
3017
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
3001
- const json = JSON.stringify(document, null, 2);
3018
+ const billDocument = codexFiles === 0 ? document : {
3019
+ ...document,
3020
+ importEvidence: [{ ...codexEvidence, complete: codexEvidence.missingModel + codexEvidence.unsupported + codexEvidence.unparseable === 0 }],
3021
+ };
3022
+ const json = JSON.stringify(billDocument, null, 2);
3002
3023
  /*
3003
3024
  A terminal gets a statement a person can read; a pipe gets the receipt.
3004
3025
  The receipt on a terminal was 60 lines of JSON before the first figure a
@@ -3020,8 +3041,8 @@ async function commandBill(args, pricing, t) {
3020
3041
  console.error(t.bill.sources(sources, files.length));
3021
3042
  printReceiptSummary(document, t);
3022
3043
  if (statement)
3023
- printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles > 0);
3024
- await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles > 0);
3044
+ printBillStatement(report, labelledByProject > 0, t, period.words, claudeCodeFiles + codexFiles > 0);
3045
+ await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, claudeCodeFiles + codexFiles > 0);
3025
3046
  /*
3026
3047
  A slug with a slash in it is how OpenRouter names a model, and the bundled
3027
3048
  catalogue does not carry those: the live overlay does. Said only when the
@@ -3143,38 +3164,22 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false)
3143
3164
  report's own days, oldest first, newest kept when there are many; shown
3144
3165
  only once the bill spans two calendar months, since one month is the total.
3145
3166
  */
3146
- const months = new Map();
3147
- for (const day of report.spendByDay) {
3148
- const month = months.get(day.day.slice(0, 7)) ?? { calls: 0, usd: 0 };
3149
- month.calls += day.calls;
3150
- month.usd += day.usd;
3151
- months.set(day.day.slice(0, 7), month);
3152
- }
3153
- if (months.size >= 2) {
3154
- const ordered = [...months.entries()].sort(([a], [b]) => a.localeCompare(b));
3155
- const shown = ordered.slice(-LIMIT).map(([name, { calls, usd }]) => {
3167
+ const { months, undated } = spendByMonth(report);
3168
+ if (months.length >= 2) {
3169
+ const shown = months.slice(-LIMIT).map(({ month, calls, usd }) => {
3156
3170
  const share = total > 0 ? usd / total : 0;
3157
- return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3171
+ return [month, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
3158
3172
  });
3159
- if (ordered.length > LIMIT)
3160
- shown.unshift([c.dim(t.bill.earlierMonths(ordered.length - LIMIT)), '', '', '']);
3173
+ if (months.length > LIMIT)
3174
+ shown.unshift([c.dim(t.bill.earlierMonths(months.length - LIMIT)), '', '', '']);
3161
3175
  console.log();
3162
3176
  for (const line of table(columns(t.bill.colMonth()), shown))
3163
3177
  console.log(line);
3164
- const dated = ordered.reduce((sum, [, month]) => ({ calls: sum.calls + month.calls, usd: sum.usd + month.usd }), {
3165
- calls: 0,
3166
- usd: 0,
3167
- });
3168
- const undatedCalls = report.total.calls - dated.calls;
3169
- if (undatedCalls > 0) {
3170
- console.log(c.dim(` ${wrap(t.bill.monthsUndated(undatedCalls, formatUsd(total - dated.usd)), 74, ' ')}`));
3171
- }
3172
- const newest = ordered[ordered.length - 1]?.[0];
3173
- if (newest !== undefined) {
3174
- const [year, month] = newest.split('-').map(Number);
3175
- const lastDay = new Date(Date.UTC(year ?? 1970, month ?? 1, 0)).toISOString().slice(0, 10);
3176
- console.log(c.dim(` ${t.bill.monthHint(`${newest}-01`, lastDay)}`));
3178
+ if (undated.calls > 0) {
3179
+ console.log(c.dim(` ${wrap(t.bill.monthsUndated(undated.calls, formatUsd(undated.usd)), 74, ' ')}`));
3177
3180
  }
3181
+ const newest = months[months.length - 1];
3182
+ console.log(c.dim(` ${t.bill.monthHint(newest.firstDay, newest.lastDay)}`));
3178
3183
  }
3179
3184
  console.log();
3180
3185
  if (report.unpricedModels.length > 0) {
@@ -3390,6 +3395,61 @@ function commandOwnrate(args, t) {
3390
3395
  };
3391
3396
  console.log(JSON.stringify(snippet, null, 2));
3392
3397
  }
3398
+ /** Explicit paths only: Codex histories are not discovered from the user's home. */
3399
+ async function commandFromCodex(args, t) {
3400
+ const target = args.positional[0];
3401
+ if (target === undefined)
3402
+ throw new Error(t.fromCodex.noPath());
3403
+ let info;
3404
+ try {
3405
+ info = await stat(target);
3406
+ }
3407
+ catch {
3408
+ throw new Error(t.fromCodex.notFound(target));
3409
+ }
3410
+ const files = info.isDirectory()
3411
+ ? (await readdir(target, { recursive: true, withFileTypes: true }))
3412
+ .filter((entry) => entry.isFile() && /\.(jsonl|ndjson)$/i.test(entry.name))
3413
+ .map((entry) => join(entry.parentPath, entry.name)).sort()
3414
+ : [target];
3415
+ if (files.length === 0)
3416
+ throw new Error(t.fromCodex.noFiles(target));
3417
+ const label = stringFlag(args, 'label');
3418
+ const lines = [];
3419
+ let duplicates = 0;
3420
+ let missingModel = 0;
3421
+ let unsupported = 0;
3422
+ let unparseable = 0;
3423
+ for (const file of files) {
3424
+ const text = await readFile(file, 'utf8');
3425
+ if (!looksLikeCodexTranscript(text)) {
3426
+ unsupported++;
3427
+ continue;
3428
+ }
3429
+ const conversion = codexRecords(text, label === undefined ? {} : { label });
3430
+ for (const record of conversion.records)
3431
+ lines.push(JSON.stringify(record));
3432
+ duplicates += conversion.duplicates;
3433
+ missingModel += conversion.missingModel;
3434
+ unsupported += conversion.unsupported;
3435
+ unparseable += conversion.unparseable;
3436
+ }
3437
+ console.error(t.fromCodex.summary(files.length, lines.length, duplicates));
3438
+ if (missingModel + unsupported + unparseable > 0) {
3439
+ console.error(t.fromCodex.gaps(missingModel, unsupported, unparseable));
3440
+ }
3441
+ console.error(t.fromCodex.caveat());
3442
+ if (lines.length === 0)
3443
+ throw new Error(t.fromCodex.noUsage());
3444
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3445
+ const text = lines.join('\n') + '\n';
3446
+ if (out !== undefined) {
3447
+ await writeFile(out, text, 'utf8');
3448
+ console.error(t.fromCodex.written(out));
3449
+ }
3450
+ else
3451
+ console.log(text.trimEnd());
3452
+ }
3393
3453
  async function commandFromOtel(args, t) {
3394
3454
  const target = args.positional[0];
3395
3455
  if (target === undefined)
@@ -4540,12 +4600,13 @@ async function commandGateway(args, config, configDir, pricing, t) {
4540
4600
  const budget = budgetPositions(resolved.records, config.spend, { catalogue: pricing });
4541
4601
  const position = budget.positions[0] ?? null;
4542
4602
  /**
4543
- * Read once at start, like `serve`'s.
4603
+ * Read the baseline once at start. The gateway adds its own completed
4604
+ * usage and reserves in-flight estimates in memory via `liveBudget`.
4544
4605
  *
4545
4606
  * A file read in the request path would put Trazum's own latency between a
4546
4607
  * caller and their provider on every call, which is a cost this product
4547
- * would otherwise be reporting on somebody else. The staleness is real, so a
4548
- * refusal carries `asOfMs` and says what it rested on.
4608
+ * would otherwise be reporting on somebody else. External spend is still
4609
+ * stale, so a refusal carries the baseline's `asOfMs`.
4549
4610
  */
4550
4611
  const standing = position === null || position.coverage === 'none'
4551
4612
  ? null
@@ -4567,6 +4628,7 @@ async function commandGateway(args, config, configDir, pricing, t) {
4567
4628
  */
4568
4629
  let unmeasured = 0;
4569
4630
  const server = buildGateway({
4631
+ liveBudget: true,
4570
4632
  provider,
4571
4633
  catalogue: pricing,
4572
4634
  policy: {
@@ -5948,24 +6010,12 @@ async function commandOptimize(args, config, pricing, t, locale) {
5948
6010
  }
5949
6011
  return;
5950
6012
  }
5951
- // Tokens-only when the host bills by subscription: there is no bill to
5952
- // reduce, so a monthly figure would be arithmetic about tokens dressed as
5953
- // money. Either flag overrides it, because the host says where *Trazum* runs
5954
- // and not where the prompt goes — somebody editing a production prompt inside
5955
- // Cursor wants the dollars, and they should not have to leave the editor to
5956
- // see them.
6013
+ // Agent harnesses default to token context; their identity does not establish
6014
+ // billing. Explicit API-cost requests and usage-log scenarios retain pricing.
5957
6015
  const host = detectHost();
5958
- /**
5959
- * `--from-log` implies `--cost`, and the reasoning is different from the
5960
- * `--calls` case documented below: `--calls` is a typed scenario parameter,
5961
- * but a usage log with billed token counts is *evidence* — proof this
5962
- * prompt's traffic goes to a metered API, whatever the terminal running
5963
- * the command bills like. Withholding the money there would suppress
5964
- * exactly the figures the person measured in order to see.
5965
- */
5966
6016
  const tokensOnly = boolFlag(args, 'cost') || measured !== null
5967
6017
  ? false
5968
- : boolFlag(args, 'tokens-only') || host.billing === 'subscription';
6018
+ : boolFlag(args, 'tokens-only') || prefersTokenReport(host);
5969
6019
  /**
5970
6020
  * Whether they named a scenario while the money was being withheld.
5971
6021
  *
@@ -11115,6 +11165,17 @@ function printRank(ranked, context) {
11115
11165
  }
11116
11166
  async function main() {
11117
11167
  const argv = process.argv.slice(2);
11168
+ if (argv[0] === 'task') {
11169
+ const { runTask } = await import('./task.js');
11170
+ await runTask(argv.slice(1));
11171
+ return;
11172
+ }
11173
+ // The stdin display filter has its own small grammar and no project config.
11174
+ if (argv[0] === 'filter') {
11175
+ const { runFilter } = await import('./filter.js');
11176
+ await runFilter(argv.slice(1));
11177
+ return;
11178
+ }
11118
11179
  let locale = localeFromArgv(argv);
11119
11180
  let t = getCliMessages(locale);
11120
11181
  const args = parseArgs(argv, t);
@@ -11316,6 +11377,9 @@ async function main() {
11316
11377
  case 'reconcile':
11317
11378
  await commandReconcile(args, t);
11318
11379
  break;
11380
+ case 'from-codex':
11381
+ await commandFromCodex(args, t);
11382
+ break;
11319
11383
  case 'from-otel':
11320
11384
  await commandFromOtel(args, t);
11321
11385
  break;