@trazum/cli 1.42.0 → 1.43.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.
- package/README.md +1 -0
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +63 -0
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +65 -0
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/types.d.ts +26 -1
- package/dist/i18n/types.d.ts.map +1 -1
- package/dist/index.js +162 -1
- package/dist/index.js.map +1 -1
- package/dist/watch-run.d.ts +69 -0
- package/dist/watch-run.d.ts.map +1 -0
- package/dist/watch-run.js +79 -0
- package/dist/watch-run.js.map +1 -0
- package/package.json +2 -2
- package/src/i18n/en.ts +73 -0
- package/src/i18n/es.ts +75 -0
- package/src/i18n/types.ts +27 -1
- package/src/index.ts +222 -0
- package/src/watch-run.ts +126 -0
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { join, resolve as resolvePath } from 'node:path';
|
|
4
4
|
import { gunzipSync } from 'node:zlib';
|
|
5
|
-
import { applyRewrites, BASELINE_FILENAME, BASELINE_VERSION, breaches, cacheableMinimum, analyzeCachePrefix, billLevers, bucketedCacheEconomics, bucketedProfile, buildHistory, buildPlan, connectorFor, CONNECTORS, normalizeAnthropicUsage, normalizeOpenAIUsage, bucketsFromRecords, pruneRecords, recordsFromBuckets, storeInventory, storedReportFrom, verifyPlan, cacheEconomics, cacheHitRate, contextPressure, comparePrompts, compareToBaseline, computeSavings, countTokensAnthropic, DEFAULT_USAGE, detectFromSource, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, moneyIsComparable, mostSpecificMatch, nearestName, optimize, parseBaseline, PHRASE_LANGUAGES, plannedCalls, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, TTL_1H_MS, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
|
|
5
|
+
import { 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, countTokensAnthropic, DEFAULT_USAGE, detectFromSource, coverageDrift, driversBetween, explainGateFailure, assignSources, fleetRollup, labelCoverage, measuredUsage, gateMargin, GATE_MARGIN_TIGHT, estimateTokens, evaluate, extractPrompts, findExamples, formatBaseline, formatSignedUsd, formatUsd, getMessages, getModel, hasMarker, LOCALES, MAX_BASELINE_BYTES, moneyIsComparable, mostSpecificMatch, nearestName, optimize, parseBaseline, PHRASE_LANGUAGES, plannedCalls, profilePrompt, profileToCsv, profileUsage, promptId, providerFromEnv, pruneExamples, refineWithLlm, rejectionText, reorderForCache, repriceProfile, reviewAgeDays, reviewExamples, RULES, sharedPrefixes, sharesOf, SOURCE_EXTENSIONS, suggestRewrites, toOtlpMetrics, toPromptfoo, TTL_1H_MS, UNLABELLED, withExactTokenCounts, } from '@trazum/core';
|
|
6
6
|
import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cache.js';
|
|
7
7
|
import { dayOf, formatGap, median, spanDays } from './time.js';
|
|
8
8
|
// Everything that reads the filesystem, on its own entry point so the web
|
|
@@ -11,6 +11,7 @@ import { CONFIG_FILENAME, DEFAULT_EXTENSIONS, budgetFor, BUNDLED_CATALOGUE, SAFE
|
|
|
11
11
|
import { contentAt, gitAvailable, namesByRevision, pathInRepository, repositoryRoot, revisionsFor, } from './git.js';
|
|
12
12
|
import { fetchProviderUsage } from './connect.js';
|
|
13
13
|
import { STORE_DIR, appendRecords, readStore, rewriteStore } from './store-fs.js';
|
|
14
|
+
import { WATCH_STATE_VERSION, checkWebhook, postWebhook, readWatchState, writeWatchState, } from './watch-run.js';
|
|
14
15
|
import { detectLocale, getCliMessages } from './i18n/index.js';
|
|
15
16
|
import { MAX_SUMMARY_CHARS, fitWithin, renderBlameMarkdown, renderCheckMarkdown, renderDiffMarkdown, renderRankMarkdown, renderProfileMarkdown, } from './markdown.js';
|
|
16
17
|
// --------------------------------------------------------------------------
|
|
@@ -31,6 +32,8 @@ const VALUE_FLAGS = new Set([
|
|
|
31
32
|
'min-usd',
|
|
32
33
|
'payload',
|
|
33
34
|
'keep',
|
|
35
|
+
'interval',
|
|
36
|
+
'webhook',
|
|
34
37
|
// `route` takes a path here, and the flag is deliberately not `--prompt`:
|
|
35
38
|
// everywhere else in this tool `--prompt` names a marked prompt *inside* a
|
|
36
39
|
// source file, and reusing it for a path would be a trap laid for the reader.
|
|
@@ -295,6 +298,7 @@ const COMMAND_FLAGS = {
|
|
|
295
298
|
history: ['store', 'json', 'markdown-out'],
|
|
296
299
|
connect: ['since', 'until', 'payload', 'store', 'json', 'out', 'markdown-out', 'pricing', 'pricing-live', 'dry-run'],
|
|
297
300
|
store: ['prune', 'keep', 'json', 'pricing', 'pricing-live', 'dry-run'],
|
|
301
|
+
watch: ['once', 'interval', 'since', 'payload', 'webhook', 'json', 'pricing', 'pricing-live'],
|
|
298
302
|
route: ['prompt-file', 'cases', 'label', 'concurrency', 'json', 'yes', 'pricing', 'pricing-live'],
|
|
299
303
|
eval: ['cases', 'level', 'concurrency', 'export', 'out', 'o', 'model'],
|
|
300
304
|
prune: ['cases', 'concurrency', 'json', 'yes'],
|
|
@@ -1689,6 +1693,160 @@ function parseWhen(args, flag, endOfDay, t, now) {
|
|
|
1689
1693
|
return { ms: exact, relative: false };
|
|
1690
1694
|
throw new Error(t.profile.badWhen(flag, value));
|
|
1691
1695
|
}
|
|
1696
|
+
/**
|
|
1697
|
+
* `trazum watch` — the afternoon it happened, said that afternoon.
|
|
1698
|
+
*
|
|
1699
|
+
* One cycle is the primitive: measure, keep, evaluate, emit, remember. The
|
|
1700
|
+
* loop is that cycle in a timer, so a cron entry and a foreground watcher run
|
|
1701
|
+
* exactly the same code and the tests exercise the thing that ships.
|
|
1702
|
+
*
|
|
1703
|
+
* Three transports, all boring on purpose: a non-zero exit code so cron mails
|
|
1704
|
+
* it, a JSON event on stdout so any pipeline can read it, and a webhook for
|
|
1705
|
+
* the operator who already has somewhere for alerts to go. No hosted service
|
|
1706
|
+
* and no account.
|
|
1707
|
+
*/
|
|
1708
|
+
async function commandWatch(args, config, pricing, t) {
|
|
1709
|
+
const root = process.cwd();
|
|
1710
|
+
const asJson = boolFlag(args, 'json');
|
|
1711
|
+
const n = (value) => value.toLocaleString(t.numberLocale);
|
|
1712
|
+
const day = (msValue) => new Date(msValue).toISOString().slice(0, 10);
|
|
1713
|
+
const thresholds = {
|
|
1714
|
+
maxUsd: config.spend?.maxUsd,
|
|
1715
|
+
maxDayUsd: config.spend?.maxDayUsd,
|
|
1716
|
+
maxCacheLossUsd: config.spend?.maxCacheLossUsd,
|
|
1717
|
+
};
|
|
1718
|
+
if (thresholds.maxUsd === undefined &&
|
|
1719
|
+
thresholds.maxDayUsd === undefined &&
|
|
1720
|
+
thresholds.maxCacheLossUsd === undefined) {
|
|
1721
|
+
throw new Error(t.watch.noThresholds());
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* A webhook is a new outbound surface, so it is checked before anything is
|
|
1725
|
+
* sent: credentials in a URL end up in logs and shell history, and an alert
|
|
1726
|
+
* carrying spend figures over plain http across a network is a leak the
|
|
1727
|
+
* operator did not ask for. Loopback is the exception, because pointing a
|
|
1728
|
+
* watcher at your own alerting daemon is the ordinary case.
|
|
1729
|
+
*/
|
|
1730
|
+
const webhookRaw = stringFlag(args, 'webhook');
|
|
1731
|
+
let webhook = null;
|
|
1732
|
+
if (webhookRaw !== undefined) {
|
|
1733
|
+
const checked = checkWebhook(webhookRaw);
|
|
1734
|
+
if (!checked.ok)
|
|
1735
|
+
throw new Error(t.watch.badWebhook(checked.reason));
|
|
1736
|
+
webhook = checked.url;
|
|
1737
|
+
}
|
|
1738
|
+
const intervalRaw = stringFlag(args, 'interval');
|
|
1739
|
+
const once = boolFlag(args, 'once') || intervalRaw === undefined;
|
|
1740
|
+
let intervalMs = 0;
|
|
1741
|
+
if (!once) {
|
|
1742
|
+
const match = /^(\d+)(m|h)$/.exec(intervalRaw);
|
|
1743
|
+
const amount = match === null ? NaN : Number(match[1]);
|
|
1744
|
+
intervalMs = match?.[2] === 'h' ? amount * 3_600_000 : amount * 60_000;
|
|
1745
|
+
// Usage APIs are rate limited, and a tight loop is a way to get somebody's
|
|
1746
|
+
// key throttled by a tool that was supposed to save them money.
|
|
1747
|
+
if (!Number.isFinite(intervalMs) || intervalMs < 5 * 60_000) {
|
|
1748
|
+
throw new Error(t.watch.intervalTooTight());
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
const cycle = async () => {
|
|
1752
|
+
const state = await readWatchState(root);
|
|
1753
|
+
const nowMs = Date.now();
|
|
1754
|
+
/**
|
|
1755
|
+
* Where the measurements come from: a saved payload when one is named
|
|
1756
|
+
* (which is how this is tested and how an air-gapped run works), and the
|
|
1757
|
+
* store otherwise. A cycle that found nothing to measure says so — a
|
|
1758
|
+
* watcher over nothing is a green light nobody earned.
|
|
1759
|
+
*/
|
|
1760
|
+
const payloadPath = stringFlag(args, 'payload');
|
|
1761
|
+
let pull;
|
|
1762
|
+
if (payloadPath !== undefined) {
|
|
1763
|
+
pull = normalizeAnthropicUsage(JSON.parse(await readFile(payloadPath, 'utf8')));
|
|
1764
|
+
}
|
|
1765
|
+
else {
|
|
1766
|
+
const { resolved } = await readStore(root);
|
|
1767
|
+
if (resolved.records.length === 0)
|
|
1768
|
+
throw new Error(t.watch.nothingToWatch(STORE_DIR));
|
|
1769
|
+
pull = {
|
|
1770
|
+
provider: 'store',
|
|
1771
|
+
granularity: 'bucketed',
|
|
1772
|
+
buckets: bucketsFromRecords(resolved.records),
|
|
1773
|
+
window: null,
|
|
1774
|
+
gaps: [],
|
|
1775
|
+
unavailable: [],
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
const report = bucketedProfile(pull, { catalogue: pricing });
|
|
1779
|
+
const cache = bucketedCacheEconomics(report);
|
|
1780
|
+
const result = evaluateWatch({
|
|
1781
|
+
report,
|
|
1782
|
+
thresholds,
|
|
1783
|
+
cacheDeltaUsd: cache.verdict === 'no-cache' ? undefined : cache.deltaUsd,
|
|
1784
|
+
nowMs,
|
|
1785
|
+
lastCoveredToMs: state?.lastCoveredToMs ?? undefined,
|
|
1786
|
+
alreadyFired: new Set(Object.keys(state?.fired ?? {})),
|
|
1787
|
+
});
|
|
1788
|
+
if (asJson) {
|
|
1789
|
+
console.log(JSON.stringify({ schemaVersion: 1, firedAtMs: nowMs, ...result }, null, 2));
|
|
1790
|
+
}
|
|
1791
|
+
else {
|
|
1792
|
+
if (result.gap !== null) {
|
|
1793
|
+
console.log(c.yellow(wrap(t.watch.gap(day(result.gap.fromMs), day(result.gap.toMs)), 76, ' ')));
|
|
1794
|
+
}
|
|
1795
|
+
for (const crossing of result.crossings) {
|
|
1796
|
+
console.log(c.red(wrap(t.watch.crossed(crossing.gate, formatUsd(crossing.measuredUsd), formatUsd(crossing.limitUsd), crossing.day), 76, ' ')));
|
|
1797
|
+
}
|
|
1798
|
+
for (const abstention of result.abstentions) {
|
|
1799
|
+
console.log(c.dim(wrap(t.watch.notJudgeable(abstention.gate, abstention.reason, abstention.detail === null
|
|
1800
|
+
? null
|
|
1801
|
+
: `${Math.round((abstention.detail.coveredMs / abstention.detail.neededMs) * 100)}%`), 76, ' ')));
|
|
1802
|
+
}
|
|
1803
|
+
for (const still of result.suppressed) {
|
|
1804
|
+
console.log(c.yellow(wrap(t.watch.stillOver(still.gate, formatUsd(still.measuredUsd), formatUsd(still.limitUsd), still.day), 76, ' ')));
|
|
1805
|
+
}
|
|
1806
|
+
if (result.crossings.length === 0 &&
|
|
1807
|
+
result.suppressed.length === 0 &&
|
|
1808
|
+
result.abstentions.length === 0) {
|
|
1809
|
+
console.log(c.green(wrap(t.watch.allWithin(n(Object.keys(thresholds).filter((k) => thresholds[k] !== undefined).length)), 76, ' ')));
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
if (webhook !== null && result.crossings.length > 0) {
|
|
1813
|
+
const sent = await postWebhook(webhook, {
|
|
1814
|
+
schemaVersion: 1,
|
|
1815
|
+
firedAtMs: nowMs,
|
|
1816
|
+
crossings: result.crossings,
|
|
1817
|
+
});
|
|
1818
|
+
if (!sent.ok) {
|
|
1819
|
+
// Reported and swallowed: the exit code and the event already carried
|
|
1820
|
+
// the crossing, and losing those because a receiver is down would make
|
|
1821
|
+
// the quietest failure the loudest one.
|
|
1822
|
+
console.error(c.yellow(t.watch.webhookFailed(sent.status === null ? sent.error ?? '' : String(sent.status))));
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
const fired = { ...(state?.fired ?? {}) };
|
|
1826
|
+
for (const crossing of result.crossings)
|
|
1827
|
+
fired[firedKey(crossing.gate, crossing.day)] = nowMs;
|
|
1828
|
+
await writeWatchState(root, {
|
|
1829
|
+
v: WATCH_STATE_VERSION,
|
|
1830
|
+
lastCycleMs: nowMs,
|
|
1831
|
+
lastCoveredToMs: report.span?.toMs ?? state?.lastCoveredToMs ?? null,
|
|
1832
|
+
fired,
|
|
1833
|
+
});
|
|
1834
|
+
return result.crossings.length + result.suppressed.length;
|
|
1835
|
+
};
|
|
1836
|
+
const crossed = await cycle();
|
|
1837
|
+
// Still over is still a failure: only the alert was already sent.
|
|
1838
|
+
if (crossed > 0)
|
|
1839
|
+
process.exitCode = 1;
|
|
1840
|
+
if (once)
|
|
1841
|
+
return;
|
|
1842
|
+
console.log(c.dim(t.watch.watching(String(Math.round(intervalMs / 60_000)))));
|
|
1843
|
+
// The loop is the cycle in a timer and nothing more, so the primitive above
|
|
1844
|
+
// is the only thing that ever needs testing.
|
|
1845
|
+
for (;;) {
|
|
1846
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
1847
|
+
await cycle();
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1692
1850
|
/**
|
|
1693
1851
|
* `trazum store` — what is kept, and what a prune would take.
|
|
1694
1852
|
*
|
|
@@ -5468,6 +5626,9 @@ async function main() {
|
|
|
5468
5626
|
case 'store':
|
|
5469
5627
|
await commandStore(args, config, pricing, t);
|
|
5470
5628
|
break;
|
|
5629
|
+
case 'watch':
|
|
5630
|
+
await commandWatch(args, config, pricing, t);
|
|
5631
|
+
break;
|
|
5471
5632
|
case 'route':
|
|
5472
5633
|
await commandRoute(args, pricing, t);
|
|
5473
5634
|
break;
|