@caveman-ai/cli 1.3.1 → 1.3.4
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 +41 -1
- package/dist/agent-skills.generated.js +1 -1
- package/dist/agents.generated.js +388 -11
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +332 -51
- package/dist/cloud-client.mjs +22 -0
- package/dist/cloud-mcp.mjs +75 -0
- package/dist/index.js +3014 -273
- package/dist/native-hook-fast.js +2 -2
- package/dist/openclaw-provider-compat.js +111 -0
- package/dist/provider-routing.js +140 -0
- package/dist/proxy-fetch.js +3 -1
- package/dist/stats-cli.js +105 -0
- package/dist/surface.json +299 -0
- package/package.json +1 -1
package/dist/native-hook-fast.js
CHANGED
|
@@ -498,8 +498,8 @@ async function main() {
|
|
|
498
498
|
if (!response) {
|
|
499
499
|
// A dead loopback gateway PORT at prompt time is the SessionStart revive
|
|
500
500
|
// signal arriving mid-session: native routing still points this session's
|
|
501
|
-
// next request at the local proxy
|
|
502
|
-
//
|
|
501
|
+
// next request at the local proxy. Crashes or older proxies that idle-exit
|
|
502
|
+
// can leave a plain session without a way to restart it — the
|
|
503
503
|
// turn hard-fails with ConnectionRefused. Delegate this one event to the
|
|
504
504
|
// full CLI, which revives the proxy exactly like SessionStart (and records
|
|
505
505
|
// the event itself). The port probe — not the dead runtime socket — is the
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// OpenClaw v2026.8.2 (0965053fe6b9341776df147a6934b7485c60b5ca):
|
|
2
|
+
// packages/ai/src/transports/openai-completions-compat.ts
|
|
3
|
+
// packages/ai/src/transports/openai-responses-payload-policy.ts
|
|
4
|
+
// packages/ai/src/providers/anthropic.ts
|
|
5
|
+
// src/agents/provider-attribution.ts, src/config/types.models.ts
|
|
6
|
+
// This is a bounded config-overlay gate, not a copy of OpenClaw's private
|
|
7
|
+
// plugin metadata registry. Unknown host policy must remain in the host.
|
|
8
|
+
function object(value) {
|
|
9
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
10
|
+
? value : undefined;
|
|
11
|
+
}
|
|
12
|
+
function hostname(baseUrl) {
|
|
13
|
+
try {
|
|
14
|
+
return new URL(baseUrl).hostname.toLowerCase();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function nativeOpenAIHost(host) {
|
|
21
|
+
return host === "api.openai.com" || host === "chatgpt.com" || [
|
|
22
|
+
".openai.azure.com", ".cognitiveservices.azure.com", ".services.ai.azure.com", ".api.cognitive.microsoft.com",
|
|
23
|
+
].some(suffix => host.endsWith(suffix));
|
|
24
|
+
}
|
|
25
|
+
/** Overrides that change the final transport cannot be copied onto localhost. */
|
|
26
|
+
export function openClawRequestCompatibilityIssue(value) {
|
|
27
|
+
if (value === undefined)
|
|
28
|
+
return undefined;
|
|
29
|
+
const request = object(value);
|
|
30
|
+
if (!request)
|
|
31
|
+
return "its request transport overrides could not be resolved";
|
|
32
|
+
const auth = object(request.auth);
|
|
33
|
+
if (request.auth !== undefined && (!auth || auth.mode !== "provider-default")) {
|
|
34
|
+
return "its custom request authentication cannot be preserved through routing";
|
|
35
|
+
}
|
|
36
|
+
if (request.proxy !== undefined || request.tls !== undefined) {
|
|
37
|
+
return "its request proxy or TLS settings belong to the original endpoint";
|
|
38
|
+
}
|
|
39
|
+
if (request.allowPrivateNetwork === false) {
|
|
40
|
+
return "its request policy explicitly disallows the local proxy endpoint";
|
|
41
|
+
}
|
|
42
|
+
if (request.headers !== undefined && !object(request.headers)) {
|
|
43
|
+
return "its request headers could not be resolved";
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
/** Freeze public defaults only when their values do not require private metadata. */
|
|
48
|
+
export function preserveOpenClawProviderCompat(model) {
|
|
49
|
+
const host = hostname(model.baseUrl);
|
|
50
|
+
if (!host)
|
|
51
|
+
return { ok: false, reason: "its original endpoint compatibility could not be resolved" };
|
|
52
|
+
const compat = object(model.compat);
|
|
53
|
+
if (model.compat !== undefined && !compat) {
|
|
54
|
+
return { ok: false, reason: "its explicit model compatibility could not be resolved" };
|
|
55
|
+
}
|
|
56
|
+
if (model.api === "openai-completions") {
|
|
57
|
+
// Even a complete public compat object cannot override the private
|
|
58
|
+
// requiresNonEmptyUserOrAssistantMessage field or the native-route store
|
|
59
|
+
// wrapper. Calling the standalone resolver would guess active metadata.
|
|
60
|
+
return { ok: false, reason: "OpenClaw does not expose the resolved OpenAI Chat provider policy needed to preserve its payload defaults" };
|
|
61
|
+
}
|
|
62
|
+
// OpenClaw normalizes configured provider IDs before matching models and
|
|
63
|
+
// applying transport policy. Keep the config key intact, but compare the
|
|
64
|
+
// same identity its runtime sees (including for public provider defaults).
|
|
65
|
+
const provider = model.provider.trim().toLowerCase();
|
|
66
|
+
// Public model compat cannot freeze xAI's native compact-endpoint decision.
|
|
67
|
+
if (model.api === "openai-responses" && (provider === "xai" || provider === "x-ai") && host === "api.x.ai") {
|
|
68
|
+
return { ok: false, reason: "OpenClaw's native xAI compact-endpoint policy cannot be preserved by public compatibility settings" };
|
|
69
|
+
}
|
|
70
|
+
// These headers are generated after model resolution from endpoint metadata.
|
|
71
|
+
// Static config headers do not recover the installed runtime version, and
|
|
72
|
+
// OpenClaw's attribution defaults take precedence over configured values.
|
|
73
|
+
if ((provider === "openai" && nativeOpenAIHost(host)) ||
|
|
74
|
+
(provider === "openrouter" && (host === "openrouter.ai" || host.endsWith(".openrouter.ai"))) ||
|
|
75
|
+
(provider === "xai" && host === "api.x.ai") ||
|
|
76
|
+
host === "integrate.api.nvidia.com" || host === "generativelanguage.googleapis.com") {
|
|
77
|
+
return { ok: false, reason: "OpenClaw generates endpoint-specific request headers that this config overlay cannot preserve" };
|
|
78
|
+
}
|
|
79
|
+
if (model.api === "openai-responses") {
|
|
80
|
+
if (nativeOpenAIHost(host) || model.baseUrl.includes("api.openai.com")) {
|
|
81
|
+
return { ok: false, reason: "OpenClaw's native Responses cache, replay and service-tier policy cannot be preserved by public compatibility settings" };
|
|
82
|
+
}
|
|
83
|
+
// The bundled Responses payload resolver treats all other routes as
|
|
84
|
+
// non-native. xAI alone additionally defaults to an instructions field.
|
|
85
|
+
// Explicit switches prevent the transport host from re-deriving these
|
|
86
|
+
// public defaults after the endpoint changes to localhost.
|
|
87
|
+
return { ok: true, compat: {
|
|
88
|
+
...compat,
|
|
89
|
+
supportsStore: compat?.supportsStore ?? true,
|
|
90
|
+
supportsPromptCacheKey: compat?.supportsPromptCacheKey ?? false,
|
|
91
|
+
supportsInstructions: compat?.supportsInstructions ?? host === "api.x.ai",
|
|
92
|
+
} };
|
|
93
|
+
}
|
|
94
|
+
if (model.api === "anthropic-messages") {
|
|
95
|
+
if (provider === "anthropic" && host === "api.anthropic.com") {
|
|
96
|
+
return { ok: false, reason: "OpenClaw's native Anthropic fallback beta, service-tier and stream validation policy cannot be preserved by public compatibility settings" };
|
|
97
|
+
}
|
|
98
|
+
const fireworks = provider === "fireworks";
|
|
99
|
+
return { ok: true, compat: {
|
|
100
|
+
...compat,
|
|
101
|
+
supportsEagerToolInputStreaming: compat?.supportsEagerToolInputStreaming ?? !fireworks,
|
|
102
|
+
supportsLongCacheRetention: compat?.supportsLongCacheRetention ?? !fireworks,
|
|
103
|
+
sendSessionAffinityHeaders: compat?.sendSessionAffinityHeaders ??
|
|
104
|
+
(fireworks || (provider === "cloudflare-ai-gateway" && model.baseUrl.includes("anthropic"))),
|
|
105
|
+
} };
|
|
106
|
+
}
|
|
107
|
+
if (model.api === "google-generative-ai") {
|
|
108
|
+
return { ok: true, ...(compat ? { compat: { ...compat } } : {}) };
|
|
109
|
+
}
|
|
110
|
+
return { ok: false, reason: `OpenClaw's ${model.api} transport compatibility has not been verified` };
|
|
111
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
export const COMPAT_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
2
|
+
function endpoint(raw) {
|
|
3
|
+
if (!raw || /[\s?#]/.test(raw))
|
|
4
|
+
return undefined;
|
|
5
|
+
try {
|
|
6
|
+
const url = new URL(raw);
|
|
7
|
+
if (!['http:', 'https:'].includes(url.protocol) || !url.hostname
|
|
8
|
+
|| url.username || url.password || url.search || url.hash || url.pathname.includes("//"))
|
|
9
|
+
return undefined;
|
|
10
|
+
// Host SDKs disagree on repeated separators; refuse them rather than
|
|
11
|
+
// normalize a tenant path. Go adapters join decoded path segments.
|
|
12
|
+
// Do not claim equivalence for
|
|
13
|
+
// escaped separators, dot segments, or backslashes normalized by WHATWG URL.
|
|
14
|
+
if (/%|\\/.test(raw) || /(?:^|\/)\.{1,2}(?:\/|$)/.test(raw))
|
|
15
|
+
return undefined;
|
|
16
|
+
return url;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function publishedUpstreamsOf(raw) {
|
|
23
|
+
const out = Object.create(null);
|
|
24
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
25
|
+
return out;
|
|
26
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
27
|
+
if (!COMPAT_NAME_RE.test(name))
|
|
28
|
+
continue;
|
|
29
|
+
// Retain an invalid mount as unavailable; it must not fall through to a
|
|
30
|
+
// same-named native provider after its credential-bearing URL is omitted.
|
|
31
|
+
out[name] = typeof value === 'string' && endpoint(value) ? value : '';
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
function append(base, path) {
|
|
36
|
+
return base.origin + base.pathname.replace(/\/+$/, '') + path;
|
|
37
|
+
}
|
|
38
|
+
function compatTarget(base, path) {
|
|
39
|
+
const leftPath = base.pathname.replace(/^\/+|\/+$/g, '');
|
|
40
|
+
const rightPath = path.replace(/^\/+|\/+$/g, '');
|
|
41
|
+
const left = leftPath ? leftPath.split('/') : [];
|
|
42
|
+
const right = rightPath ? rightPath.split('/') : [];
|
|
43
|
+
let overlap = Math.min(left.length, right.length);
|
|
44
|
+
while (overlap > 0 && left.slice(-overlap).join('/') !== right.slice(0, overlap).join('/'))
|
|
45
|
+
overlap--;
|
|
46
|
+
return base.origin + '/' + [...left, ...right.slice(overlap)].join('/');
|
|
47
|
+
}
|
|
48
|
+
export function verifiedProviderRoute(gateway, api, provider, originalBaseUrl, published) {
|
|
49
|
+
const original = endpoint(originalBaseUrl);
|
|
50
|
+
if (!original || !endpoint(gateway))
|
|
51
|
+
return undefined;
|
|
52
|
+
const family = api === 'anthropic-messages' ? 'anthropic'
|
|
53
|
+
: api === 'openai-completions' || api === 'openai-responses' ? 'openai'
|
|
54
|
+
: api === 'google-generative-ai' ? 'gemini' : undefined;
|
|
55
|
+
if (!family)
|
|
56
|
+
return undefined;
|
|
57
|
+
const operation = api === 'anthropic-messages' ? '/v1/messages'
|
|
58
|
+
: api === 'openai-completions' ? '/chat/completions'
|
|
59
|
+
: api === 'openai-responses' ? '/responses' : '/models/caveman-route-proof:streamGenerateContent';
|
|
60
|
+
const expected = append(original, operation);
|
|
61
|
+
const mount = COMPAT_NAME_RE.test(provider) && published?.compat_upstreams
|
|
62
|
+
&& Object.hasOwn(published.compat_upstreams, provider) ? published.compat_upstreams[provider] : undefined;
|
|
63
|
+
if (mount !== undefined) {
|
|
64
|
+
const upstream = endpoint(mount);
|
|
65
|
+
if (!upstream || family === 'gemini')
|
|
66
|
+
return undefined;
|
|
67
|
+
const suffix = family === 'openai' ? '/v1' : '';
|
|
68
|
+
if (compatTarget(upstream, suffix + operation) !== expected)
|
|
69
|
+
return undefined;
|
|
70
|
+
return gateway.replace(/\/+$/, '') + `/compat/${provider}${suffix}`;
|
|
71
|
+
}
|
|
72
|
+
const upstream = endpoint(published?.provider_upstreams?.[family]);
|
|
73
|
+
if (!upstream)
|
|
74
|
+
return undefined;
|
|
75
|
+
const versions = family === 'gemini' ? ['/v1beta', '/v1'] : [family === 'openai' ? '/v1' : ''];
|
|
76
|
+
for (const version of versions) {
|
|
77
|
+
if (append(upstream, version + operation) === expected) {
|
|
78
|
+
return gateway.replace(/\/+$/, '') + `/${family}${version}`;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
// This is the gateway's ordinary end-to-end header contract for these three
|
|
84
|
+
// wire protocols. Additional mount headers require explicit operator config;
|
|
85
|
+
// preserving them in an overlay alone does not make the proxy forward them.
|
|
86
|
+
const COPIED_HEADERS = ["content-type", "content-encoding", "accept", "accept-encoding", "idempotency-key", "openai-organization", "openai-project", "session_id", "x-session-id", "x-client-request-id", "x-session-affinity", "anthropic-version", "anthropic-beta", "api-version", "user-agent"];
|
|
87
|
+
const COMPAT_HEADERS = {
|
|
88
|
+
openrouter: ["http-referer", "x-openrouter-title", "x-openrouter-categories"],
|
|
89
|
+
nvidia: ["x-billing-invoke-origin"],
|
|
90
|
+
opencode: ["x-opencode-session", "x-opencode-client", "x-opencode-project", "x-opencode-request"],
|
|
91
|
+
"opencode-go": ["x-opencode-session", "x-opencode-client", "x-opencode-project", "x-opencode-request"],
|
|
92
|
+
};
|
|
93
|
+
export function publishedForwardHeadersOf(raw) {
|
|
94
|
+
const out = Object.create(null);
|
|
95
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
96
|
+
return out;
|
|
97
|
+
for (const [name, values] of Object.entries(raw)) {
|
|
98
|
+
if (COMPAT_NAME_RE.test(name) && Array.isArray(values))
|
|
99
|
+
out[name] = values.filter((v) => typeof v === "string").map(v => v.toLowerCase());
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
export function unforwardedProviderHeaders(api, provider, headers, published) {
|
|
104
|
+
if (headers == null)
|
|
105
|
+
return [];
|
|
106
|
+
if (typeof headers !== "object" || Array.isArray(headers))
|
|
107
|
+
return ["invalid header configuration"];
|
|
108
|
+
const allowed = new Set(COPIED_HEADERS);
|
|
109
|
+
if (api === "openai-completions" || api === "openai-responses")
|
|
110
|
+
allowed.add("authorization");
|
|
111
|
+
if (api === "anthropic-messages") {
|
|
112
|
+
allowed.add("authorization");
|
|
113
|
+
allowed.add("x-api-key");
|
|
114
|
+
}
|
|
115
|
+
if (api === "google-generative-ai") {
|
|
116
|
+
allowed.add("authorization");
|
|
117
|
+
allowed.add("x-goog-api-key");
|
|
118
|
+
allowed.add("x-goog-user-project");
|
|
119
|
+
}
|
|
120
|
+
if (published?.compat_upstreams && Object.hasOwn(published.compat_upstreams, provider)) {
|
|
121
|
+
for (const name of published.compat_forward_headers?.[provider] ?? [])
|
|
122
|
+
allowed.add(name.toLowerCase());
|
|
123
|
+
if (Object.hasOwn(COMPAT_HEADERS, provider))
|
|
124
|
+
for (const name of COMPAT_HEADERS[provider])
|
|
125
|
+
allowed.add(name);
|
|
126
|
+
}
|
|
127
|
+
return Object.entries(headers).filter(([name, value]) => {
|
|
128
|
+
if (value === undefined)
|
|
129
|
+
return false;
|
|
130
|
+
const lower = name.toLowerCase();
|
|
131
|
+
// SDK custom headers override their generated Authorization verbatim.
|
|
132
|
+
// The proxy's credential mapper supports Bearer on these routes, so Basic,
|
|
133
|
+
// Digest, empty, or explicitly suppressed auth cannot be certified by name.
|
|
134
|
+
if (lower === "authorization")
|
|
135
|
+
return typeof value !== "string" || !/^Bearer +\S+$/i.test(value.trim());
|
|
136
|
+
if (["x-api-key", "x-goog-api-key"].includes(lower) && (typeof value !== "string" || !value.trim()))
|
|
137
|
+
return true;
|
|
138
|
+
return value !== null && !allowed.has(lower);
|
|
139
|
+
}).map(([name]) => name).sort();
|
|
140
|
+
}
|
package/dist/proxy-fetch.js
CHANGED
|
@@ -17,6 +17,7 @@ import { request as httpRequest } from "node:http";
|
|
|
17
17
|
import { request as httpsRequest } from "node:https";
|
|
18
18
|
import { Readable } from "node:stream";
|
|
19
19
|
import { connect as tlsConnect } from "node:tls";
|
|
20
|
+
import { isIP } from "node:net";
|
|
20
21
|
/** Redirect hops to follow before giving up, matching the fetch spec's limit. */
|
|
21
22
|
const MAX_REDIRECTS = 20;
|
|
22
23
|
const DEFAULT_PORTS = { "http:": "80", "https:": "443" };
|
|
@@ -215,7 +216,8 @@ function sendThroughProxy(request, proxy) {
|
|
|
215
216
|
method,
|
|
216
217
|
path: `${url.pathname}${url.search}`,
|
|
217
218
|
headers: { ...headers, host: url.host },
|
|
218
|
-
|
|
219
|
+
// Node 26 rejects an IP literal as SNI servername; omit it for IP targets.
|
|
220
|
+
createConnection: () => tlsConnect({ socket, host: url.hostname, servername: isIP(url.hostname) ? undefined : url.hostname }),
|
|
219
221
|
}, httpsRequest);
|
|
220
222
|
})
|
|
221
223
|
.catch(reject);
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// The proxy owns accounting and HTML. This module only parses the public
|
|
2
|
+
// command and renders its already-calculated report; it never recomputes money.
|
|
3
|
+
export const STATS_USAGE = "stats [--json] [--days N | --all-time] [--provider ID] [--model ID] [--agent ID] [--auth MODE] [--plain | --open] [--out PATH]";
|
|
4
|
+
export const STATS_HELP = `caveman stats — your local token and cost report
|
|
5
|
+
|
|
6
|
+
caveman stats summary and visual dashboard
|
|
7
|
+
caveman stats --days 7 last 7 UTC calendar days
|
|
8
|
+
caveman stats --all-time all recorded history
|
|
9
|
+
caveman stats --provider openai one provider
|
|
10
|
+
caveman stats --model gpt-5.6 one recorded model
|
|
11
|
+
caveman stats --auth subscription
|
|
12
|
+
caveman stats --json complete machine-readable report
|
|
13
|
+
caveman stats --plain terminal summary, no browser
|
|
14
|
+
caveman stats --out savings.html --open
|
|
15
|
+
|
|
16
|
+
Filters: --provider, --model, --agent and --auth use exact recorded values.
|
|
17
|
+
Days: 30 by default; 1–3660, or --all-time. All dates use UTC.
|
|
18
|
+
The dashboard is a private, offline HTML snapshot. Run stats again to refresh.
|
|
19
|
+
API cost estimates and subscription API equivalents are separate. Neither
|
|
20
|
+
proves an invoice reduction. Unknown models and billing modes stay unpriced.
|
|
21
|
+
`;
|
|
22
|
+
export function parseStatsOptions(argv) {
|
|
23
|
+
const result = { json: false, plain: false, open: false, filters: [] };
|
|
24
|
+
const seen = new Set();
|
|
25
|
+
const valueFlags = new Set(["--days", "--provider", "--model", "--agent", "--auth", "--out"]);
|
|
26
|
+
for (let i = 0; i < argv.length; i++) {
|
|
27
|
+
const arg = argv[i];
|
|
28
|
+
if (seen.has(arg))
|
|
29
|
+
throw new Error(`duplicate ${arg}`);
|
|
30
|
+
seen.add(arg);
|
|
31
|
+
if (valueFlags.has(arg)) {
|
|
32
|
+
const value = argv[++i];
|
|
33
|
+
if (!value || value.startsWith("--") || /[\u0000-\u001f\u007f]/u.test(value))
|
|
34
|
+
throw new Error(`${arg} requires a value`);
|
|
35
|
+
if (arg === "--days" && (!/^\d+$/u.test(value) || Number(value) < 1 || Number(value) > 3660)) {
|
|
36
|
+
throw new Error("--days must be an integer from 1 to 3660");
|
|
37
|
+
}
|
|
38
|
+
if (arg === "--out")
|
|
39
|
+
result.out = value;
|
|
40
|
+
else
|
|
41
|
+
result.filters.push(arg, value);
|
|
42
|
+
}
|
|
43
|
+
else if (arg === "--json")
|
|
44
|
+
result.json = true;
|
|
45
|
+
else if (arg === "--plain" || arg === "--no-open")
|
|
46
|
+
result.plain = true;
|
|
47
|
+
else if (arg === "--open")
|
|
48
|
+
result.open = true;
|
|
49
|
+
else if (arg === "--all-time")
|
|
50
|
+
result.filters.push("--days", "0");
|
|
51
|
+
else
|
|
52
|
+
throw new Error(`unknown option ${arg}`);
|
|
53
|
+
}
|
|
54
|
+
if (seen.has("--days") && seen.has("--all-time"))
|
|
55
|
+
throw new Error("choose --days or --all-time");
|
|
56
|
+
if (result.plain && result.open)
|
|
57
|
+
throw new Error("choose --plain or --open");
|
|
58
|
+
if (result.json && result.open)
|
|
59
|
+
throw new Error("--json cannot open a browser");
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
const count = (n) => Number.isFinite(n) ? n.toLocaleString("en-US") : "unknown";
|
|
63
|
+
const money = (n) => typeof n === "number" && Number.isFinite(n)
|
|
64
|
+
? `${n < 0 ? "−" : ""}$${Math.abs(n).toFixed(Math.abs(n) > 0 && Math.abs(n) < 0.01 ? 6 : 4)}`
|
|
65
|
+
: "unavailable";
|
|
66
|
+
const label = (value) => value.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/gu, "").replace(/[\u0000-\u001f\u007f-\u009f]/gu, "");
|
|
67
|
+
export function renderStatsSummary(report) {
|
|
68
|
+
const m = report.totals;
|
|
69
|
+
const usageCount = (n) => {
|
|
70
|
+
if (m.complete_usage_requests === 0 && n === 0)
|
|
71
|
+
return "unknown";
|
|
72
|
+
return `${count(n)}${m.partial_usage_requests > 0 ? " observed" : ""}`;
|
|
73
|
+
};
|
|
74
|
+
const lines = [
|
|
75
|
+
"Caveman Stats",
|
|
76
|
+
`${report.window.lifetime ? "All recorded history" : `Last ${report.window.days} days`} · UTC · local estimates`,
|
|
77
|
+
"",
|
|
78
|
+
];
|
|
79
|
+
if (m.requests === 0) {
|
|
80
|
+
lines.push("No routed requests in this window.", "Run an agent through Caveman, then run caveman stats again.");
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
const reduction = m.measured_requests > 0
|
|
84
|
+
? `${count(m.saved_tokens)} tokens${m.before_tokens > 0 ? ` (${(100 * m.saved_tokens / m.before_tokens).toFixed(1)}%)` : ""}`
|
|
85
|
+
: "unavailable — no request comparisons recorded yet";
|
|
86
|
+
lines.push(`Input reduction estimate ${reduction}`, `Compared request tokens ${m.measured_requests > 0 ? `${count(m.before_tokens)} original / ${count(m.after_tokens)} delivered` : "unavailable"}`, `API input cost estimate ${money(m.api_savings_usd)} reduction · ${count(m.api_savings_requests)} priced requests`, `Subscription equivalent ${money(m.api_equivalent_savings_usd)} at API rates · ${count(m.equivalent_savings_requests)} priced requests`, `API spend estimate ${money(m.api_spend_usd)} · ${count(m.api_spend_requests)} priced requests`, "", `Requests ${count(m.requests)} total / ${count(m.successful_requests)} successful / ${count(m.failed_requests)} failed`, `Provider usage ${usageCount(m.input_tokens)} input / ${usageCount(m.output_tokens)} output`, `Cache usage ${usageCount(m.cache_read_tokens)} read / ${usageCount(m.cache_write_tokens)} written`, `Usage coverage ${count(m.complete_usage_requests)} complete / ${count(m.partial_usage_requests)} partial or unavailable`, `Comparison coverage ${count(m.measured_requests)} measured / ${count(m.unmeasured_requests)} unavailable`);
|
|
87
|
+
if (m.expanded_requests > 0)
|
|
88
|
+
lines.push(`Overhead regressions ${count(m.expanded_requests)} requests (included in net delta)`);
|
|
89
|
+
if (m.legacy_requests > 0)
|
|
90
|
+
lines.push(`Legacy segment reductions ${count(m.legacy_saved_tokens)} tokens / ${count(m.legacy_requests)} requests (separate)`);
|
|
91
|
+
if (m.unknown_auth_requests > 0)
|
|
92
|
+
lines.push(`Unknown billing ${count(m.unknown_auth_requests)} requests (excluded from money totals)`);
|
|
93
|
+
if (report.providers?.length) {
|
|
94
|
+
lines.push("", "By provider");
|
|
95
|
+
for (const p of report.providers) {
|
|
96
|
+
lines.push(` ${label(p.provider)}: ${count(p.requests)} requests · ${p.measured_requests > 0 ? count(p.saved_tokens) : "unknown"} tokens · API ${money(p.api_savings_usd)} · subscription equivalent ${money(p.api_equivalent_savings_usd)}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
lines.push("", "API estimates assume the observed cache mix. Subscription equivalents do not reduce your bill.");
|
|
100
|
+
}
|
|
101
|
+
if (report.report_path)
|
|
102
|
+
lines.push("", `Dashboard: ${report.report_path}`);
|
|
103
|
+
lines.push("Full breakdown: caveman stats --json");
|
|
104
|
+
return `${lines.join("\n")}\n`;
|
|
105
|
+
}
|