@trazum/cli 2.7.12 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/assets/trazum-statusline.sh +131 -0
- package/dist/git.d.ts +38 -0
- package/dist/git.d.ts.map +1 -1
- package/dist/git.js +54 -0
- package/dist/git.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +170 -3
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +174 -3
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/types.d.ts +84 -0
- package/dist/i18n/types.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +670 -262
- package/dist/index.js.map +1 -1
- package/dist/proactive.d.ts +344 -0
- package/dist/proactive.d.ts.map +1 -0
- package/dist/proactive.js +1079 -0
- package/dist/proactive.js.map +1 -0
- package/dist/style.d.ts +305 -26
- package/dist/style.d.ts.map +1 -1
- package/dist/style.js +449 -47
- package/dist/style.js.map +1 -1
- package/dist/watch-notify.d.ts +82 -0
- package/dist/watch-notify.d.ts.map +1 -0
- package/dist/watch-notify.js +118 -0
- package/dist/watch-notify.js.map +1 -0
- package/dist/watch-run.d.ts +7 -0
- package/dist/watch-run.d.ts.map +1 -1
- package/dist/watch-run.js.map +1 -1
- package/dist/weekly.d.ts +32 -0
- package/dist/weekly.d.ts.map +1 -0
- package/dist/weekly.js +119 -0
- package/dist/weekly.js.map +1 -0
- package/package.json +3 -2
- package/src/git.ts +77 -0
- package/src/i18n/en.ts +198 -3
- package/src/i18n/es.ts +202 -3
- package/src/i18n/types.ts +130 -0
- package/src/index.ts +715 -302
- package/src/proactive.ts +1319 -0
- package/src/style.ts +502 -54
- package/src/watch-notify.ts +152 -0
- package/src/watch-run.ts +7 -0
- package/src/weekly.ts +133 -0
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
|
-
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
|
|
4
4
|
import { mkdir, mkdtemp, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
5
5
|
import { cpus, homedir, tmpdir } from 'node:os';
|
|
6
6
|
import { createInterface } from 'node:readline/promises';
|
|
@@ -8,7 +8,7 @@ import { dirname, join, resolve as resolvePath } from 'node:path';
|
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
9
|
import { createGunzip, gunzipSync } from 'node:zlib';
|
|
10
10
|
import { Readable } from 'node:stream';
|
|
11
|
-
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, SHAPE_COMMAND, notAUsageLog, usageShapesOf, plannedCalls, claudeCodeRecords, codexRecords, looksLikeCodexTranscript, geminiCliRecords, looksLikeGeminiCliSession, slimUsageLine, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, batchResultRecords, 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, spendByPeriod, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
|
|
11
|
+
import { CONTRACT_NAMES, contractSchema, applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billFigures, billLevers, buildWeeklySummary, 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, SHAPE_COMMAND, notAUsageLog, usageShapesOf, plannedCalls, claudeCodeRecords, codexRecords, looksLikeCodexTranscript, geminiCliRecords, looksLikeGeminiCliSession, slimUsageLine, ESTIMATE_ERROR_BAND_PCT, bandFor, foreignTokenizer, measuredForeignError, anthropicCostReport, anthropicUsageRecords, looksLikeOpenaiCost, looksLikeAnthropicCost, batchResultRecords, openaiCostReport, openaiUsageRecords, openrouterActivityRecords, reconcile, heliconeRecords, langsmithRecords, litellmRecords, otelRecords, ownRate, positionAt, positionReport, PRICING_LAST_REVIEWED, reviewedForModels, PROVIDER_REVIEWED, STALE_PRICING_DAYS, profilePrompt, profileToCsv, profileUsage, weekWindows, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, switchAnalysis, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, spendByPeriod, isOffered, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
|
|
12
12
|
import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cache.js';
|
|
13
13
|
import { OPTIONAL_COUNTERS } from './optional-counters.js';
|
|
14
14
|
import { dayOf, formatGap, median, spanDays } from './time.js';
|
|
@@ -22,6 +22,7 @@ import { WAIVER_LOG, appendWaiverUse, readWaiverLog } from './waiver-log.js';
|
|
|
22
22
|
import { DEFAULT_PORT, buildServer, listen } from './serve.js';
|
|
23
23
|
import { DEFAULT_GATEWAY_PORT, UPSTREAMS, buildGateway, listenGateway, } from './gateway-server.js';
|
|
24
24
|
import { WATCH_STATE_VERSION, checkWebhook, postWebhook, readWatchState, writeWatchState, } from './watch-run.js';
|
|
25
|
+
import { notificationFor, sendNotification } from './watch-notify.js';
|
|
25
26
|
import { LOCALE_ENV_VARS, detectLocale, getCliMessages } from './i18n/index.js';
|
|
26
27
|
import { MAX_SUMMARY_CHARS, fitWithin, renderBlameMarkdown, renderCheckMarkdown, renderDiffMarkdown, renderRankMarkdown, renderProfileMarkdown, tierCeilingCaveat, } from './markdown.js';
|
|
27
28
|
import { renderPositionHtml, renderProfileHtml, renderRollupHtml } from './html.js';
|
|
@@ -33,8 +34,12 @@ import { renderProfilePdf } from './pdf.js';
|
|
|
33
34
|
// proportion bar and the heading rule — the 1.75 style module. The guard in
|
|
34
35
|
// style.test.js holds the contract: stripped colour output is byte-identical
|
|
35
36
|
// to plain output, and a pipe stays plain.
|
|
36
|
-
import {
|
|
37
|
+
import { runCrontab } from './git.js';
|
|
38
|
+
import { checkedWeekly } from './weekly.js';
|
|
39
|
+
import { ITEMS as PROACTIVE_ITEMS, BACKUP_SUFFIX, CRONTAB, inspectAll as inspectProactive, run as runProactive, shown as shownPath, systemCrontab, } from './proactive.js';
|
|
40
|
+
import { MAX_COLUMNS, Report, WINDOW, c, cErr, fitPath, sectionHeading, table, wrap } from './style.js';
|
|
37
41
|
const VALUE_FLAGS = new Set([
|
|
42
|
+
'only',
|
|
38
43
|
'id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions',
|
|
39
44
|
'recovery-dir',
|
|
40
45
|
'answers',
|
|
@@ -501,7 +506,7 @@ const COMMAND_FLAGS = {
|
|
|
501
506
|
history: ['store', 'json', 'markdown-out'],
|
|
502
507
|
connect: ['since', 'until', 'payload', 'store', 'json', 'out', 'markdown-out', 'pricing', 'pricing-live', 'dry-run'],
|
|
503
508
|
store: ['prune', 'keep', 'json', 'pricing', 'pricing-live', 'dry-run'],
|
|
504
|
-
watch: ['once', 'interval', 'since', 'payload', 'webhook', 'json', 'pricing', 'pricing-live'],
|
|
509
|
+
watch: ['once', 'interval', 'since', 'payload', 'sessions', 'notify', 'webhook', 'json', 'pricing', 'pricing-live'],
|
|
505
510
|
serve: ['port', 'socket', 'log', 'pricing', 'pricing-live'],
|
|
506
511
|
route: ['prompt-file', 'cases', 'label', 'concurrency', 'json', 'yes', 'pricing', 'pricing-live'],
|
|
507
512
|
eval: ['cases', 'level', 'concurrency', 'export', 'out', 'o', 'model'],
|
|
@@ -525,6 +530,7 @@ const COMMAND_FLAGS = {
|
|
|
525
530
|
'from-openai': ['label', 'label-by-project', 'out', 'o'],
|
|
526
531
|
'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
|
|
527
532
|
bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'since', 'until', 'by'],
|
|
533
|
+
weekly: ['label', 'label-from-project', 'out', 'o', 'until', 'notify', 'pricing', 'pricing-live'],
|
|
528
534
|
'from-helicone': ['out', 'o'],
|
|
529
535
|
'from-langsmith': ['out', 'o'],
|
|
530
536
|
switch: ['to', 'migration-usd', 'cases'],
|
|
@@ -545,6 +551,7 @@ const COMMAND_FLAGS = {
|
|
|
545
551
|
rules: ['measure', 'level', 'json'],
|
|
546
552
|
blame: ['limit', 'model', 'calls', 'output-tokens', 'batch', 'prompt', 'markdown-out'],
|
|
547
553
|
doctor: ['level', 'model', 'calls', 'output-tokens', 'batch', 'disable', 'prompt', 'otlp-out'],
|
|
554
|
+
proactive: ['only', 'dry-run', 'yes', 'json'],
|
|
548
555
|
};
|
|
549
556
|
function rejectUnknownFlags(args, t) {
|
|
550
557
|
const known = COMMAND_FLAGS[args.command];
|
|
@@ -700,6 +707,7 @@ function biggestLever(result, tokensOnly, t) {
|
|
|
700
707
|
return null;
|
|
701
708
|
const ruleSaving = result.savings.monthlySavingsUsd;
|
|
702
709
|
return {
|
|
710
|
+
amount: formatUsd(best.estimatedMonthlyUsd),
|
|
703
711
|
line: t.report.biggestLeverDetail(best.title, formatUsd(best.estimatedMonthlyUsd),
|
|
704
712
|
// The multiple is the point of the line, and it is only honest when there
|
|
705
713
|
// is something to divide by. A prompt the rules could not improve at all
|
|
@@ -734,16 +742,23 @@ measured = null) {
|
|
|
734
742
|
*
|
|
735
743
|
* So the answer to "what should I do about this prompt" goes at the top, and
|
|
736
744
|
* the token count follows as the detail it is.
|
|
745
|
+
*
|
|
746
|
+
* Drawn as every report's headline is (#758): the question as a heading, the
|
|
747
|
+
* answer under it with its figure marked. With no lever worth money, the
|
|
748
|
+
* question is the token count, and the reduction is the marked figure.
|
|
737
749
|
*/
|
|
738
750
|
const best = biggestLever(result, tokensOnly, t);
|
|
751
|
+
const draw = new Report();
|
|
752
|
+
const reduction = `-${result.reductionPct.toFixed(1)}%`;
|
|
739
753
|
if (best) {
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
console.log(` ${c.dim(wrap(best.line, 74, ' '))}`);
|
|
754
|
+
draw.blank().headline(t.report.biggestLever(), best.line, best.amount);
|
|
755
|
+
draw.blank().title(t.report.inputTokens());
|
|
743
756
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
757
|
+
else {
|
|
758
|
+
draw.blank().heading(t.report.inputTokens());
|
|
759
|
+
}
|
|
760
|
+
draw.line(` ${n(result.tokensBefore)} → ${c.green(n(result.tokensAfter))} ${best ? c.bold(reduction) : c.mark(reduction)}${sourceNote}`);
|
|
761
|
+
draw.print();
|
|
747
762
|
// Before the rules, because the rearrangement is the bigger change and the
|
|
748
763
|
// one the reader has to make a judgement about.
|
|
749
764
|
//
|
|
@@ -781,7 +796,7 @@ measured = null) {
|
|
|
781
796
|
}
|
|
782
797
|
}
|
|
783
798
|
if (reorder.moved.length > 0)
|
|
784
|
-
|
|
799
|
+
new Report().note('caution', t.report.reorderReview()).print();
|
|
785
800
|
}
|
|
786
801
|
if (result.rules.length > 0) {
|
|
787
802
|
console.log();
|
|
@@ -803,7 +818,7 @@ measured = null) {
|
|
|
803
818
|
*/
|
|
804
819
|
const promptLanguage = detectTextLanguage(result.original);
|
|
805
820
|
if (promptLanguage !== null && dictionaryStanding(promptLanguage)?.standing === 'unreviewed') {
|
|
806
|
-
|
|
821
|
+
new Report().note('caution', t.report.dictionaryAppliedUnreviewed(t.languages[promptLanguage] ?? promptLanguage)).print();
|
|
807
822
|
}
|
|
808
823
|
for (const rule of result.rules) {
|
|
809
824
|
const tag = rule.level === 'aggressive'
|
|
@@ -828,18 +843,19 @@ measured = null) {
|
|
|
828
843
|
}
|
|
829
844
|
else {
|
|
830
845
|
console.log();
|
|
831
|
-
|
|
846
|
+
const draw = new Report();
|
|
847
|
+
draw.text(t.report.nothingToTrim(), { tone: 'dim' });
|
|
832
848
|
// Which languages the dictionaries actually cover. Only here, because this
|
|
833
849
|
// is the one branch where silence reads as "your prompt is already clean".
|
|
834
|
-
|
|
850
|
+
draw.text(t.report.dictionaryCoverage(languageNames(PHRASE_LANGUAGES, t)), { tone: 'dim' });
|
|
835
851
|
// And which of them nobody here reads. Naming the seven and stopping there
|
|
836
852
|
// reads as seven equal dictionaries; five of them have never been agreed by
|
|
837
853
|
// a speaker of the language, and a reader deciding whether to trust an
|
|
838
854
|
// empty result deserves the difference.
|
|
839
855
|
const unreviewed = languagesWithStanding(PHRASE_LANGUAGES, 'unreviewed');
|
|
840
|
-
if (unreviewed.length > 0)
|
|
841
|
-
|
|
842
|
-
|
|
856
|
+
if (unreviewed.length > 0)
|
|
857
|
+
draw.text(t.report.dictionaryUnreviewed(languageNames(unreviewed, t)), { tone: 'dim' });
|
|
858
|
+
draw.print();
|
|
843
859
|
}
|
|
844
860
|
if (result.llm) {
|
|
845
861
|
console.log();
|
|
@@ -848,7 +864,7 @@ measured = null) {
|
|
|
848
864
|
console.log(` ${c.green(t.report.llmApplied(result.llm.provider, result.llm.model, result.llm.tokensBefore, result.llm.tokensAfter))}`);
|
|
849
865
|
}
|
|
850
866
|
else {
|
|
851
|
-
|
|
867
|
+
new Report().note('caution', t.report.llmRejected(result.llm.rejectedReason ?? '')).print();
|
|
852
868
|
}
|
|
853
869
|
}
|
|
854
870
|
// On a subscription there is no bill to reduce. Everything below this point
|
|
@@ -898,14 +914,14 @@ measured = null) {
|
|
|
898
914
|
: c.dim('·');
|
|
899
915
|
const amount = amountOf(advisory);
|
|
900
916
|
const column = width > 0 ? `${c.green(amount.padStart(width))} ` : '';
|
|
901
|
-
console.log(` ${marker} ${column}${c.bold(advisory.title)}`);
|
|
917
|
+
console.log(` ${marker} ${column}${c.bold(wrap(advisory.title, 78 - gutter.length, gutter))}`);
|
|
902
918
|
console.log(`${gutter}${c.dim(wrap(advisory.detail, 78 - gutter.length, gutter))}`);
|
|
903
919
|
}
|
|
904
920
|
// The "start here" line is printed at the top of the report now, where a
|
|
905
921
|
// reader who stops after four lines still sees it.
|
|
906
922
|
}
|
|
907
923
|
printSuggestions(suggestions, t, n);
|
|
908
|
-
printRest(result, showDiff, t, examplesReview
|
|
924
|
+
printRest(result, showDiff, t, examplesReview);
|
|
909
925
|
/**
|
|
910
926
|
* Where the money actually is, said at the front door.
|
|
911
927
|
*
|
|
@@ -962,7 +978,7 @@ measured = null) {
|
|
|
962
978
|
...result.pricingSource.addedModels,
|
|
963
979
|
];
|
|
964
980
|
if (touched.length > 0) {
|
|
965
|
-
|
|
981
|
+
new Report().note('caution', t.report.pricingOverlaid(touched.join(', '), result.pricingSource.lastReviewed)).print();
|
|
966
982
|
}
|
|
967
983
|
const periodOnly = measured !== null && measured.scaled === null;
|
|
968
984
|
console.log(` ${formatUsd(savings.perMonth.before.totalUsd)} → ` +
|
|
@@ -991,13 +1007,10 @@ function printTokensOnly(result, host, t, n,
|
|
|
991
1007
|
namedScenario = false) {
|
|
992
1008
|
const model = getModel(result.usage.model);
|
|
993
1009
|
const saved = result.tokensBefore - result.tokensAfter;
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
: t.report.tokensOnlyAsked()}`);
|
|
999
|
-
console.log();
|
|
1000
|
-
console.log(` ${c.green(t.report.tokensSaved(n(saved)))}`);
|
|
1010
|
+
const draw = new Report();
|
|
1011
|
+
draw.blank().heading(t.report.tokensOnlyHeading(host.displayName));
|
|
1012
|
+
draw.text(prefersTokenReport(host) ? t.report.tokensOnlyWhy(host.displayName) : t.report.tokensOnlyAsked());
|
|
1013
|
+
draw.blank().text(t.report.tokensSaved(n(saved)), { tone: 'good' });
|
|
1001
1014
|
/**
|
|
1002
1015
|
* Share of the window, which is what a saved token is actually worth here.
|
|
1003
1016
|
*
|
|
@@ -1020,12 +1033,13 @@ namedScenario = false) {
|
|
|
1020
1033
|
*/
|
|
1021
1034
|
const unchanged = before === after;
|
|
1022
1035
|
const negligible = after === '0.0%';
|
|
1023
|
-
|
|
1036
|
+
draw.text(!unchanged
|
|
1024
1037
|
? t.report.windowUse(before, after, model.displayName, n(model.contextWindow))
|
|
1025
1038
|
: negligible
|
|
1026
1039
|
? t.report.windowNegligible(n(result.tokensAfter), model.displayName, n(model.contextWindow))
|
|
1027
|
-
: t.report.windowUnmoved(after, model.displayName, n(model.contextWindow))
|
|
1028
|
-
|
|
1040
|
+
: t.report.windowUnmoved(after, model.displayName, n(model.contextWindow)), { tone: 'dim' });
|
|
1041
|
+
draw.text(namedScenario ? t.report.tokensOnlyAskedFor() : t.report.tokensOnlyCost(), { tone: 'dim' });
|
|
1042
|
+
draw.print();
|
|
1029
1043
|
}
|
|
1030
1044
|
/**
|
|
1031
1045
|
* The proposed rewrites.
|
|
@@ -1075,7 +1089,7 @@ function printSuggestions(suggestions, t, n) {
|
|
|
1075
1089
|
if (!applied)
|
|
1076
1090
|
console.log(` ${c.dim(t.report.suggestHowToApply())}`);
|
|
1077
1091
|
}
|
|
1078
|
-
function printRest(result, showDiff, t, examplesReview
|
|
1092
|
+
function printRest(result, showDiff, t, examplesReview) {
|
|
1079
1093
|
if (examplesReview && examplesReview.groups.length > 0) {
|
|
1080
1094
|
console.log();
|
|
1081
1095
|
console.log(c.bold(t.report.examplesReview()));
|
|
@@ -1099,24 +1113,6 @@ function truncate(text, max) {
|
|
|
1099
1113
|
const clean = text.replace(/\s+/g, ' ').trim();
|
|
1100
1114
|
return clean.length <= max ? clean : `${clean.slice(0, max - 1)}\u2026`;
|
|
1101
1115
|
}
|
|
1102
|
-
/** Wraps a paragraph to a given width. */
|
|
1103
|
-
function wrap(text, width, indent) {
|
|
1104
|
-
const words = text.split(/\s+/);
|
|
1105
|
-
const lines = [];
|
|
1106
|
-
let line = '';
|
|
1107
|
-
for (const word of words) {
|
|
1108
|
-
if (line.length + word.length + 1 > width) {
|
|
1109
|
-
lines.push(line);
|
|
1110
|
-
line = word;
|
|
1111
|
-
}
|
|
1112
|
-
else {
|
|
1113
|
-
line = line ? `${line} ${word}` : word;
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
if (line)
|
|
1117
|
-
lines.push(line);
|
|
1118
|
-
return lines.join(`\n${indent}`);
|
|
1119
|
-
}
|
|
1120
1116
|
// --------------------------------------------------------------------------
|
|
1121
1117
|
// Subcommands
|
|
1122
1118
|
// --------------------------------------------------------------------------
|
|
@@ -2940,17 +2936,90 @@ async function readUsageLogOnly(file, t, billPath = file) {
|
|
|
2940
2936
|
* a bill rather than usage, and pointed at `reconcile`.
|
|
2941
2937
|
*/
|
|
2942
2938
|
async function commandBill(args, pricing, t) {
|
|
2943
|
-
/*
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2939
|
+
/*
|
|
2940
|
+
The statement answers first (#758). What was read, file by file, is a
|
|
2941
|
+
note on the answer, and on a terminal it printed above it: five lines of
|
|
2942
|
+
file names before the total. So when the statement is what stdout gets,
|
|
2943
|
+
those lines are held and written to stderr after it, in the order they
|
|
2944
|
+
came, and on the way out of an error too. A pipe that reads the receipt
|
|
2945
|
+
gets them as it always did, as they happen.
|
|
2946
|
+
*/
|
|
2947
|
+
const statement = !boolFlag(args, 'receipt') && boolFlag(args, 'table', process.stdout.isTTY === true);
|
|
2948
|
+
if (!statement)
|
|
2949
|
+
return billBody(args, pricing, t);
|
|
2950
|
+
const held = [];
|
|
2951
|
+
const write = console.error;
|
|
2952
|
+
console.error = (...line) => {
|
|
2953
|
+
held.push(line);
|
|
2954
|
+
};
|
|
2955
|
+
try {
|
|
2956
|
+
await billBody(args, pricing, t);
|
|
2952
2957
|
}
|
|
2953
|
-
|
|
2958
|
+
finally {
|
|
2959
|
+
console.error = write;
|
|
2960
|
+
// Notes on the answer, not the answer: dimmed on a terminal, below the
|
|
2961
|
+
// statement's own notes, and wrapped to the window when there is one. A
|
|
2962
|
+
// line of its own lines, or a pipe, gets the bytes as they came.
|
|
2963
|
+
for (const line of held) {
|
|
2964
|
+
const [only] = line;
|
|
2965
|
+
if (line.length === 1 && typeof only === 'string') {
|
|
2966
|
+
const text = WINDOW && !only.includes('\n') ? wrap(only, MAX_COLUMNS, '') : only;
|
|
2967
|
+
console.error(text.split('\n').map((part) => cErr.dim(part)).join('\n'));
|
|
2968
|
+
}
|
|
2969
|
+
else
|
|
2970
|
+
console.error(...line);
|
|
2971
|
+
}
|
|
2972
|
+
}
|
|
2973
|
+
}
|
|
2974
|
+
/**
|
|
2975
|
+
* `trazum weekly [<file|dir>...]`: the week in Markdown, for somebody to read
|
|
2976
|
+
* in an issue (#757).
|
|
2977
|
+
*
|
|
2978
|
+
* It reads what `bill` reads, prices the seven days before `--until` and the
|
|
2979
|
+
* seven before those with the same catalogue, and writes the bill, what moved
|
|
2980
|
+
* and the three changes `plan` ranks first. It writes a file or stdout and
|
|
2981
|
+
* nothing else: it holds no GitHub token and makes no call. Where the summary
|
|
2982
|
+
* is posted is the Action's business, and the Action's inputs are the owner's
|
|
2983
|
+
* word for where.
|
|
2984
|
+
*
|
|
2985
|
+
* Every dollar amount and percentage in the finished text is read back against
|
|
2986
|
+
* the two weeks' bills. A summary with one that is in neither is refused and
|
|
2987
|
+
* nothing is written: the number would be read, believed and not re-added.
|
|
2988
|
+
*/
|
|
2989
|
+
async function commandWeekly(args, pricing, t) {
|
|
2990
|
+
const now = Date.now();
|
|
2991
|
+
const until = parseWhen(args, 'until', true, t, now);
|
|
2992
|
+
const windows = weekWindows(until.ms ?? now);
|
|
2993
|
+
const { lines } = await gatherUsageLines(args, t);
|
|
2994
|
+
const text = lines.join('\n');
|
|
2995
|
+
const profileWeek = (week) => profileUsage(text, { catalogue: pricing, sinceMs: week.sinceMs, untilMs: week.untilMs });
|
|
2996
|
+
const current = profileWeek(windows.current);
|
|
2997
|
+
const previous = profileWeek(windows.previous);
|
|
2998
|
+
const plan = buildPlan(current, billLevers(current, { catalogue: pricing }), pricing.lastReviewed);
|
|
2999
|
+
const { markdown, headline } = checkedWeekly(buildWeeklySummary(current, previous, plan, windows), billFigures(current, previous, plan), t);
|
|
3000
|
+
const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
|
|
3001
|
+
if (out !== undefined) {
|
|
3002
|
+
await writeFile(out, markdown, 'utf8');
|
|
3003
|
+
console.error(t.weekly.wrote(out));
|
|
3004
|
+
}
|
|
3005
|
+
else {
|
|
3006
|
+
process.stdout.write(markdown);
|
|
3007
|
+
}
|
|
3008
|
+
/*
|
|
3009
|
+
The person at the machine, once the summary is safely written: the same
|
|
3010
|
+
notifier `watch --notify` uses, carrying one sentence of figures that went
|
|
3011
|
+
through the same check as the file. Off unless asked for; where the
|
|
3012
|
+
platform has no notifier it is said and the file stands.
|
|
3013
|
+
*/
|
|
3014
|
+
if (boolFlag(args, 'notify')) {
|
|
3015
|
+
const sent = sendNotification(notificationFor([headline]));
|
|
3016
|
+
if (sent.outcome === 'unavailable')
|
|
3017
|
+
console.error(c.yellow(t.weekly.notifyUnavailable(sent.command)));
|
|
3018
|
+
if (sent.outcome === 'failed')
|
|
3019
|
+
console.error(c.yellow(t.weekly.notifyFailed(sent.command, sent.error)));
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
async function gatherUsageLines(args, t) {
|
|
2954
3023
|
/*
|
|
2955
3024
|
No path is the most common first run, and it used to be a refusal: the
|
|
2956
3025
|
person had to know where Claude Code keeps its sessions before the one
|
|
@@ -3224,6 +3293,21 @@ async function commandBill(args, pricing, t) {
|
|
|
3224
3293
|
console.error(t.fromGeminiCli.remainder(geminiRemainder));
|
|
3225
3294
|
if (sources === 0)
|
|
3226
3295
|
throw new Error(t.bill.nothingRead());
|
|
3296
|
+
return { lines, sources, fileCount: files.length, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, labelledByProject };
|
|
3297
|
+
}
|
|
3298
|
+
async function billBody(args, pricing, t) {
|
|
3299
|
+
/* Refused before any file is read: a bad shape found after the receipt
|
|
3300
|
+
printed would end a run that looked finished with an error. */
|
|
3301
|
+
const csvShape = csvShapeOf(args, t);
|
|
3302
|
+
/* "What did this month cost" is the question a Claude Code folder of a
|
|
3303
|
+
year's sessions answers worst without a period. */
|
|
3304
|
+
const period = billingPeriod(args, t);
|
|
3305
|
+
const byFlag = stringFlag(args, 'by');
|
|
3306
|
+
if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
|
|
3307
|
+
throw new Error(t.bill.badBy(byFlag));
|
|
3308
|
+
}
|
|
3309
|
+
const by = byFlag;
|
|
3310
|
+
const { lines, sources, fileCount, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, labelledByProject } = await gatherUsageLines(args, t);
|
|
3227
3311
|
const text = lines.join('\n');
|
|
3228
3312
|
const report = profileUsage(text, {
|
|
3229
3313
|
catalogue: pricing,
|
|
@@ -3255,7 +3339,7 @@ async function commandBill(args, pricing, t) {
|
|
|
3255
3339
|
else if (!statement) {
|
|
3256
3340
|
console.log(json);
|
|
3257
3341
|
}
|
|
3258
|
-
console.error(t.bill.sources(sources,
|
|
3342
|
+
console.error(t.bill.sources(sources, fileCount));
|
|
3259
3343
|
printReceiptSummary(document, t);
|
|
3260
3344
|
const agentSessions = claudeCodeFiles + codexFiles + geminiCliFiles > 0;
|
|
3261
3345
|
/*
|
|
@@ -3436,13 +3520,14 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false,
|
|
|
3436
3520
|
const pct = (share) => `${(share * 100).toFixed(1)}%`;
|
|
3437
3521
|
const total = report.total.totalUsd;
|
|
3438
3522
|
const LIMIT = 12;
|
|
3523
|
+
const shareCells = (usd) => {
|
|
3524
|
+
const share = total > 0 ? usd / total : 0;
|
|
3525
|
+
return [{ bar: share }, pct(share)];
|
|
3526
|
+
};
|
|
3439
3527
|
const rowsOf = (entries) => {
|
|
3440
|
-
const shown = entries.slice(0, LIMIT).map(({ name, calls, usd }) =>
|
|
3441
|
-
const share = total > 0 ? usd / total : 0;
|
|
3442
|
-
return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
|
|
3443
|
-
});
|
|
3528
|
+
const shown = entries.slice(0, LIMIT).map(({ name, calls, usd }) => [name, n(calls), formatUsd(usd), ...shareCells(usd)]);
|
|
3444
3529
|
if (entries.length > LIMIT)
|
|
3445
|
-
shown.push([c.dim(t.bill.moreRows(entries.length - LIMIT)), '', '', '']);
|
|
3530
|
+
shown.push([c.dim(t.bill.moreRows(entries.length - LIMIT)), '', '', '', '']);
|
|
3446
3531
|
return shown;
|
|
3447
3532
|
};
|
|
3448
3533
|
const columns = (first) => [
|
|
@@ -3450,48 +3535,32 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false,
|
|
|
3450
3535
|
{ header: t.bill.colCalls(), align: 'right' },
|
|
3451
3536
|
{ header: 'USD', align: 'right' },
|
|
3452
3537
|
{ header: t.bill.colShare(), align: 'left' },
|
|
3538
|
+
{ header: '', align: 'right' },
|
|
3453
3539
|
];
|
|
3454
|
-
console.log();
|
|
3455
|
-
console.log(sectionHeading(t.bill.statementHeading()));
|
|
3456
|
-
console.log(` ${c.bold(t.bill.statementTotal(formatUsd(total), report.total.calls))}`);
|
|
3457
|
-
if (report.span !== null) {
|
|
3458
|
-
const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
|
|
3459
|
-
console.log(c.dim(` ${wrap(span, 74, ' ')}`));
|
|
3460
|
-
}
|
|
3461
|
-
// The period asked for, as typed: the span above is when the calls in it fell.
|
|
3462
|
-
if (window !== undefined)
|
|
3463
|
-
console.log(c.dim(` ${wrap(t.profile.windowLine(window.since, window.until), 74, ' ')}`));
|
|
3464
3540
|
/*
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3541
|
+
The question and its answer first: the total, marked. Then the
|
|
3542
|
+
breakdown, by agent, project, model and period. Then what qualifies the
|
|
3543
|
+
total, and what to do next. A reader who stops after the total has it.
|
|
3468
3544
|
*/
|
|
3469
|
-
|
|
3470
|
-
|
|
3545
|
+
const draw = new Report();
|
|
3546
|
+
const totalUsd = formatUsd(total);
|
|
3547
|
+
draw.blank().headline(t.bill.statementHeading(), t.bill.statementTotal(totalUsd, report.total.calls), totalUsd);
|
|
3471
3548
|
// Which agent spent what, first: it is the split a person running more than one asks for.
|
|
3472
|
-
if (byAgent.length > 1)
|
|
3473
|
-
|
|
3474
|
-
for (const line of table(columns(t.bill.colAgent()), rowsOf(byAgent)))
|
|
3475
|
-
console.log(line);
|
|
3476
|
-
}
|
|
3549
|
+
if (byAgent.length > 1)
|
|
3550
|
+
draw.blank().table(columns(t.bill.colAgent()), rowsOf(byAgent));
|
|
3477
3551
|
const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
|
|
3478
3552
|
if (labelled.length > 0) {
|
|
3479
|
-
console.log();
|
|
3480
3553
|
const entries = report.byLabel.map((row) => ({
|
|
3481
3554
|
name: row.label === UNLABELLED ? t.profile.unlabelled() : row.label,
|
|
3482
3555
|
calls: row.breakdown.calls,
|
|
3483
3556
|
usd: row.breakdown.totalUsd,
|
|
3484
3557
|
}));
|
|
3485
|
-
|
|
3486
|
-
console.log(line);
|
|
3487
|
-
}
|
|
3558
|
+
draw.blank().table(columns(byProject ? t.bill.colProject() : t.bill.colWorkload()), rowsOf(entries));
|
|
3488
3559
|
}
|
|
3489
3560
|
const priced = report.byModel.filter((row) => !report.unpricedModels.includes(row.model));
|
|
3490
3561
|
if (priced.length > 0) {
|
|
3491
|
-
console.log();
|
|
3492
3562
|
const entries = priced.map((row) => ({ name: row.model, calls: row.breakdown.calls, usd: row.breakdown.totalUsd }));
|
|
3493
|
-
|
|
3494
|
-
console.log(line);
|
|
3563
|
+
draw.blank().table(columns(t.bill.colModel()), rowsOf(entries));
|
|
3495
3564
|
}
|
|
3496
3565
|
/*
|
|
3497
3566
|
A year of Claude Code sessions billed in one total says what it all cost
|
|
@@ -3508,40 +3577,49 @@ function printBillStatement(report, byProject, t, window, apiEquivalent = false,
|
|
|
3508
3577
|
const { periods, undated } = spendByPeriod(report, unit);
|
|
3509
3578
|
if (periods.length >= (by === undefined ? 2 : 1)) {
|
|
3510
3579
|
const keep = unit === 'day' ? 31 : LIMIT;
|
|
3511
|
-
const shown = periods.slice(-keep).map(({ period, calls, usd }) =>
|
|
3512
|
-
const share = total > 0 ? usd / total : 0;
|
|
3513
|
-
return [period, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
|
|
3514
|
-
});
|
|
3580
|
+
const shown = periods.slice(-keep).map(({ period, calls, usd }) => [period, n(calls), formatUsd(usd), ...shareCells(usd)]);
|
|
3515
3581
|
if (periods.length > keep) {
|
|
3516
3582
|
const earlier = periods.length - keep;
|
|
3517
|
-
shown.unshift([c.dim(unit === 'month' ? t.bill.earlierMonths(earlier) : t.bill.earlierPeriods(earlier, unit)), '', '', '']);
|
|
3583
|
+
shown.unshift([c.dim(unit === 'month' ? t.bill.earlierMonths(earlier) : t.bill.earlierPeriods(earlier, unit)), '', '', '', '']);
|
|
3518
3584
|
}
|
|
3519
|
-
|
|
3520
|
-
for (const line of table(columns(unit === 'month' ? t.bill.colMonth() : t.bill.colPeriod(unit)), shown))
|
|
3521
|
-
console.log(line);
|
|
3585
|
+
draw.blank().table(columns(unit === 'month' ? t.bill.colMonth() : t.bill.colPeriod(unit)), shown);
|
|
3522
3586
|
if (undated.calls > 0) {
|
|
3523
3587
|
const sentence = unit === 'month'
|
|
3524
3588
|
? t.bill.monthsUndated(undated.calls, formatUsd(undated.usd))
|
|
3525
3589
|
: t.bill.periodsUndated(undated.calls, formatUsd(undated.usd), unit);
|
|
3526
|
-
|
|
3590
|
+
draw.text(sentence, { tone: 'dim' });
|
|
3527
3591
|
}
|
|
3528
3592
|
const newest = periods[periods.length - 1];
|
|
3529
|
-
|
|
3593
|
+
draw.text(unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit), { tone: 'dim' });
|
|
3530
3594
|
}
|
|
3531
|
-
|
|
3595
|
+
// What qualifies the total: when the calls fell, and what it is not.
|
|
3596
|
+
draw.blank();
|
|
3597
|
+
if (report.span !== null) {
|
|
3598
|
+
draw.text(t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs)), { tone: 'dim' });
|
|
3599
|
+
}
|
|
3600
|
+
// The period asked for, as typed: the span above is when the calls in it fell.
|
|
3601
|
+
if (window !== undefined)
|
|
3602
|
+
draw.text(t.profile.windowLine(window.since, window.until), { tone: 'dim' });
|
|
3603
|
+
/*
|
|
3604
|
+
"Your bill" over Claude Code transcripts is the API's list price for the
|
|
3605
|
+
work. On a Pro or Max plan the plan is what was paid, and a statement that
|
|
3606
|
+
did not say so would hand somebody a figure they never owed.
|
|
3607
|
+
*/
|
|
3608
|
+
if (apiEquivalent)
|
|
3609
|
+
draw.note('caution', t.bill.apiEquivalent());
|
|
3532
3610
|
if (report.unpricedModels.length > 0) {
|
|
3533
|
-
|
|
3611
|
+
draw.note('caution', t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls));
|
|
3534
3612
|
}
|
|
3535
3613
|
const ceiling = tierCeilingLine(report, t);
|
|
3536
3614
|
if (ceiling !== null)
|
|
3537
|
-
|
|
3615
|
+
draw.note('caution', ceiling);
|
|
3538
3616
|
if (report.skippedLines.length > 0)
|
|
3539
|
-
|
|
3617
|
+
draw.note('caution', t.bill.statementUnread(report.skippedLines.length));
|
|
3540
3618
|
if (report.timeWindow !== null && report.timeWindow.undatedExcluded > 0) {
|
|
3541
|
-
|
|
3619
|
+
draw.note('caution', t.receipt.undatedExcluded(report.timeWindow.undatedExcluded));
|
|
3542
3620
|
}
|
|
3543
|
-
|
|
3544
|
-
|
|
3621
|
+
draw.blank().text(t.bill.statementNext(), { tone: 'dim' }).blank();
|
|
3622
|
+
draw.print();
|
|
3545
3623
|
}
|
|
3546
3624
|
/**
|
|
3547
3625
|
* The bill as a document for somebody else: PDF, HTML, Markdown, CSV.
|
|
@@ -3735,7 +3813,6 @@ function commandOwnrate(args, t) {
|
|
|
3735
3813
|
outputPerMTok: Number(usdPerMTok.toFixed(4)),
|
|
3736
3814
|
contextWindow: 32768,
|
|
3737
3815
|
cacheMinTokens: null,
|
|
3738
|
-
tier: 'unknown',
|
|
3739
3816
|
capability: 'unknown',
|
|
3740
3817
|
},
|
|
3741
3818
|
},
|
|
@@ -5617,7 +5694,7 @@ async function commandOwners(args, config, pricing, t) {
|
|
|
5617
5694
|
* saved $X" is a measurement; "you will save $X" is a claim about the future
|
|
5618
5695
|
* this product has refused at every scale since 1.27.
|
|
5619
5696
|
*/
|
|
5620
|
-
async function commandCommitment(args,
|
|
5697
|
+
async function commandCommitment(args, pricing, t) {
|
|
5621
5698
|
const path = args.positional[0];
|
|
5622
5699
|
if (path === undefined)
|
|
5623
5700
|
throw new Error(t.errors.missingInputFile());
|
|
@@ -6153,7 +6230,7 @@ async function commandOptimize(args, config, pricing, t, locale) {
|
|
|
6153
6230
|
const saving = row.periodOnly
|
|
6154
6231
|
? t.report.allLabelsRowPeriod(formatUsd(row.savingUsd))
|
|
6155
6232
|
: t.report.allLabelsRow(formatUsd(row.savingUsd));
|
|
6156
|
-
console.log(` ${row.savingUsd > 0 ? c.
|
|
6233
|
+
console.log(` ${row.savingUsd > 0 ? c.accent('→') : c.dim('·')} ${c.bold(row.label)} ${saving} ${c.dim(`${row.path} · ${n(row.tokensBefore)} → ${n(row.tokensAfter)} tokens · ${formatUsd(row.spentUsd)} measured`)}`);
|
|
6157
6234
|
}
|
|
6158
6235
|
if (rows.length > 0) {
|
|
6159
6236
|
console.log(` ${c.dim(wrap(t.report.allLabelsFooter(), 74, ' '))}`);
|
|
@@ -6583,12 +6660,15 @@ async function commandCheck(args, config, pricing, t, locale) {
|
|
|
6583
6660
|
console.log(`${c.green(t.check.okLabel())} ${t.check.ok(n(verdict.tokens), n(maxTokens))}`);
|
|
6584
6661
|
}
|
|
6585
6662
|
else {
|
|
6586
|
-
|
|
6663
|
+
// The verdict first, in a word and its colour; then what would make it fit.
|
|
6664
|
+
const draw = new Report();
|
|
6665
|
+
draw.text(t.check.failed(n(verdict.tokens), n(maxTokens)), { first: `${c.red(t.check.failedLabel())} `, indent: '' });
|
|
6587
6666
|
if (verdict.optimizedTokens !== null) {
|
|
6588
|
-
|
|
6667
|
+
draw.text(verdict.optimizedTokens <= maxTokens
|
|
6589
6668
|
? t.check.wouldFit(level, n(verdict.optimizedTokens))
|
|
6590
|
-
: t.check.stillTooBig(n(verdict.optimizedTokens)));
|
|
6669
|
+
: t.check.stillTooBig(n(verdict.optimizedTokens)), { indent: '' });
|
|
6591
6670
|
}
|
|
6671
|
+
draw.print((line) => console.error(line));
|
|
6592
6672
|
}
|
|
6593
6673
|
if (!ok)
|
|
6594
6674
|
process.exitCode = 1;
|
|
@@ -6866,6 +6946,200 @@ async function commandServe(args, config, pricing, t) {
|
|
|
6866
6946
|
console.log(` ${c.yellow(wrap(t.serve.limitsUnpriced(limitsIndex.unpriced), 74, ' '))}`);
|
|
6867
6947
|
}
|
|
6868
6948
|
}
|
|
6949
|
+
/**
|
|
6950
|
+
* `trazum proactive`: the three places Trazum can speak first, turned on and
|
|
6951
|
+
* off from one command. The logic and the one function that writes live in
|
|
6952
|
+
* `proactive.ts`; this reads the machine once, asks, and says what happened.
|
|
6953
|
+
*
|
|
6954
|
+
* **A separate command and not a mode of `init`**, because the two edit
|
|
6955
|
+
* different things for different reasons. `init` proposes a config for one
|
|
6956
|
+
* repository and has `--dry-run` and `--yes` meaning "the config"; this edits
|
|
6957
|
+
* files in a home directory and the project's MCP config. Two jobs under one
|
|
6958
|
+
* name would have made `init --dry-run` ambiguous about which it printed.
|
|
6959
|
+
*/
|
|
6960
|
+
async function commandProactive(args, pricing, t) {
|
|
6961
|
+
const action = args.positional[0] ?? 'status';
|
|
6962
|
+
if (action !== 'status' && action !== 'on' && action !== 'off')
|
|
6963
|
+
throw new Error(t.proactive.unknownAction(action));
|
|
6964
|
+
let items = PROACTIVE_ITEMS;
|
|
6965
|
+
const only = stringFlag(args, 'only');
|
|
6966
|
+
if (only !== undefined) {
|
|
6967
|
+
const named = only.split(',').map((name) => name.trim()).filter(Boolean);
|
|
6968
|
+
const unknown = named.find((name) => !PROACTIVE_ITEMS.includes(name));
|
|
6969
|
+
if (unknown !== undefined || named.length === 0) {
|
|
6970
|
+
throw new Error(t.proactive.unknownItem(unknown ?? '', PROACTIVE_ITEMS.join(', ')));
|
|
6971
|
+
}
|
|
6972
|
+
items = PROACTIVE_ITEMS.filter((item) => named.includes(item));
|
|
6973
|
+
}
|
|
6974
|
+
/*
|
|
6975
|
+
The home directory is read from the environment here and nowhere else, once,
|
|
6976
|
+
and everything in proactive.ts takes it as a parameter. HOME first, as the
|
|
6977
|
+
shell does, then USERPROFILE for Windows, then what the operating system says.
|
|
6978
|
+
*/
|
|
6979
|
+
const home = process.env.HOME || process.env.USERPROFILE || homedir();
|
|
6980
|
+
const entry = (() => {
|
|
6981
|
+
try {
|
|
6982
|
+
return realpathSync(process.argv[1] ?? '');
|
|
6983
|
+
}
|
|
6984
|
+
catch {
|
|
6985
|
+
return resolvePath(process.argv[1] ?? '');
|
|
6986
|
+
}
|
|
6987
|
+
})();
|
|
6988
|
+
const ctx = {
|
|
6989
|
+
home,
|
|
6990
|
+
cwd: process.cwd(),
|
|
6991
|
+
platform: process.platform,
|
|
6992
|
+
execPath: process.execPath,
|
|
6993
|
+
entry,
|
|
6994
|
+
trazumBin: process.env.TRAZUM_BIN,
|
|
6995
|
+
crontab: systemCrontab(runCrontab),
|
|
6996
|
+
script: () => readFile(fileURLToPath(new URL('../assets/trazum-statusline.sh', import.meta.url)), 'utf8'),
|
|
6997
|
+
catalogue: pricing,
|
|
6998
|
+
};
|
|
6999
|
+
const asJson = boolFlag(args, 'json');
|
|
7000
|
+
const terminal = process.stdin.isTTY === true;
|
|
7001
|
+
const yes = boolFlag(args, 'yes');
|
|
7002
|
+
const dryRun = action === 'status' || boolFlag(args, 'dry-run') || (!yes && !terminal);
|
|
7003
|
+
const forcedDryRun = action !== 'status' && !boolFlag(args, 'dry-run') && !yes && !terminal;
|
|
7004
|
+
const name = (item) => t.proactive.item[item];
|
|
7005
|
+
const reason = (finding) => t.proactive.reason[finding.code](finding.params);
|
|
7006
|
+
const place = (target) => (target === CRONTAB ? t.proactive.crontab() : shownPath(ctx, target));
|
|
7007
|
+
/** One file and the lines that go and that come, as they would be read in it. */
|
|
7008
|
+
const printChange = (change, say = console.log) => {
|
|
7009
|
+
say(` ${place(change.target)}`);
|
|
7010
|
+
for (const line of change.removed)
|
|
7011
|
+
say(` ${c.red(`- ${line}`)}`);
|
|
7012
|
+
for (const line of change.added)
|
|
7013
|
+
say(` ${c.green(`+ ${line}`)}`);
|
|
7014
|
+
};
|
|
7015
|
+
const prompt = { reader: null };
|
|
7016
|
+
/** The items whose lines were printed before their question, so they are not printed twice. */
|
|
7017
|
+
const shownBeforeAsking = new Set();
|
|
7018
|
+
const decide = async (item, changes) => {
|
|
7019
|
+
if (yes)
|
|
7020
|
+
return true;
|
|
7021
|
+
/*
|
|
7022
|
+
Every file and every line, and then the question. A yes to "write the
|
|
7023
|
+
status line?" with the lines printed afterwards is a yes to something
|
|
7024
|
+
nobody had read: the first version asked first, and its changelog entry
|
|
7025
|
+
said the opposite.
|
|
7026
|
+
*/
|
|
7027
|
+
// With --json the standard output is the document, so the lines go beside the question.
|
|
7028
|
+
const say = asJson ? console.error : console.log;
|
|
7029
|
+
say('');
|
|
7030
|
+
say(` ${c.bold((action === 'off' ? t.proactive.wouldTurnOff : t.proactive.wouldTurnOn)(name(item)))}`);
|
|
7031
|
+
for (const change of changes)
|
|
7032
|
+
printChange(change, say);
|
|
7033
|
+
shownBeforeAsking.add(item);
|
|
7034
|
+
prompt.reader ??= createInterface({ input: process.stdin, output: process.stderr });
|
|
7035
|
+
const files = [...new Set(changes.map((change) => place(change.target)))].join(', ');
|
|
7036
|
+
const answer = await prompt.reader.question(action === 'off' ? t.proactive.askOff(name(item), files) : t.proactive.askOn(name(item), files));
|
|
7037
|
+
return /^(y|yes|s|si|sí)$/i.test(answer.trim());
|
|
7038
|
+
};
|
|
7039
|
+
let outcome;
|
|
7040
|
+
try {
|
|
7041
|
+
if (action === 'status') {
|
|
7042
|
+
const inspected = await inspectProactive(ctx);
|
|
7043
|
+
const statuses = PROACTIVE_ITEMS.map((item) => inspected.items[item].status);
|
|
7044
|
+
outcome = { before: statuses, results: [], after: statuses };
|
|
7045
|
+
}
|
|
7046
|
+
else {
|
|
7047
|
+
outcome = await runProactive(ctx, { action, items, dryRun, decide });
|
|
7048
|
+
}
|
|
7049
|
+
}
|
|
7050
|
+
finally {
|
|
7051
|
+
prompt.reader?.close();
|
|
7052
|
+
}
|
|
7053
|
+
const shownStatuses = (list) => list.filter((status) => items.includes(status.item));
|
|
7054
|
+
if (asJson) {
|
|
7055
|
+
const document = {
|
|
7056
|
+
schemaVersion: 1,
|
|
7057
|
+
action,
|
|
7058
|
+
dryRun,
|
|
7059
|
+
home: ctx.home,
|
|
7060
|
+
project: ctx.cwd,
|
|
7061
|
+
items: shownStatuses(outcome.after).map((status) => ({
|
|
7062
|
+
item: status.item,
|
|
7063
|
+
state: status.verdict,
|
|
7064
|
+
reason: status.code,
|
|
7065
|
+
detail: reason(status),
|
|
7066
|
+
files: status.files,
|
|
7067
|
+
notes: status.notes.map((note) => ({ reason: note.code, detail: reason(note) })),
|
|
7068
|
+
})),
|
|
7069
|
+
changes: outcome.results.map((result) => ({
|
|
7070
|
+
item: result.item,
|
|
7071
|
+
outcome: result.outcome,
|
|
7072
|
+
error: result.error === null ? null : { reason: result.error.code, detail: reason(result.error) },
|
|
7073
|
+
files: result.changes.map((change) => ({ file: change.target, added: change.added, removed: change.removed })),
|
|
7074
|
+
})),
|
|
7075
|
+
};
|
|
7076
|
+
console.log(JSON.stringify(document, null, 2));
|
|
7077
|
+
if (outcome.results.some((result) => result.outcome === 'failed'))
|
|
7078
|
+
process.exitCode = 1;
|
|
7079
|
+
return;
|
|
7080
|
+
}
|
|
7081
|
+
const verdictPaint = (status, text) => status.verdict === 'on' ? c.green(text) : status.verdict === 'off' ? text : status.verdict === 'could-not-tell' ? c.red(text) : c.yellow(text);
|
|
7082
|
+
/*
|
|
7083
|
+
The question is the heading and the rows are its answer, one item a line:
|
|
7084
|
+
the name, its state in a word, and why (#758). The state's colour repeats
|
|
7085
|
+
the word; the reason hangs under itself, inside the window.
|
|
7086
|
+
*/
|
|
7087
|
+
const draw = new Report();
|
|
7088
|
+
const block = (list) => {
|
|
7089
|
+
const width = Math.max(...items.map((item) => name(item).length));
|
|
7090
|
+
const verdictWidth = Math.max(...Object.values(t.proactive.verdict).map((word) => word.length));
|
|
7091
|
+
const hang = ' '.repeat(width + verdictWidth + 6);
|
|
7092
|
+
// The module's `wrap`: the layout a pipe always had, and inside the window when there is one.
|
|
7093
|
+
const said = (finding) => c.dim(wrap(reason(finding), 76 - width - verdictWidth, hang).trimStart());
|
|
7094
|
+
for (const status of shownStatuses(list)) {
|
|
7095
|
+
draw.line(` ${name(status.item).padEnd(width)} ${verdictPaint(status, t.proactive.verdict[status.verdict].padEnd(verdictWidth))} ${said(status)}`);
|
|
7096
|
+
for (const note of status.notes)
|
|
7097
|
+
draw.line(` ${' '.repeat(width + verdictWidth + 4)}${said(note)}`);
|
|
7098
|
+
}
|
|
7099
|
+
};
|
|
7100
|
+
draw.blank().heading(t.proactive.heading());
|
|
7101
|
+
block(outcome.before);
|
|
7102
|
+
if (action === 'status') {
|
|
7103
|
+
draw.print();
|
|
7104
|
+
return;
|
|
7105
|
+
}
|
|
7106
|
+
let anyChange = false;
|
|
7107
|
+
for (const result of outcome.results) {
|
|
7108
|
+
if (result.outcome === 'nothing') {
|
|
7109
|
+
draw.blank().text(t.proactive.nothingToChange(name(result.item)), { tone: 'dim' });
|
|
7110
|
+
continue;
|
|
7111
|
+
}
|
|
7112
|
+
anyChange = true;
|
|
7113
|
+
const done = result.outcome === 'written';
|
|
7114
|
+
const header = action === 'off'
|
|
7115
|
+
? (done ? t.proactive.didTurnOff : t.proactive.wouldTurnOff)(name(result.item))
|
|
7116
|
+
: (done ? t.proactive.didTurnOn : t.proactive.wouldTurnOn)(name(result.item));
|
|
7117
|
+
draw.blank().text(header, { tone: 'bold' });
|
|
7118
|
+
// Asked about in a terminal, an item's lines are already above its question.
|
|
7119
|
+
// The lines a file gains or loses are its content: drawn as they are.
|
|
7120
|
+
if (!shownBeforeAsking.has(result.item))
|
|
7121
|
+
for (const change of result.changes)
|
|
7122
|
+
printChange(change, (line) => draw.line(line));
|
|
7123
|
+
if (result.outcome === 'declined')
|
|
7124
|
+
draw.text(t.proactive.declined(name(result.item)));
|
|
7125
|
+
if (result.outcome === 'failed' && result.error !== null) {
|
|
7126
|
+
draw.note('error', t.proactive.failed(name(result.item), reason(result.error)), { tone: 'error' });
|
|
7127
|
+
}
|
|
7128
|
+
}
|
|
7129
|
+
// The module's `wrap` at the widths these always had, so a pipe gets the same lines.
|
|
7130
|
+
if (action === 'on' && anyChange)
|
|
7131
|
+
draw.blank().line(` ${c.dim(wrap(t.proactive.backupNote(BACKUP_SUFFIX), 74, ' ').trimStart())}`);
|
|
7132
|
+
if (dryRun && anyChange) {
|
|
7133
|
+
draw.blank().line(` ${wrap(forcedDryRun ? t.proactive.dryRunNoTerminal() : t.proactive.dryRunAsked(), 74, ' ').trimStart()}`);
|
|
7134
|
+
}
|
|
7135
|
+
if (outcome.results.some((result) => result.outcome === 'written')) {
|
|
7136
|
+
draw.blank();
|
|
7137
|
+
block(outcome.after);
|
|
7138
|
+
}
|
|
7139
|
+
draw.print();
|
|
7140
|
+
if (outcome.results.some((result) => result.outcome === 'failed'))
|
|
7141
|
+
process.exitCode = 1;
|
|
7142
|
+
}
|
|
6869
7143
|
/**
|
|
6870
7144
|
* `trazum watch` — the afternoon it happened, said that afternoon.
|
|
6871
7145
|
*
|
|
@@ -6908,6 +7182,16 @@ async function commandWatch(args, config, pricing, t) {
|
|
|
6908
7182
|
throw new Error(t.watch.badWebhook(checked.reason));
|
|
6909
7183
|
webhook = checked.url;
|
|
6910
7184
|
}
|
|
7185
|
+
/*
|
|
7186
|
+
One source to a cycle. `--sessions` is the sessions `bill` reads with no
|
|
7187
|
+
path, so the command that needs no setup can alert; refused beside
|
|
7188
|
+
`--payload` before anything is read, because a cycle that quietly picked
|
|
7189
|
+
one of two would be watching the other's silence.
|
|
7190
|
+
*/
|
|
7191
|
+
const sessions = boolFlag(args, 'sessions');
|
|
7192
|
+
if (sessions && stringFlag(args, 'payload') !== undefined)
|
|
7193
|
+
throw new Error(t.watch.sessionsAndPayload());
|
|
7194
|
+
const notify = boolFlag(args, 'notify');
|
|
6911
7195
|
const intervalRaw = stringFlag(args, 'interval');
|
|
6912
7196
|
const once = boolFlag(args, 'once') || intervalRaw === undefined;
|
|
6913
7197
|
let intervalMs = 0;
|
|
@@ -6922,38 +7206,60 @@ async function commandWatch(args, config, pricing, t) {
|
|
|
6922
7206
|
}
|
|
6923
7207
|
}
|
|
6924
7208
|
const cycle = async () => {
|
|
6925
|
-
|
|
7209
|
+
/*
|
|
7210
|
+
What was reported about one source says nothing about the other's
|
|
7211
|
+
figures: a crossing kept quiet because the store had already said it
|
|
7212
|
+
must not keep quiet one that only the sessions show. A state the other
|
|
7213
|
+
source wrote is a first cycle for this one, and writing over it below is
|
|
7214
|
+
what keeps the two from reading each other's record.
|
|
7215
|
+
*/
|
|
7216
|
+
const prior = await readWatchState(root);
|
|
7217
|
+
const state = prior !== null && (prior.source === 'sessions') !== sessions ? null : prior;
|
|
6926
7218
|
const nowMs = Date.now();
|
|
6927
7219
|
/**
|
|
6928
|
-
* Where the measurements come from:
|
|
6929
|
-
*
|
|
6930
|
-
*
|
|
6931
|
-
*
|
|
7220
|
+
* Where the measurements come from: the sessions on this machine when
|
|
7221
|
+
* `--sessions` is given, a saved payload when one is named (which is how
|
|
7222
|
+
* this is tested and how an air-gapped run works), and the store
|
|
7223
|
+
* otherwise. A cycle that found nothing to measure says so — a watcher
|
|
7224
|
+
* over nothing is a green light nobody earned.
|
|
6932
7225
|
*/
|
|
6933
7226
|
const payloadPath = stringFlag(args, 'payload');
|
|
6934
|
-
let
|
|
6935
|
-
|
|
6936
|
-
|
|
7227
|
+
let report;
|
|
7228
|
+
let cacheDeltaUsd;
|
|
7229
|
+
let sessionFolders = [];
|
|
7230
|
+
if (sessions) {
|
|
7231
|
+
const measured = await watchedSessions(pricing, t);
|
|
7232
|
+
report = measured.report;
|
|
7233
|
+
cacheDeltaUsd = measured.cacheDeltaUsd;
|
|
7234
|
+
sessionFolders = measured.folders;
|
|
6937
7235
|
}
|
|
6938
7236
|
else {
|
|
6939
|
-
|
|
6940
|
-
if (
|
|
6941
|
-
|
|
6942
|
-
|
|
6943
|
-
|
|
6944
|
-
|
|
6945
|
-
|
|
6946
|
-
|
|
6947
|
-
|
|
6948
|
-
|
|
6949
|
-
|
|
7237
|
+
let pull;
|
|
7238
|
+
if (payloadPath !== undefined) {
|
|
7239
|
+
pull = normalizeAnthropicUsage(JSON.parse(await readFile(payloadPath, 'utf8')));
|
|
7240
|
+
}
|
|
7241
|
+
else {
|
|
7242
|
+
const { resolved } = await readStore(root);
|
|
7243
|
+
if (resolved.records.length === 0)
|
|
7244
|
+
throw new Error(t.watch.nothingToWatch(STORE_DIR));
|
|
7245
|
+
pull = {
|
|
7246
|
+
provider: 'store',
|
|
7247
|
+
granularity: 'bucketed',
|
|
7248
|
+
buckets: bucketsFromRecords(resolved.records),
|
|
7249
|
+
window: null,
|
|
7250
|
+
gaps: [],
|
|
7251
|
+
unavailable: [],
|
|
7252
|
+
};
|
|
7253
|
+
}
|
|
7254
|
+
const bucketed = bucketedProfile(pull, { catalogue: pricing });
|
|
7255
|
+
const cache = bucketedCacheEconomics(bucketed);
|
|
7256
|
+
report = bucketed;
|
|
7257
|
+
cacheDeltaUsd = cache.verdict === 'no-cache' ? undefined : cache.deltaUsd;
|
|
6950
7258
|
}
|
|
6951
|
-
const report = bucketedProfile(pull, { catalogue: pricing });
|
|
6952
|
-
const cache = bucketedCacheEconomics(report);
|
|
6953
7259
|
const result = evaluateWatch({
|
|
6954
7260
|
report,
|
|
6955
7261
|
thresholds,
|
|
6956
|
-
cacheDeltaUsd
|
|
7262
|
+
cacheDeltaUsd,
|
|
6957
7263
|
nowMs,
|
|
6958
7264
|
lastCoveredToMs: state?.lastCoveredToMs ?? undefined,
|
|
6959
7265
|
alreadyFired: new Set(Object.keys(state?.fired ?? {})),
|
|
@@ -6962,6 +7268,8 @@ async function commandWatch(args, config, pricing, t) {
|
|
|
6962
7268
|
console.log(JSON.stringify({ schemaVersion: 1, firedAtMs: nowMs, ...result }, null, 2));
|
|
6963
7269
|
}
|
|
6964
7270
|
else {
|
|
7271
|
+
for (const line of sessionFolders)
|
|
7272
|
+
console.log(c.dim(line));
|
|
6965
7273
|
if (result.gap !== null) {
|
|
6966
7274
|
console.log(c.yellow(wrap(t.watch.gap(day(result.gap.fromMs), day(result.gap.toMs)), 76, ' ')));
|
|
6967
7275
|
}
|
|
@@ -6995,6 +7303,22 @@ async function commandWatch(args, config, pricing, t) {
|
|
|
6995
7303
|
console.error(c.yellow(t.watch.webhookFailed(sent.status === null ? sent.error ?? '' : String(sent.status))));
|
|
6996
7304
|
}
|
|
6997
7305
|
}
|
|
7306
|
+
/*
|
|
7307
|
+
The person at the machine, for what is new this cycle and nothing else:
|
|
7308
|
+
a crossing already reported is `suppressed`, and a notification about it
|
|
7309
|
+
would be the second one. The text is the sentence the terminal printed,
|
|
7310
|
+
built from the same figures, and `notificationFor` takes nothing but
|
|
7311
|
+
sentences, so a prompt, a path or a project name has no way in.
|
|
7312
|
+
*/
|
|
7313
|
+
if (notify && result.crossings.length > 0) {
|
|
7314
|
+
const sent = sendNotification(notificationFor(result.crossings.map((crossing) => t.watch.crossed(crossing.gate, formatUsd(crossing.measuredUsd), formatUsd(crossing.limitUsd), crossing.day))));
|
|
7315
|
+
// Said on stderr so a `--json` reader's stdout stays the document, and
|
|
7316
|
+
// swallowed for the reason the webhook's failure is.
|
|
7317
|
+
if (sent.outcome === 'unavailable')
|
|
7318
|
+
console.error(c.yellow(t.watch.notifyUnavailable(sent.command)));
|
|
7319
|
+
if (sent.outcome === 'failed')
|
|
7320
|
+
console.error(c.yellow(t.watch.notifyFailed(sent.command, sent.error)));
|
|
7321
|
+
}
|
|
6998
7322
|
const fired = { ...(state?.fired ?? {}) };
|
|
6999
7323
|
for (const crossing of result.crossings)
|
|
7000
7324
|
fired[firedKey(crossing.gate, crossing.day)] = nowMs;
|
|
@@ -7003,6 +7327,7 @@ async function commandWatch(args, config, pricing, t) {
|
|
|
7003
7327
|
lastCycleMs: nowMs,
|
|
7004
7328
|
lastCoveredToMs: report.span?.toMs ?? state?.lastCoveredToMs ?? null,
|
|
7005
7329
|
fired,
|
|
7330
|
+
...(sessions ? { source: 'sessions' } : {}),
|
|
7006
7331
|
});
|
|
7007
7332
|
return result.crossings.length + result.suppressed.length;
|
|
7008
7333
|
};
|
|
@@ -7020,6 +7345,62 @@ async function commandWatch(args, config, pricing, t) {
|
|
|
7020
7345
|
await cycle();
|
|
7021
7346
|
}
|
|
7022
7347
|
}
|
|
7348
|
+
/**
|
|
7349
|
+
* What `trazum watch --sessions` judges: the sessions Claude Code, Codex and
|
|
7350
|
+
* Gemini CLI keep on this machine, read the way `bill` reads them with no
|
|
7351
|
+
* path and priced the way `bill` prices them.
|
|
7352
|
+
*
|
|
7353
|
+
* The folders are `agentSessionFolders`, the walk is `bill`'s, the converters
|
|
7354
|
+
* are the ones `from-claude-code`, `from-codex` and `from-gemini-cli` use, and
|
|
7355
|
+
* the money is `profileUsage`'s, so a total here is the total `bill` prints for
|
|
7356
|
+
* the same folders. Only those three agents' files: a file no agent claims is
|
|
7357
|
+
* not this command's to guess at, and `bill` is where it gets named.
|
|
7358
|
+
*
|
|
7359
|
+
* What comes back is the part of a report a gate is judged against, with no
|
|
7360
|
+
* prompt text in it: the records the converters make carry counts and a model,
|
|
7361
|
+
* and the folders named are the agents' own, never a project.
|
|
7362
|
+
*/
|
|
7363
|
+
async function watchedSessions(pricing, t) {
|
|
7364
|
+
const { found, tried } = await agentSessionFolders(process.env);
|
|
7365
|
+
if (found.length === 0)
|
|
7366
|
+
throw new Error(t.bill.noPath(tried.join(', ')));
|
|
7367
|
+
const lines = [];
|
|
7368
|
+
for (const { path } of found) {
|
|
7369
|
+
const entries = await readdir(path, { recursive: true, withFileTypes: true });
|
|
7370
|
+
const files = entries
|
|
7371
|
+
.filter((entry) => entry.isFile() && isUsageLogName(entry.name))
|
|
7372
|
+
.map((entry) => join(entry.parentPath, entry.name))
|
|
7373
|
+
.sort();
|
|
7374
|
+
for (const file of files) {
|
|
7375
|
+
const text = await readUsageLog(file, t);
|
|
7376
|
+
const [shape, ...others] = usageShapesOf(text);
|
|
7377
|
+
if (shape === undefined || others.length > 0)
|
|
7378
|
+
continue;
|
|
7379
|
+
const records = shape === 'claude-code'
|
|
7380
|
+
? claudeCodeRecords(text, {}).records
|
|
7381
|
+
: shape === 'codex'
|
|
7382
|
+
? codexRecords(text, {}).records
|
|
7383
|
+
: shape === 'gemini-cli'
|
|
7384
|
+
? geminiCliRecords(text, {}).records
|
|
7385
|
+
: [];
|
|
7386
|
+
for (const record of records)
|
|
7387
|
+
lines.push(JSON.stringify(record));
|
|
7388
|
+
}
|
|
7389
|
+
}
|
|
7390
|
+
const profile = profileUsage(lines.join('\n'), { catalogue: pricing });
|
|
7391
|
+
if (profile.total.calls === 0)
|
|
7392
|
+
throw new Error(t.watch.noSessionUsage());
|
|
7393
|
+
const cache = cacheEconomics(profile.total);
|
|
7394
|
+
return {
|
|
7395
|
+
report: {
|
|
7396
|
+
span: profile.span === null ? null : { fromMs: profile.span.fromMs, toMs: profile.span.toMs },
|
|
7397
|
+
total: { totalUsd: profile.total.totalUsd },
|
|
7398
|
+
byDay: profile.spendByDay.map((entry) => ({ day: entry.day, usd: entry.usd, calls: entry.calls })),
|
|
7399
|
+
},
|
|
7400
|
+
cacheDeltaUsd: cache.verdict === 'not-attempted' || cache.verdict === 'unpriced' ? undefined : cache.deltaUsd,
|
|
7401
|
+
folders: found.map(({ agent, path }) => t.watch.readingSessions(AGENT_NAMES[agent], path)),
|
|
7402
|
+
};
|
|
7403
|
+
}
|
|
7023
7404
|
/**
|
|
7024
7405
|
* `trazum store` — what is kept, and what a prune would take.
|
|
7025
7406
|
*
|
|
@@ -7745,7 +8126,7 @@ async function profileBySource(args, config, logFiles, logTexts, pricing, window
|
|
|
7745
8126
|
cacheUnderwater: rollup.cacheUnderwater,
|
|
7746
8127
|
unmatchedFiles: unmatched,
|
|
7747
8128
|
},
|
|
7748
|
-
}, (
|
|
8129
|
+
}, (_key, value) => (value instanceof Map ? undefined : value), 2));
|
|
7749
8130
|
}
|
|
7750
8131
|
else {
|
|
7751
8132
|
console.log(sectionHeading(t.profile.fleetHeading(n(rollup.sources.length), formatUsd(rollup.totalUsd), t.profile.calls(rollup.calls))));
|
|
@@ -7870,7 +8251,7 @@ function profileDryRun(args, report, t) {
|
|
|
7870
8251
|
* was — the gates set the exit code, and this reports what they set.
|
|
7871
8252
|
*/
|
|
7872
8253
|
async function runProfileGates(context) {
|
|
7873
|
-
const { args, config, configDir, report, previous, againstDelta, windowed,
|
|
8254
|
+
const { args, config, configDir, report, previous, againstDelta, windowed, pricing, t } = context;
|
|
7874
8255
|
const n = (value) => value.toLocaleString(t.numberLocale);
|
|
7875
8256
|
const pct = (share) => `${(share * 100).toFixed(1)}%`;
|
|
7876
8257
|
/*
|
|
@@ -8293,7 +8674,7 @@ async function runProfileGates(context) {
|
|
|
8293
8674
|
* is built from could only be learned by reading the whole body it sat in.
|
|
8294
8675
|
*/
|
|
8295
8676
|
async function writeProfileSideFiles(context) {
|
|
8296
|
-
const { args,
|
|
8677
|
+
const { args, report, previous, pressures, labelDrivers, modelDrivers, againstOverlap, whatIf, pricingStale, windowed, gates, pricing, t, } = context;
|
|
8297
8678
|
/**
|
|
8298
8679
|
* Where the "wrote to" notice goes. Under `--json`, stdout carries the
|
|
8299
8680
|
* report and nothing else — a status line there turns a parseable
|
|
@@ -8589,8 +8970,7 @@ function reportOutcomesAndCoverage(report, config, t) {
|
|
|
8589
8970
|
* thing you could only find out by reading both places.
|
|
8590
8971
|
*/
|
|
8591
8972
|
function reportAgainstPrevious(context) {
|
|
8592
|
-
const { report, previous, againstOverlap, labelDrivers, modelDrivers,
|
|
8593
|
-
const n = (value) => value.toLocaleString(t.numberLocale);
|
|
8973
|
+
const { report, previous, againstOverlap, labelDrivers, modelDrivers, t } = context;
|
|
8594
8974
|
const pct = (share) => `${(share * 100).toFixed(1)}%`;
|
|
8595
8975
|
/**
|
|
8596
8976
|
* This bill against the previous one — how spend actually gets out of hand.
|
|
@@ -8834,21 +9214,19 @@ function reportContextPressure(pressures, t) {
|
|
|
8834
9214
|
* prediction of *when*: a straight line through two points is a guess
|
|
8835
9215
|
* wearing arithmetic's clothes.
|
|
8836
9216
|
*/
|
|
8837
|
-
{
|
|
8838
|
-
|
|
9217
|
+
if (pressures.length > 0) {
|
|
9218
|
+
console.log();
|
|
9219
|
+
console.log(sectionHeading(t.profile.pressureHeading()));
|
|
9220
|
+
for (const row of pressures.slice(0, 3)) {
|
|
9221
|
+
const label = row.label === UNLABELLED ? t.profile.unlabelled() : row.label;
|
|
9222
|
+
const line = t.profile.pressureLine(label, row.modelName, n(row.maxCallInputTokens), n(row.contextWindow), pct(row.share));
|
|
8839
9223
|
console.log();
|
|
8840
|
-
|
|
8841
|
-
|
|
8842
|
-
|
|
8843
|
-
|
|
8844
|
-
|
|
8845
|
-
|
|
8846
|
-
console.log(` ${c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
|
|
8847
|
-
console.log(` ${c.dim(wrap(t.profile.pressureAdvice(), 74, ' '))}`);
|
|
8848
|
-
}
|
|
8849
|
-
else {
|
|
8850
|
-
console.log(` ${c.dim(wrap(line, 74, ' '))}`);
|
|
8851
|
-
}
|
|
9224
|
+
if (row.share >= 0.85) {
|
|
9225
|
+
console.log(` ${c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
|
|
9226
|
+
console.log(` ${c.dim(wrap(t.profile.pressureAdvice(), 74, ' '))}`);
|
|
9227
|
+
}
|
|
9228
|
+
else {
|
|
9229
|
+
console.log(` ${c.dim(wrap(line, 74, ' '))}`);
|
|
8852
9230
|
}
|
|
8853
9231
|
}
|
|
8854
9232
|
}
|
|
@@ -9012,9 +9390,8 @@ function reportConversationHistory(report, t) {
|
|
|
9012
9390
|
* which is the only version of this question worth answering: a migration priced
|
|
9013
9391
|
* off a guess is a forecast, and this product does not forecast.
|
|
9014
9392
|
*/
|
|
9015
|
-
function reportWhatIf(whatIf,
|
|
9393
|
+
function reportWhatIf(whatIf, t) {
|
|
9016
9394
|
const n = (value) => value.toLocaleString(t.numberLocale);
|
|
9017
|
-
const pct = (share) => `${(share * 100).toFixed(1)}%`;
|
|
9018
9395
|
/**
|
|
9019
9396
|
* `--what-if <model>`: these exact calls, at another model's rates.
|
|
9020
9397
|
*
|
|
@@ -9041,7 +9418,7 @@ function reportWhatIf(whatIf, report, t) {
|
|
|
9041
9418
|
else {
|
|
9042
9419
|
const cheaper = whatIf.deltaUsd < 0;
|
|
9043
9420
|
const line = t.profile.whatIfTotal(formatUsd(whatIf.currentUsd), formatUsd(whatIf.targetUsd), formatUsd(Math.abs(whatIf.deltaUsd)));
|
|
9044
|
-
console.log(` ${cheaper ? c.
|
|
9421
|
+
console.log(` ${cheaper ? c.accent('→') : c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
|
|
9045
9422
|
console.log(` ${c.dim(wrap(cheaper ? t.profile.whatIfCheaper() : t.profile.whatIfDearer(), 74, ' '))}`);
|
|
9046
9423
|
/**
|
|
9047
9424
|
* The other half of the whole decision: the same move with the target's
|
|
@@ -9099,7 +9476,6 @@ function reportWhatIf(whatIf, report, t) {
|
|
|
9099
9476
|
* rather than from what a file would cost.
|
|
9100
9477
|
*/
|
|
9101
9478
|
function reportLevers(report, pricing, t) {
|
|
9102
|
-
const n = (value) => value.toLocaleString(t.numberLocale);
|
|
9103
9479
|
const pct = (share) => `${(share * 100).toFixed(1)}%`;
|
|
9104
9480
|
/**
|
|
9105
9481
|
* The section this command is for, and the answer to the fairest complaint the
|
|
@@ -9149,7 +9525,7 @@ function reportLevers(report, pricing, t) {
|
|
|
9149
9525
|
* $12.60 and $10.50 against a slice that had spent $21.00: a saving larger
|
|
9150
9526
|
* than the bill it came from, in the flattering direction.
|
|
9151
9527
|
*/
|
|
9152
|
-
console.log(` ${c.
|
|
9528
|
+
console.log(` ${c.accent('→')} ${c.bold(wrap(t.profile.leverSlice(label, slice.modelName, formatUsd(slice.combinedUsd), pct(slice.shareOfBill)), 74, ' '))}`);
|
|
9153
9529
|
console.log(` ${c.dim(t.profile.leverCalls(t.profile.calls(slice.calls), formatUsd(slice.spentUsd)))}`);
|
|
9154
9530
|
if (slice.route) {
|
|
9155
9531
|
console.log(` ${c.dim('·')} ${c.dim(wrap(t.profile.leverRoute(slice.route.candidate.displayName, formatUsd(slice.route.savingUsd)), 74, ' '))}`);
|
|
@@ -9615,40 +9991,47 @@ async function commandPlan(args, pricing, t) {
|
|
|
9615
9991
|
console.log(JSON.stringify(stamped, null, 2));
|
|
9616
9992
|
return;
|
|
9617
9993
|
}
|
|
9618
|
-
|
|
9619
|
-
|
|
9620
|
-
|
|
9621
|
-
|
|
9622
|
-
|
|
9994
|
+
/*
|
|
9995
|
+
The question and its answer first: what the plan would save, marked.
|
|
9996
|
+
Then the actions, then what was left out and how to read it (#758).
|
|
9997
|
+
*/
|
|
9998
|
+
const draw = new Report();
|
|
9999
|
+
const projected = formatUsd(stamped.projectedSavingUsd);
|
|
10000
|
+
draw.headline(t.plan.heading(n(actions.length), formatUsd(plan.totalUsd)), t.plan.totals(projected, formatUsd(stamped.measuredStakeUsd)), projected);
|
|
10001
|
+
if (plan.span === null)
|
|
10002
|
+
draw.text(t.plan.noClock(), { tone: 'dim' });
|
|
9623
10003
|
for (const action of actions) {
|
|
9624
10004
|
const name = action.label === UNLABELLED ? t.profile.unlabelled() : action.label;
|
|
9625
10005
|
const money = action.savingUsd !== null
|
|
9626
10006
|
? t.plan.projected(formatUsd(action.savingUsd))
|
|
9627
10007
|
: t.plan.staked(formatUsd(action.stakeUsd ?? 0));
|
|
9628
|
-
|
|
9629
|
-
|
|
10008
|
+
draw.blank();
|
|
10009
|
+
// The action and its money on one line when the window holds them; the
|
|
10010
|
+
// money under the action when it does not, never split from its word.
|
|
10011
|
+
const title = t.plan.action(action.kind, name, action.model);
|
|
10012
|
+
const whole = ` ${draw.markOf('point')} ${c.bold(title)} ${money}`;
|
|
10013
|
+
if (draw.fits(whole))
|
|
10014
|
+
draw.line(whole);
|
|
10015
|
+
else
|
|
10016
|
+
draw.text(title, { first: ` ${draw.markOf('point')} `, indent: ' ', tone: 'bold' }).text(money, { indent: ' ' });
|
|
10017
|
+
// The module's `wrap`, at the widths these lines always had on a pipe.
|
|
9630
10018
|
if (action.detail.routeTo !== undefined) {
|
|
9631
|
-
|
|
10019
|
+
draw.line(` ${c.dim(wrap(t.plan.routeTo(action.detail.routeTo.displayName, action.kind === 'route+batch'), 1000, ' '))}`);
|
|
9632
10020
|
}
|
|
9633
10021
|
for (const assumption of action.assumes) {
|
|
9634
|
-
|
|
9635
|
-
}
|
|
9636
|
-
if (action.check !== null) {
|
|
9637
|
-
console.log(` ${c.dim(wrap(t.plan.check(action.check), 72, ' '))}`);
|
|
10022
|
+
draw.line(` ${draw.markOf('question')} ${c.dim(wrap(t.plan.assume(assumption), 72, ' '))}`);
|
|
9638
10023
|
}
|
|
10024
|
+
if (action.check !== null)
|
|
10025
|
+
draw.line(` ${c.dim(wrap(t.plan.check(action.check), 72, ' '))}`);
|
|
9639
10026
|
}
|
|
9640
|
-
if (filtered > 0)
|
|
9641
|
-
|
|
9642
|
-
|
|
9643
|
-
|
|
9644
|
-
|
|
9645
|
-
console.log();
|
|
9646
|
-
console.log(` ${c.dim(wrap(t.plan.batchExcluded(formatUsd(plan.batchExcludedUsd)), 74, ' '))}`);
|
|
9647
|
-
}
|
|
9648
|
-
console.log();
|
|
9649
|
-
console.log(` ${c.dim(wrap(t.plan.footer(), 74, ' '))}`);
|
|
10027
|
+
if (filtered > 0)
|
|
10028
|
+
draw.blank().text(t.plan.filtered(n(filtered), formatUsd(minUsd), formatUsd(droppedUsd)), { tone: 'dim' });
|
|
10029
|
+
if (plan.batchExcludedUsd > 0)
|
|
10030
|
+
draw.blank().text(t.plan.batchExcluded(formatUsd(plan.batchExcludedUsd)), { tone: 'dim' });
|
|
10031
|
+
draw.blank().text(t.plan.footer(), { tone: 'dim' });
|
|
9650
10032
|
if (outPath !== undefined)
|
|
9651
|
-
|
|
10033
|
+
draw.text(t.plan.wrote(outPath), { indent: '', tone: 'dim' });
|
|
10034
|
+
draw.print();
|
|
9652
10035
|
}
|
|
9653
10036
|
async function commandProfile(args, config, configDir, pricing, t) {
|
|
9654
10037
|
const path = args.positional[0];
|
|
@@ -10042,7 +10425,7 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10042
10425
|
if (report.total.calls === 0) {
|
|
10043
10426
|
console.log();
|
|
10044
10427
|
console.log(c.dim(report.unpriced.calls === 0 ? t.profile.empty() : t.profile.nothingPriced()));
|
|
10045
|
-
reportProfileGaps(report, t,
|
|
10428
|
+
reportProfileGaps(report, t, pricingStale);
|
|
10046
10429
|
return;
|
|
10047
10430
|
}
|
|
10048
10431
|
const shares = sharesOf(report.total);
|
|
@@ -10052,9 +10435,45 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10052
10435
|
[t.profile.partCacheWrite(), report.total.cacheWriteUsd, shares.cacheWrite, report.total.cacheWriteTokens],
|
|
10053
10436
|
[t.profile.partOutput(), report.total.outputUsd, shares.output, report.total.outputTokens],
|
|
10054
10437
|
];
|
|
10055
|
-
|
|
10056
|
-
|
|
10057
|
-
|
|
10438
|
+
/*
|
|
10439
|
+
The question and its answer first: what this log cost, the total marked.
|
|
10440
|
+
Then where it went, part by part. Then what qualifies the total: the
|
|
10441
|
+
period, the files, a doubled line, the window (#758).
|
|
10442
|
+
*/
|
|
10443
|
+
const draw = new Report();
|
|
10444
|
+
const totalUsd = formatUsd(report.total.totalUsd);
|
|
10445
|
+
draw.blank().headline(t.profile.heading(), t.profile.spent(t.profile.calls(report.total.calls), totalUsd), totalUsd);
|
|
10446
|
+
draw.blank();
|
|
10447
|
+
// Every part, including the zero ones. A row missing because it was zero reads
|
|
10448
|
+
// as a row somebody forgot, and "you are not caching at all" is a finding.
|
|
10449
|
+
const partRows = parts.map(([name, usd, share, tokens]) => ({
|
|
10450
|
+
share,
|
|
10451
|
+
text: t.profile.part(name, formatUsd(usd), pct(share), n(tokens)),
|
|
10452
|
+
}));
|
|
10453
|
+
// Billed per search, so it counts searches where the rows above count tokens.
|
|
10454
|
+
if (report.total.webSearchRequests > 0) {
|
|
10455
|
+
partRows.push({
|
|
10456
|
+
share: shares.webSearch,
|
|
10457
|
+
text: t.profile.partSearches(t.profile.partWebSearch(), formatUsd(report.total.webSearchUsd), pct(shares.webSearch), report.total.webSearchRequests),
|
|
10458
|
+
});
|
|
10459
|
+
}
|
|
10460
|
+
draw.shares(partRows);
|
|
10461
|
+
/**
|
|
10462
|
+
* The line the command exists for: which part of the bill to argue with.
|
|
10463
|
+
*
|
|
10464
|
+
* When output is both the biggest part and over half, the two sentences say the
|
|
10465
|
+
* same thing and the second says more — so only the second prints. Reporting a
|
|
10466
|
+
* fact twice in adjacent lines reads as a bug, and it was one.
|
|
10467
|
+
*/
|
|
10468
|
+
const [biggestName, , biggestShare] = parts.reduce((a, b) => (b[1] > a[1] ? b : a));
|
|
10469
|
+
const outputDominates = shares.output > 0.5;
|
|
10470
|
+
draw.blank();
|
|
10471
|
+
if (outputDominates) {
|
|
10472
|
+
draw.text(t.profile.outputDominates(pct(shares.output)), { tone: 'bold' });
|
|
10473
|
+
}
|
|
10474
|
+
else {
|
|
10475
|
+
draw.text(t.profile.biggestPart(biggestName, pct(biggestShare)), { tone: 'bold' });
|
|
10476
|
+
}
|
|
10058
10477
|
/**
|
|
10059
10478
|
* The period, when the log carries a clock — stated, never extrapolated. A
|
|
10060
10479
|
* span makes the reader's own monthly arithmetic valid; a per-month figure
|
|
@@ -10068,13 +10487,12 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10068
10487
|
const partial = report.span.calls < totalParsed
|
|
10069
10488
|
? ` ${t.profile.spanPartial(n(report.span.calls), n(totalParsed))}`
|
|
10070
10489
|
: '';
|
|
10071
|
-
|
|
10490
|
+
draw.text(`${t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs))}${partial}`, { tone: 'dim' });
|
|
10072
10491
|
}
|
|
10073
10492
|
// How many files this report covers, when it covers more than one: a total
|
|
10074
10493
|
// over "the logs" that silently skipped one is wrong by an unknown amount.
|
|
10075
|
-
if (logFiles.length > 1)
|
|
10076
|
-
|
|
10077
|
-
}
|
|
10494
|
+
if (logFiles.length > 1)
|
|
10495
|
+
draw.text(t.profile.readFiles(logFiles.length, path), { tone: 'dim' });
|
|
10078
10496
|
/**
|
|
10079
10497
|
* A doubled bill, said before anything is believed.
|
|
10080
10498
|
*
|
|
@@ -10086,7 +10504,7 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10086
10504
|
* double export or a genuinely busy millisecond is the reader's to know.
|
|
10087
10505
|
*/
|
|
10088
10506
|
if (report.duplicateLines.count > 0) {
|
|
10089
|
-
|
|
10507
|
+
draw.note('caution', t.profile.duplicateLines(report.duplicateLines.count, formatUsd(report.duplicateLines.usd)), { tone: 'dim' });
|
|
10090
10508
|
}
|
|
10091
10509
|
/**
|
|
10092
10510
|
* The window, said before any figure is trusted as "the log": everything
|
|
@@ -10096,40 +10514,14 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10096
10514
|
* figures are a floor on the period, and only this line says so.
|
|
10097
10515
|
*/
|
|
10098
10516
|
if (report.timeWindow !== null) {
|
|
10099
|
-
|
|
10100
|
-
if (relativeWindow)
|
|
10101
|
-
|
|
10102
|
-
}
|
|
10517
|
+
draw.text(t.profile.windowLine(stringFlag(args, 'since') ?? '—', stringFlag(args, 'until') ?? '—'), { tone: 'dim' });
|
|
10518
|
+
if (relativeWindow)
|
|
10519
|
+
draw.text(t.profile.windowRelative(), { tone: 'dim' });
|
|
10103
10520
|
if (report.timeWindow.undatedExcluded > 0) {
|
|
10104
|
-
|
|
10521
|
+
draw.note('caution', t.profile.windowUndated(report.timeWindow.undatedExcluded));
|
|
10105
10522
|
}
|
|
10106
10523
|
}
|
|
10107
|
-
|
|
10108
|
-
// Every part, including the zero ones. A row missing because it was zero reads
|
|
10109
|
-
// as a row somebody forgot, and "you are not caching at all" is a finding.
|
|
10110
|
-
for (const [name, usd, share, tokens] of parts) {
|
|
10111
|
-
console.log(` ${bar(share)} ${t.profile.part(name, formatUsd(usd), pct(share), n(tokens))}`);
|
|
10112
|
-
}
|
|
10113
|
-
// Billed per search, so it counts searches where the rows above count tokens.
|
|
10114
|
-
if (report.total.webSearchRequests > 0) {
|
|
10115
|
-
console.log(` ${bar(shares.webSearch)} ${t.profile.partSearches(t.profile.partWebSearch(), formatUsd(report.total.webSearchUsd), pct(shares.webSearch), report.total.webSearchRequests)}`);
|
|
10116
|
-
}
|
|
10117
|
-
/**
|
|
10118
|
-
* The line the command exists for: which part of the bill to argue with.
|
|
10119
|
-
*
|
|
10120
|
-
* When output is both the biggest part and over half, the two sentences say the
|
|
10121
|
-
* same thing and the second says more — so only the second prints. Reporting a
|
|
10122
|
-
* fact twice in adjacent lines reads as a bug, and it was one.
|
|
10123
|
-
*/
|
|
10124
|
-
const [biggestName, , biggestShare] = parts.reduce((a, b) => (b[1] > a[1] ? b : a));
|
|
10125
|
-
const outputDominates = shares.output > 0.5;
|
|
10126
|
-
console.log();
|
|
10127
|
-
if (outputDominates) {
|
|
10128
|
-
console.log(` ${c.bold(wrap(t.profile.outputDominates(pct(shares.output)), 74, ' '))}`);
|
|
10129
|
-
}
|
|
10130
|
-
else {
|
|
10131
|
-
console.log(` ${c.bold(t.profile.biggestPart(biggestName, pct(biggestShare)))}`);
|
|
10132
|
-
}
|
|
10524
|
+
draw.print();
|
|
10133
10525
|
/**
|
|
10134
10526
|
* The most expensive day, with a suspect attached.
|
|
10135
10527
|
*
|
|
@@ -10148,9 +10540,12 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10148
10540
|
const labelClause = peak.topLabel !== null && report.byLabel.length > 1
|
|
10149
10541
|
? ` ${t.profile.dayPeakLabel(peak.topLabel === UNLABELLED ? t.profile.unlabelled() : peak.topLabel, formatUsd(peak.topLabelUsd))}`
|
|
10150
10542
|
: '';
|
|
10543
|
+
// Loud past twice the median: the mark says so, a pipe included.
|
|
10151
10544
|
const loud = peak.usd > 2 * medianUsd;
|
|
10152
|
-
|
|
10153
|
-
|
|
10545
|
+
if (loud)
|
|
10546
|
+
new Report().note('caution', `${line}${labelClause}`).print();
|
|
10547
|
+
else
|
|
10548
|
+
new Report().text(`${line}${labelClause}`, { tone: 'dim' }).print();
|
|
10154
10549
|
}
|
|
10155
10550
|
}
|
|
10156
10551
|
/**
|
|
@@ -10190,7 +10585,7 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10190
10585
|
reportCacheVerdict(report, t);
|
|
10191
10586
|
await reportLabelsBudgetsAndCache(report, config, pricing, t);
|
|
10192
10587
|
reportLevers(report, pricing, t);
|
|
10193
|
-
reportWhatIf(whatIf,
|
|
10588
|
+
reportWhatIf(whatIf, t);
|
|
10194
10589
|
reportConversationHistory(report, t);
|
|
10195
10590
|
reportOutputShape(report, t);
|
|
10196
10591
|
reportInputShape(report, t);
|
|
@@ -10206,15 +10601,17 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10206
10601
|
]) {
|
|
10207
10602
|
if (rows.length <= 1)
|
|
10208
10603
|
continue; // One row is the total again, said twice.
|
|
10209
|
-
|
|
10210
|
-
|
|
10211
|
-
|
|
10604
|
+
new Report()
|
|
10605
|
+
.blank()
|
|
10606
|
+
.heading(heading)
|
|
10607
|
+
.shares(rows.map(([name, breakdown]) => {
|
|
10212
10608
|
const share = report.total.totalUsd > 0 ? breakdown.totalUsd / report.total.totalUsd : 0;
|
|
10213
|
-
|
|
10214
|
-
}
|
|
10609
|
+
return { share, text: t.profile.row(name, formatUsd(breakdown.totalUsd), pct(share), t.profile.calls(breakdown.calls)) };
|
|
10610
|
+
}))
|
|
10611
|
+
.print();
|
|
10215
10612
|
}
|
|
10216
10613
|
reportOutcomesAndCoverage(report, config, t);
|
|
10217
|
-
reportProfileGaps(report, t,
|
|
10614
|
+
reportProfileGaps(report, t, pricingStale);
|
|
10218
10615
|
gates = await runProfileGates({
|
|
10219
10616
|
args, config, configDir, report, previous, againstDelta, windowed, now, pricing, t,
|
|
10220
10617
|
});
|
|
@@ -10230,7 +10627,7 @@ async function commandProfile(args, config, configDir, pricing, t) {
|
|
|
10230
10627
|
* silently omits calls is wrong in the flattering direction, which is the fault
|
|
10231
10628
|
* this repository keeps finding in itself.
|
|
10232
10629
|
*/
|
|
10233
|
-
function reportProfileGaps(report, t,
|
|
10630
|
+
function reportProfileGaps(report, t, stalePricing = null) {
|
|
10234
10631
|
/**
|
|
10235
10632
|
* The one fact that silently invalidates every dollar above: a price table
|
|
10236
10633
|
* the provider may have re-priced since. Loud, because unlike a skipped
|
|
@@ -10688,7 +11085,7 @@ async function checkDirectory(root, args, flagBudget, config, counter, level, t,
|
|
|
10688
11085
|
return;
|
|
10689
11086
|
only = checkable;
|
|
10690
11087
|
}
|
|
10691
|
-
const { verdicts, declined, truncated,
|
|
11088
|
+
const { verdicts, declined, truncated, band } = await scanPrompts(root, args, flagBudget, config, counter, level, t, locale, pricing, only);
|
|
10692
11089
|
/**
|
|
10693
11090
|
* The baseline gate, when the config declares one and `--no-baseline` did not
|
|
10694
11091
|
* switch it off for this run.
|
|
@@ -10795,26 +11192,43 @@ async function checkDirectory(root, args, flagBudget, config, counter, level, t,
|
|
|
10795
11192
|
const labelWidth = Math.max(t.check.okLabel().length, t.check.failedLabel().length) + 2;
|
|
10796
11193
|
const tokenWidth = Math.max(...verdicts.map((v) => n(v.tokens).length));
|
|
10797
11194
|
const budgetWidth = Math.max(0, ...verdicts.map((v) => (v.maxTokens === null ? 0 : n(v.maxTokens).length)));
|
|
10798
|
-
|
|
10799
|
-
|
|
10800
|
-
|
|
11195
|
+
/*
|
|
11196
|
+
The question and its answer first (#758): how many prompts, and whether
|
|
11197
|
+
they fit, in the colour of the verdict and in words that say it without
|
|
11198
|
+
one. Then the prompts, one a line; then what could not be read.
|
|
11199
|
+
*/
|
|
11200
|
+
const summary = t.check.directorySummary(failures.length, verdicts.length);
|
|
11201
|
+
// Three independent verdicts about one run: a busted budget, an unreadable
|
|
11202
|
+
// marker, and drift past the baseline. Any of them failing fails the build —
|
|
11203
|
+
// an && here would let a breach ride out on a green budget.
|
|
11204
|
+
// The summary sentence counts budgets, so its colour follows budgets. `bad`
|
|
11205
|
+
// is the run's verdict and folds in the baseline: three independent findings
|
|
11206
|
+
// about one run, and any of them failing fails the build. An && here would let
|
|
11207
|
+
// a breach ride out on a green budget.
|
|
11208
|
+
const budgetBad = failures.length > 0 || declined.length > 0;
|
|
11209
|
+
const bad = budgetBad || (baselineOutcome?.breached.length ?? 0) > 0;
|
|
11210
|
+
const draw = new Report();
|
|
11211
|
+
draw.blank().heading(t.check.directoryHeading(root, verdicts.length));
|
|
11212
|
+
draw.text(summary, { tone: budgetBad ? 'error' : 'good' });
|
|
11213
|
+
draw.blank();
|
|
10801
11214
|
for (const verdict of verdicts) {
|
|
10802
11215
|
const tokens = n(verdict.tokens).padStart(tokenWidth);
|
|
10803
11216
|
if (verdict.maxTokens === null) {
|
|
10804
11217
|
// Blanks where " / <budget>" would be, so the path column does not shift.
|
|
10805
|
-
|
|
10806
|
-
|
|
11218
|
+
const lead = ` ${c.dim('—'.padEnd(labelWidth))}${tokens}${' '.repeat(3 + budgetWidth)} `;
|
|
11219
|
+
draw.line(`${lead}${fitPath(`${verdict.path} ${t.check.noBudget()}`, draw.room(lead))}`);
|
|
10807
11220
|
continue;
|
|
10808
11221
|
}
|
|
10809
11222
|
const over = isOverBudget(verdict);
|
|
10810
11223
|
const plain = over ? t.check.failedLabel() : t.check.okLabel();
|
|
10811
11224
|
const label = (over ? c.red(plain) : c.green(plain)) + ' '.repeat(labelWidth - plain.length);
|
|
10812
11225
|
const budget = n(verdict.maxTokens).padEnd(budgetWidth);
|
|
10813
|
-
|
|
11226
|
+
const lead = ` ${label}${tokens} / ${budget} `;
|
|
11227
|
+
draw.line(`${lead}${fitPath(verdict.path, draw.room(lead))}`);
|
|
10814
11228
|
if (over && verdict.optimizedTokens !== null) {
|
|
10815
|
-
|
|
11229
|
+
draw.text(verdict.optimizedTokens <= verdict.maxTokens
|
|
10816
11230
|
? t.check.wouldFit(level, n(verdict.optimizedTokens))
|
|
10817
|
-
: t.check.stillTooBig(n(verdict.optimizedTokens)))}
|
|
11231
|
+
: t.check.stillTooBig(n(verdict.optimizedTokens)), { indent: ` ${' '.repeat(labelWidth)}`, tone: 'dim' });
|
|
10818
11232
|
}
|
|
10819
11233
|
}
|
|
10820
11234
|
// A marker Trazum could not read is a failure, not a footnote. The author
|
|
@@ -10822,26 +11236,14 @@ async function checkDirectory(root, args, flagBudget, config, counter, level, t,
|
|
|
10822
11236
|
// green summary alongside would be the same lie as "0 failures" from a run
|
|
10823
11237
|
// that measured nothing.
|
|
10824
11238
|
if (declined.length > 0) {
|
|
10825
|
-
|
|
10826
|
-
console.log(c.red(t.check.declinedHeading(declined.length)));
|
|
11239
|
+
draw.blank().line(c.red(t.check.declinedHeading(declined.length)));
|
|
10827
11240
|
for (const entry of declined) {
|
|
10828
|
-
|
|
11241
|
+
draw.text(`${entry.path} ${t.check.declinedAt(entry.line, entry.detail)}`, { tone: 'dim' });
|
|
10829
11242
|
}
|
|
10830
11243
|
}
|
|
10831
|
-
console.log();
|
|
10832
|
-
const summary = t.check.directorySummary(failures.length, verdicts.length);
|
|
10833
|
-
// Three independent verdicts about one run: a busted budget, an unreadable
|
|
10834
|
-
// marker, and drift past the baseline. Any of them failing fails the build —
|
|
10835
|
-
// an && here would let a breach ride out on a green budget.
|
|
10836
|
-
// The summary sentence counts budgets, so its colour follows budgets. `bad`
|
|
10837
|
-
// is the run's verdict and folds in the baseline: three independent findings
|
|
10838
|
-
// about one run, and any of them failing fails the build. An && here would let
|
|
10839
|
-
// a breach ride out on a green budget.
|
|
10840
|
-
const budgetBad = failures.length > 0 || declined.length > 0;
|
|
10841
|
-
const bad = budgetBad || (baselineOutcome?.breached.length ?? 0) > 0;
|
|
10842
|
-
console.log(` ${budgetBad ? c.red(summary) : c.green(summary)}`);
|
|
10843
11244
|
if (truncated)
|
|
10844
|
-
|
|
11245
|
+
draw.blank().note('caution', t.check.walkTruncated());
|
|
11246
|
+
draw.print();
|
|
10845
11247
|
// After the per-file summary, because the two answer different questions and
|
|
10846
11248
|
// the wider one reads last: budgets are about files, the baseline is about the
|
|
10847
11249
|
// repository. Printing it first put "All 2 within budget" underneath a failed
|
|
@@ -10940,7 +11342,7 @@ async function commandPrune(args, t) {
|
|
|
10940
11342
|
*/
|
|
10941
11343
|
const needed = contribution.verdict === 'diverges';
|
|
10942
11344
|
const unknown = contribution.verdict === 'inconclusive';
|
|
10943
|
-
const mark = unknown ? c.yellow('?') : needed ? c.dim('·') : c.
|
|
11345
|
+
const mark = unknown ? c.yellow('?') : needed ? c.dim('·') : c.accent('→');
|
|
10944
11346
|
const label = unknown
|
|
10945
11347
|
? t.prune.verdictUnknown()
|
|
10946
11348
|
: needed
|
|
@@ -11792,7 +12194,7 @@ async function main() {
|
|
|
11792
12194
|
await commandReport(args, config, pricing, t);
|
|
11793
12195
|
break;
|
|
11794
12196
|
case 'commitment':
|
|
11795
|
-
await commandCommitment(args,
|
|
12197
|
+
await commandCommitment(args, pricing, t);
|
|
11796
12198
|
break;
|
|
11797
12199
|
case 'owners':
|
|
11798
12200
|
await commandOwners(args, config, pricing, t);
|
|
@@ -11863,6 +12265,9 @@ async function main() {
|
|
|
11863
12265
|
case 'bill':
|
|
11864
12266
|
await commandBill(args, pricing, t);
|
|
11865
12267
|
break;
|
|
12268
|
+
case 'weekly':
|
|
12269
|
+
await commandWeekly(args, pricing, t);
|
|
12270
|
+
break;
|
|
11866
12271
|
case 'from-helicone':
|
|
11867
12272
|
await commandFromHelicone(args, t);
|
|
11868
12273
|
break;
|
|
@@ -11884,6 +12289,9 @@ async function main() {
|
|
|
11884
12289
|
case 'init':
|
|
11885
12290
|
await commandInit(args, config, pricing, t);
|
|
11886
12291
|
break;
|
|
12292
|
+
case 'proactive':
|
|
12293
|
+
await commandProactive(args, pricing, t);
|
|
12294
|
+
break;
|
|
11887
12295
|
case 'where':
|
|
11888
12296
|
await commandWhere(args, config, pricing, t);
|
|
11889
12297
|
break;
|