context-doctor 0.48.0 → 0.49.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 +15 -14
- package/dist/abclaude.js +1 -1
- package/dist/budget.d.ts +5 -2
- package/dist/budget.js +21 -7
- package/dist/cache.js +3 -3
- package/dist/cachemisses.d.ts +3 -0
- package/dist/cachemisses.js +8 -0
- package/dist/cachettl.js +6 -2
- package/dist/ccost.d.ts +160 -0
- package/dist/ccost.js +304 -0
- package/dist/cli.js +135 -32
- package/dist/cline.d.ts +41 -0
- package/dist/cline.js +174 -0
- package/dist/coldresume.d.ts +11 -0
- package/dist/coldresume.js +3 -3
- package/dist/coldreturns.d.ts +145 -0
- package/dist/coldreturns.js +282 -0
- package/dist/compactcost.d.ts +10 -4
- package/dist/compactcost.js +12 -7
- package/dist/compactwindow.js +2 -2
- package/dist/copilotusage.d.ts +78 -0
- package/dist/copilotusage.js +193 -0
- package/dist/doctor.d.ts +6 -0
- package/dist/doctor.js +17 -4
- package/dist/fix.d.ts +28 -2
- package/dist/fix.js +49 -5
- package/dist/limits.d.ts +222 -14
- package/dist/limits.js +684 -33
- package/dist/mcp.js +1 -1
- package/dist/mcpdefer.d.ts +47 -0
- package/dist/mcpdefer.js +91 -0
- package/dist/mod/api.d.ts +72 -2
- package/dist/mod/api.js +5 -1
- package/dist/mod/logic.d.ts +281 -0
- package/dist/mod/logic.js +336 -0
- package/dist/mod/register.d.ts +35 -2
- package/dist/mod/register.js +283 -6
- package/dist/modmeasure.d.ts +6 -4
- package/dist/modmeasure.js +8 -4
- package/dist/opencode.d.ts +57 -0
- package/dist/opencode.js +234 -0
- package/dist/orgrates.d.ts +7 -0
- package/dist/orgrates.js +19 -0
- package/dist/overhead.d.ts +3 -0
- package/dist/overhead.js +5 -1
- package/dist/pricing.d.ts +59 -2
- package/dist/pricing.js +125 -10
- package/dist/proxy.d.ts +8 -1
- package/dist/proxy.js +13 -1
- package/dist/savings.d.ts +5 -1
- package/dist/savings.js +11 -5
- package/dist/scan.d.ts +3 -1
- package/dist/scan.js +8 -1
- package/dist/sessionprice.d.ts +5 -0
- package/dist/sessionprice.js +5 -1
- package/dist/spend.d.ts +86 -3
- package/dist/spend.js +240 -23
- package/dist/spendplace.d.ts +40 -0
- package/dist/spendplace.js +93 -0
- package/dist/spendteam.d.ts +160 -0
- package/dist/spendteam.js +286 -0
- package/dist/starts.d.ts +106 -0
- package/dist/starts.js +406 -0
- package/dist/statusline.d.ts +2 -2
- package/dist/statusline.js +2 -2
- package/dist/subagentmodel.js +9 -7
- package/dist/subagentpay.d.ts +31 -2
- package/dist/subagentpay.js +232 -68
- package/dist/subagents.js +3 -3
- package/dist/tasks.js +3 -2
- package/dist/tooloutput.js +5 -5
- package/dist/usagepane.d.ts +77 -0
- package/dist/usagepane.js +287 -0
- package/package.json +1 -1
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `spend --export` and `spend merge`: a team's spend without a dashboard.
|
|
3
|
+
*
|
|
4
|
+
* Each developer runs `spend --export` and puts the file in a folder the
|
|
5
|
+
* team already shares (a drive, a repository); `spend merge <folder>` adds
|
|
6
|
+
* the files up. Nothing is sent anywhere: the files go where people put them.
|
|
7
|
+
*
|
|
8
|
+
* An export holds totals only: per local day, tool, model and repository
|
|
9
|
+
* (and branch, with `--by branch`), the requests, tokens and dollars. No
|
|
10
|
+
* prompt, no path, no project or session name: a repository is its folder's
|
|
11
|
+
* base name, or with `--anonymize` a hash of it (the same name hashes the
|
|
12
|
+
* same on every machine, so merged files still line up). The developer is a
|
|
13
|
+
* label the person chooses (`--as`), by default their OS user name.
|
|
14
|
+
*
|
|
15
|
+
* Merging: a developer's files that cover the same day (an export run twice)
|
|
16
|
+
* count that day once, from the newest file. Developers are listed in
|
|
17
|
+
* alphabetical order, not by spend: the per-repository and per-tool views
|
|
18
|
+
* are the ones meant for decisions.
|
|
19
|
+
*/
|
|
20
|
+
import { type SpendItem, type Tool } from "./spend.js";
|
|
21
|
+
export declare const EXPORT_KIND = "context-doctor spend export";
|
|
22
|
+
export declare const EXPORT_VERSION = 1;
|
|
23
|
+
export interface ExportRow {
|
|
24
|
+
/** A local day, "YYYY-MM-DD". */
|
|
25
|
+
day: string;
|
|
26
|
+
tool: Tool;
|
|
27
|
+
model: string;
|
|
28
|
+
repo: string;
|
|
29
|
+
branch?: string;
|
|
30
|
+
requests: number;
|
|
31
|
+
/** At list price; requests with no list price are counted in `unpriced`, not in it. */
|
|
32
|
+
usd: number;
|
|
33
|
+
unpriced: number;
|
|
34
|
+
tokens: {
|
|
35
|
+
input: number;
|
|
36
|
+
read: number;
|
|
37
|
+
write: number;
|
|
38
|
+
output: number;
|
|
39
|
+
};
|
|
40
|
+
/** Copilot CLI's AI credits and premium requests, as it counted them. */
|
|
41
|
+
credits?: number;
|
|
42
|
+
premium?: number;
|
|
43
|
+
}
|
|
44
|
+
export interface SpendExport {
|
|
45
|
+
kind: typeof EXPORT_KIND;
|
|
46
|
+
version: number;
|
|
47
|
+
developer: string;
|
|
48
|
+
exportedAt: string;
|
|
49
|
+
days: number;
|
|
50
|
+
/** The local days the export covers, first and last: a day in it with no row cost nothing. */
|
|
51
|
+
from: string;
|
|
52
|
+
to: string;
|
|
53
|
+
basis: string;
|
|
54
|
+
anonymized: boolean;
|
|
55
|
+
byBranch: boolean;
|
|
56
|
+
rows: ExportRow[];
|
|
57
|
+
}
|
|
58
|
+
/** The OS user name, the default developer label. */
|
|
59
|
+
export declare function defaultDeveloper(): string;
|
|
60
|
+
/** "repo-" or "branch-" and 10 hex: the same name, the same hash, on every machine. */
|
|
61
|
+
export declare function anonymize(kind: "repo" | "branch", name: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* An export of `items` (collectSpend's, with `by: "repo"` or `"branch"`).
|
|
64
|
+
* A request's repository is its folder's (spendplace.ts); Gemini CLI, which
|
|
65
|
+
* records no folder, keeps its project's name (a folder's base name or a
|
|
66
|
+
* hash Gemini made); anything else with no folder is "(no folder)".
|
|
67
|
+
*/
|
|
68
|
+
export declare function buildExport(items: SpendItem[], o: {
|
|
69
|
+
developer: string;
|
|
70
|
+
days: number;
|
|
71
|
+
since: number;
|
|
72
|
+
until: number;
|
|
73
|
+
basis: string;
|
|
74
|
+
anonymize?: boolean;
|
|
75
|
+
branches?: boolean;
|
|
76
|
+
now?: number;
|
|
77
|
+
}): SpendExport;
|
|
78
|
+
/** A file name for an export: the developer's label made safe, and its last day. */
|
|
79
|
+
export declare function exportFileName(e: SpendExport): string;
|
|
80
|
+
/** What `spend --export` says after writing the file. */
|
|
81
|
+
export declare function renderExportDone(e: SpendExport, file: string): string;
|
|
82
|
+
/** An export file's content, or why it is not one. */
|
|
83
|
+
export declare function parseExport(text: string): SpendExport | string;
|
|
84
|
+
/** Every export in `folder` (its own files, not its subfolders), and the files that are not. */
|
|
85
|
+
export declare function readExports(folder: string): {
|
|
86
|
+
exports: Array<{
|
|
87
|
+
file: string;
|
|
88
|
+
data: SpendExport;
|
|
89
|
+
}>;
|
|
90
|
+
skipped: Array<{
|
|
91
|
+
file: string;
|
|
92
|
+
reason: string;
|
|
93
|
+
}>;
|
|
94
|
+
};
|
|
95
|
+
export interface MergeRow {
|
|
96
|
+
name: string;
|
|
97
|
+
usd: number;
|
|
98
|
+
requests: number;
|
|
99
|
+
unpriced: number;
|
|
100
|
+
tools?: Tool[];
|
|
101
|
+
}
|
|
102
|
+
export interface MergeReport {
|
|
103
|
+
files: number;
|
|
104
|
+
developers: Array<MergeRow & {
|
|
105
|
+
from: string;
|
|
106
|
+
to: string;
|
|
107
|
+
files: number;
|
|
108
|
+
}>;
|
|
109
|
+
from: string;
|
|
110
|
+
to: string;
|
|
111
|
+
usd: number;
|
|
112
|
+
requests: number;
|
|
113
|
+
unpriced: number;
|
|
114
|
+
tokens: {
|
|
115
|
+
input: number;
|
|
116
|
+
read: number;
|
|
117
|
+
write: number;
|
|
118
|
+
output: number;
|
|
119
|
+
};
|
|
120
|
+
repos: MergeRow[];
|
|
121
|
+
tools: MergeRow[];
|
|
122
|
+
models: MergeRow[];
|
|
123
|
+
branches?: MergeRow[];
|
|
124
|
+
daily: Array<{
|
|
125
|
+
day: string;
|
|
126
|
+
usd: number;
|
|
127
|
+
}>;
|
|
128
|
+
/** Copilot CLI's AI credits and premium requests, as counted, across everyone. */
|
|
129
|
+
credits?: number;
|
|
130
|
+
premium?: number;
|
|
131
|
+
/** The month of the last day: what it has cost so far, the pace over the last (up to) 14 days, and the month at that pace. An estimate. */
|
|
132
|
+
forecast?: {
|
|
133
|
+
month: string;
|
|
134
|
+
soFar: number;
|
|
135
|
+
perDay: number;
|
|
136
|
+
paceDays: number;
|
|
137
|
+
daysLeft: number;
|
|
138
|
+
usd: number;
|
|
139
|
+
};
|
|
140
|
+
/** Developers whose files end before the last day: the days after count nothing for them. */
|
|
141
|
+
endsEarly: Array<{
|
|
142
|
+
developer: string;
|
|
143
|
+
to: string;
|
|
144
|
+
}>;
|
|
145
|
+
/** Days two of a developer's files both covered: counted once, from the newer file. */
|
|
146
|
+
overlaps: number;
|
|
147
|
+
bases: string[];
|
|
148
|
+
anonymized: boolean;
|
|
149
|
+
skipped: Array<{
|
|
150
|
+
file: string;
|
|
151
|
+
reason: string;
|
|
152
|
+
}>;
|
|
153
|
+
}
|
|
154
|
+
/** Add up exports: each developer's day once (their newest file that covers it), then by developer, repository, tool, model and day. */
|
|
155
|
+
export declare function mergeExports(exports: Array<{
|
|
156
|
+
file: string;
|
|
157
|
+
data: SpendExport;
|
|
158
|
+
}>, skipped?: MergeReport["skipped"]): MergeReport;
|
|
159
|
+
/** `spend merge`'s text, within 80 columns. `top`: rows per list. */
|
|
160
|
+
export declare function renderMerge(r: MergeReport, folder: string, top?: number): string;
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `spend --export` and `spend merge`: a team's spend without a dashboard.
|
|
3
|
+
*
|
|
4
|
+
* Each developer runs `spend --export` and puts the file in a folder the
|
|
5
|
+
* team already shares (a drive, a repository); `spend merge <folder>` adds
|
|
6
|
+
* the files up. Nothing is sent anywhere: the files go where people put them.
|
|
7
|
+
*
|
|
8
|
+
* An export holds totals only: per local day, tool, model and repository
|
|
9
|
+
* (and branch, with `--by branch`), the requests, tokens and dollars. No
|
|
10
|
+
* prompt, no path, no project or session name: a repository is its folder's
|
|
11
|
+
* base name, or with `--anonymize` a hash of it (the same name hashes the
|
|
12
|
+
* same on every machine, so merged files still line up). The developer is a
|
|
13
|
+
* label the person chooses (`--as`), by default their OS user name.
|
|
14
|
+
*
|
|
15
|
+
* Merging: a developer's files that cover the same day (an export run twice)
|
|
16
|
+
* count that day once, from the newest file. Developers are listed in
|
|
17
|
+
* alphabetical order, not by spend: the per-repository and per-tool views
|
|
18
|
+
* are the ones meant for decisions.
|
|
19
|
+
*/
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
22
|
+
import { userInfo } from "node:os";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
import { localDay, TOOL_NAME, TOOLS, usd } from "./spend.js";
|
|
25
|
+
import { formatTokens } from "./tokens.js";
|
|
26
|
+
export const EXPORT_KIND = "context-doctor spend export";
|
|
27
|
+
export const EXPORT_VERSION = 1;
|
|
28
|
+
/** The OS user name, the default developer label. */
|
|
29
|
+
export function defaultDeveloper() {
|
|
30
|
+
try {
|
|
31
|
+
const n = userInfo().username.trim();
|
|
32
|
+
if (n)
|
|
33
|
+
return n;
|
|
34
|
+
}
|
|
35
|
+
catch { /* none */ }
|
|
36
|
+
return process.env.USER || process.env.USERNAME || "me";
|
|
37
|
+
}
|
|
38
|
+
/** "repo-" or "branch-" and 10 hex: the same name, the same hash, on every machine. */
|
|
39
|
+
export function anonymize(kind, name) {
|
|
40
|
+
return `${kind}-${createHash("sha256").update(`context-doctor ${kind}\u0000${name}`).digest("hex").slice(0, 10)}`;
|
|
41
|
+
}
|
|
42
|
+
/** Names that say there is none, kept as they are under --anonymize. */
|
|
43
|
+
const NO_NAME = new Set(["(no folder)", "(home)"]);
|
|
44
|
+
/**
|
|
45
|
+
* An export of `items` (collectSpend's, with `by: "repo"` or `"branch"`).
|
|
46
|
+
* A request's repository is its folder's (spendplace.ts); Gemini CLI, which
|
|
47
|
+
* records no folder, keeps its project's name (a folder's base name or a
|
|
48
|
+
* hash Gemini made); anything else with no folder is "(no folder)".
|
|
49
|
+
*/
|
|
50
|
+
export function buildExport(items, o) {
|
|
51
|
+
const rows = new Map();
|
|
52
|
+
for (const it of items) {
|
|
53
|
+
let repo = it.root || it.cwd ? it.repo ?? "(no folder)" : it.tool === "gemini" ? it.project : "(no folder)";
|
|
54
|
+
let branch = o.branches ? it.branch : undefined;
|
|
55
|
+
if (o.anonymize) {
|
|
56
|
+
if (!NO_NAME.has(repo))
|
|
57
|
+
repo = anonymize("repo", repo);
|
|
58
|
+
if (branch)
|
|
59
|
+
branch = anonymize("branch", branch);
|
|
60
|
+
}
|
|
61
|
+
const model = it.model ?? "unknown";
|
|
62
|
+
const day = localDay(it.ts);
|
|
63
|
+
const k = [day, it.tool, model, repo, branch ?? ""].join("\u0000");
|
|
64
|
+
const r = rows.get(k) ?? rows.set(k, { day, tool: it.tool, model, repo, ...(branch ? { branch } : {}), requests: 0, usd: 0, unpriced: 0, tokens: { input: 0, read: 0, write: 0, output: 0 } }).get(k);
|
|
65
|
+
if (!it.iteration)
|
|
66
|
+
r.requests++; // an iteration a request's usage left out is billed, not a request of its own
|
|
67
|
+
r.usd += it.usd;
|
|
68
|
+
if (!it.priced)
|
|
69
|
+
r.unpriced++;
|
|
70
|
+
r.tokens.input += it.input;
|
|
71
|
+
r.tokens.read += it.read;
|
|
72
|
+
r.tokens.write += it.write;
|
|
73
|
+
r.tokens.output += it.output;
|
|
74
|
+
if (it.credits !== undefined)
|
|
75
|
+
r.credits = (r.credits ?? 0) + it.credits;
|
|
76
|
+
if (it.premium !== undefined)
|
|
77
|
+
r.premium = (r.premium ?? 0) + it.premium;
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
kind: EXPORT_KIND, version: EXPORT_VERSION, developer: o.developer, exportedAt: new Date(o.now ?? Date.now()).toISOString(),
|
|
81
|
+
days: o.days, from: localDay(o.since), to: localDay(o.until), basis: o.basis, anonymized: Boolean(o.anonymize), byBranch: Boolean(o.branches),
|
|
82
|
+
rows: [...rows.values()].sort((a, b) => a.day.localeCompare(b.day) || a.tool.localeCompare(b.tool) || b.usd - a.usd),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** A file name for an export: the developer's label made safe, and its last day. */
|
|
86
|
+
export function exportFileName(e) {
|
|
87
|
+
return `context-doctor-spend-${e.developer.replace(/[^A-Za-z0-9._-]+/g, "_").slice(0, 40) || "me"}-${e.to}.json`;
|
|
88
|
+
}
|
|
89
|
+
/** What `spend --export` says after writing the file. */
|
|
90
|
+
export function renderExportDone(e, file) {
|
|
91
|
+
const total = e.rows.reduce((n, r) => n + r.usd, 0), requests = e.rows.reduce((n, r) => n + r.requests, 0);
|
|
92
|
+
return [
|
|
93
|
+
`Wrote ${file}: ${usd(total)} over ${requests.toLocaleString("en-US")} requests, ${e.from} to ${e.to}, as ${e.developer}.`,
|
|
94
|
+
`It holds totals by day, tool, model and ${e.anonymized ? "hashed " : ""}repository${e.byBranch ? ` and ${e.anonymized ? "hashed " : ""}branch` : ""}: no prompt, path, project or session.`,
|
|
95
|
+
"Put it in a folder your team shares; context-doctor spend merge <folder> adds them up.",
|
|
96
|
+
].join("\n");
|
|
97
|
+
}
|
|
98
|
+
const isRow = (r) => r && typeof r === "object" && typeof r.day === "string" && /^\d{4}-\d{2}-\d{2}$/.test(r.day) && TOOLS.includes(r.tool) && typeof r.model === "string" && typeof r.repo === "string" &&
|
|
99
|
+
typeof r.requests === "number" && typeof r.usd === "number" && Number.isFinite(r.usd) && typeof r.unpriced === "number" && r.tokens && typeof r.tokens === "object";
|
|
100
|
+
/** An export file's content, or why it is not one. */
|
|
101
|
+
export function parseExport(text) {
|
|
102
|
+
let e;
|
|
103
|
+
try {
|
|
104
|
+
e = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return "not JSON";
|
|
108
|
+
}
|
|
109
|
+
if (e?.kind !== EXPORT_KIND)
|
|
110
|
+
return "not a context-doctor spend export";
|
|
111
|
+
if (e.version !== EXPORT_VERSION)
|
|
112
|
+
return `export version ${JSON.stringify(e.version)}, this context-doctor reads ${EXPORT_VERSION}`;
|
|
113
|
+
if (typeof e.developer !== "string" || !e.developer || typeof e.from !== "string" || typeof e.to !== "string" || !Array.isArray(e.rows))
|
|
114
|
+
return "missing its developer, days or rows";
|
|
115
|
+
if (!e.rows.every(isRow))
|
|
116
|
+
return "a row is not a spend total";
|
|
117
|
+
return e;
|
|
118
|
+
}
|
|
119
|
+
/** Every export in `folder` (its own files, not its subfolders), and the files that are not. */
|
|
120
|
+
export function readExports(folder) {
|
|
121
|
+
const exports = [], skipped = [];
|
|
122
|
+
for (const name of readdirSync(folder).sort()) {
|
|
123
|
+
if (!name.toLowerCase().endsWith(".json"))
|
|
124
|
+
continue;
|
|
125
|
+
let text;
|
|
126
|
+
try {
|
|
127
|
+
text = readFileSync(join(folder, name), "utf8");
|
|
128
|
+
}
|
|
129
|
+
catch (e) {
|
|
130
|
+
skipped.push({ file: name, reason: e.code === "EISDIR" ? "a folder" : "unreadable" });
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const r = parseExport(text);
|
|
134
|
+
if (typeof r === "string")
|
|
135
|
+
skipped.push({ file: name, reason: r });
|
|
136
|
+
else
|
|
137
|
+
exports.push({ file: name, data: r });
|
|
138
|
+
}
|
|
139
|
+
return { exports, skipped };
|
|
140
|
+
}
|
|
141
|
+
/** "YYYY-MM-DD" days from `a` to `b`, both included. */
|
|
142
|
+
function daysBetween(a, b) {
|
|
143
|
+
const out = [];
|
|
144
|
+
const end = Date.parse(`${b}T00:00:00Z`);
|
|
145
|
+
for (let t = Date.parse(`${a}T00:00:00Z`); Number.isFinite(t) && t <= end && out.length < 4000; t += 86_400_000)
|
|
146
|
+
out.push(new Date(t).toISOString().slice(0, 10));
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
/** Add up exports: each developer's day once (their newest file that covers it), then by developer, repository, tool, model and day. */
|
|
150
|
+
export function mergeExports(exports, skipped = []) {
|
|
151
|
+
const byDev = new Map();
|
|
152
|
+
for (const e of exports)
|
|
153
|
+
(byDev.get(e.data.developer) ?? byDev.set(e.data.developer, []).get(e.data.developer)).push(e);
|
|
154
|
+
const rows = [];
|
|
155
|
+
const developers = [];
|
|
156
|
+
let overlaps = 0;
|
|
157
|
+
for (const [developer, files] of byDev) {
|
|
158
|
+
files.sort((a, b) => b.data.exportedAt.localeCompare(a.data.exportedAt) || b.data.to.localeCompare(a.data.to));
|
|
159
|
+
const claimed = new Map();
|
|
160
|
+
for (const f of files)
|
|
161
|
+
for (const d of daysBetween(f.data.from, f.data.to)) {
|
|
162
|
+
if (claimed.has(d))
|
|
163
|
+
overlaps++;
|
|
164
|
+
else
|
|
165
|
+
claimed.set(d, f.data);
|
|
166
|
+
}
|
|
167
|
+
for (const f of files)
|
|
168
|
+
for (const r of f.data.rows)
|
|
169
|
+
if (claimed.get(r.day) === f.data)
|
|
170
|
+
rows.push({ ...r, developer });
|
|
171
|
+
const days = [...claimed.keys()].sort();
|
|
172
|
+
developers.push({ name: developer, usd: 0, requests: 0, unpriced: 0, from: days[0] ?? "", to: days[days.length - 1] ?? "", files: files.length });
|
|
173
|
+
}
|
|
174
|
+
const group = (key) => {
|
|
175
|
+
const m = new Map();
|
|
176
|
+
for (const r of rows) {
|
|
177
|
+
const k = key(r);
|
|
178
|
+
if (k === undefined)
|
|
179
|
+
continue;
|
|
180
|
+
const g = m.get(k) ?? m.set(k, { name: k, usd: 0, requests: 0, unpriced: 0, tools: [] }).get(k);
|
|
181
|
+
g.usd += r.usd;
|
|
182
|
+
g.requests += r.requests;
|
|
183
|
+
g.unpriced += r.unpriced;
|
|
184
|
+
if (!g.tools.includes(r.tool))
|
|
185
|
+
g.tools.push(r.tool);
|
|
186
|
+
}
|
|
187
|
+
return [...m.values()].map((g) => ({ ...g, tools: TOOLS.filter((t) => g.tools.includes(t)) })).sort((a, b) => b.usd - a.usd || b.requests - a.requests || a.name.localeCompare(b.name));
|
|
188
|
+
};
|
|
189
|
+
const devTotals = new Map(group((r) => r.developer).map((g) => [g.name, g]));
|
|
190
|
+
for (const d of developers)
|
|
191
|
+
Object.assign(d, { usd: devTotals.get(d.name)?.usd ?? 0, requests: devTotals.get(d.name)?.requests ?? 0, unpriced: devTotals.get(d.name)?.unpriced ?? 0, tools: devTotals.get(d.name)?.tools ?? [] });
|
|
192
|
+
developers.sort((a, b) => a.name.localeCompare(b.name));
|
|
193
|
+
const from = developers.map((d) => d.from).filter(Boolean).sort()[0] ?? "";
|
|
194
|
+
const to = developers.map((d) => d.to).filter(Boolean).sort().pop() ?? "";
|
|
195
|
+
const perDay = new Map();
|
|
196
|
+
for (const r of rows)
|
|
197
|
+
perDay.set(r.day, (perDay.get(r.day) ?? 0) + r.usd);
|
|
198
|
+
const daily = from ? daysBetween(from, to).map((day) => ({ day, usd: perDay.get(day) ?? 0 })) : [];
|
|
199
|
+
const sum = (f) => rows.reduce((n, r) => n + f(r), 0);
|
|
200
|
+
const report = {
|
|
201
|
+
files: exports.length, developers, from, to,
|
|
202
|
+
usd: sum((r) => r.usd), requests: sum((r) => r.requests), unpriced: sum((r) => r.unpriced),
|
|
203
|
+
tokens: { input: sum((r) => r.tokens.input ?? 0), read: sum((r) => r.tokens.read ?? 0), write: sum((r) => r.tokens.write ?? 0), output: sum((r) => r.tokens.output ?? 0) },
|
|
204
|
+
repos: group((r) => r.repo), tools: group((r) => r.tool), models: group((r) => r.model),
|
|
205
|
+
daily,
|
|
206
|
+
endsEarly: developers.filter((d) => d.to && d.to < to).map((d) => ({ developer: d.name, to: d.to })),
|
|
207
|
+
overlaps,
|
|
208
|
+
bases: [...new Set(exports.map((e) => e.data.basis))],
|
|
209
|
+
anonymized: exports.some((e) => e.data.anonymized),
|
|
210
|
+
skipped,
|
|
211
|
+
};
|
|
212
|
+
if (rows.some((r) => r.branch))
|
|
213
|
+
report.branches = group((r) => (r.branch ? `${r.repo} ${r.branch}` : undefined));
|
|
214
|
+
if (rows.some((r) => r.credits !== undefined))
|
|
215
|
+
report.credits = sum((r) => r.credits ?? 0);
|
|
216
|
+
if (rows.some((r) => r.premium !== undefined))
|
|
217
|
+
report.premium = sum((r) => r.premium ?? 0);
|
|
218
|
+
// The month of the last day: so far, and the rest at the pace of the last 14 days (fewer when the files hold fewer).
|
|
219
|
+
if (to) {
|
|
220
|
+
const month = to.slice(0, 7);
|
|
221
|
+
const soFar = daily.filter((d) => d.day.startsWith(month)).reduce((n, d) => n + d.usd, 0);
|
|
222
|
+
const recent = daily.slice(-14);
|
|
223
|
+
const pace = recent.reduce((n, d) => n + d.usd, 0) / Math.max(1, recent.length);
|
|
224
|
+
const [y, m] = month.split("-").map(Number);
|
|
225
|
+
const daysLeft = new Date(Date.UTC(y, m, 0)).getUTCDate() - Number(to.slice(8, 10));
|
|
226
|
+
report.forecast = { month, soFar, perDay: pace, paceDays: recent.length, daysLeft, usd: soFar + pace * daysLeft };
|
|
227
|
+
}
|
|
228
|
+
return report;
|
|
229
|
+
}
|
|
230
|
+
const MONTH_NAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
|
231
|
+
const share = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "");
|
|
232
|
+
const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
|
|
233
|
+
/** `spend merge`'s text, within 80 columns. `top`: rows per list. */
|
|
234
|
+
export function renderMerge(r, folder, top = 8) {
|
|
235
|
+
const lines = [];
|
|
236
|
+
if (!r.files) {
|
|
237
|
+
lines.push(`No spend exports in ${folder}. Each person runs \`context-doctor spend --export\` and puts the file there.`);
|
|
238
|
+
for (const s of r.skipped)
|
|
239
|
+
lines.push(` ${s.file}: ${s.reason}`);
|
|
240
|
+
return lines.join("\n");
|
|
241
|
+
}
|
|
242
|
+
const devs = r.developers.length;
|
|
243
|
+
lines.push(`Team spend: ${r.files} ${r.files === 1 ? "export" : "exports"}, ${devs} ${devs === 1 ? "developer" : "developers"}, ${r.from} to ${r.to}`);
|
|
244
|
+
lines.push(`Each request ${r.bases.length === 1 ? r.bases[0] : `priced as its export says (${r.bases.join("; ")})`}${r.anonymized ? "; repository and branch names hashed" : ""}`);
|
|
245
|
+
lines.push("─".repeat(60));
|
|
246
|
+
lines.push(`${"Total".padEnd(14)}${usd(r.usd).padStart(11)} ${r.requests.toLocaleString("en-US")} requests`);
|
|
247
|
+
const f = r.forecast;
|
|
248
|
+
if (f) {
|
|
249
|
+
const name = `${MONTH_NAMES[Number(f.month.slice(5, 7)) - 1]} ${f.month.slice(0, 4)}`;
|
|
250
|
+
lines.push(f.daysLeft > 0
|
|
251
|
+
? `${name}: ${usd(f.soFar)} so far; ~${usd(f.usd)} by month-end at the last ${f.paceDays} ${f.paceDays === 1 ? "day's" : "days'"} ${usd(f.perDay)}/day (an estimate)`
|
|
252
|
+
: `${name}: ${usd(f.soFar)}, the whole month`);
|
|
253
|
+
}
|
|
254
|
+
const list = (title, rows, tail) => {
|
|
255
|
+
lines.push("", title);
|
|
256
|
+
for (const x of rows.slice(0, top))
|
|
257
|
+
lines.push(` ${clip(x.name, 34).padEnd(34)}${usd(x.usd).padStart(10)} ${share(x.usd, r.usd).padStart(4)}${tail ? ` ${tail(x)}` : ""}`);
|
|
258
|
+
if (rows.length > top)
|
|
259
|
+
lines.push(` … and ${rows.length - top} more`);
|
|
260
|
+
};
|
|
261
|
+
const toolsOf = (x) => (r.tools.length > 1 ? (x.tools ?? []).map((t) => TOOL_NAME[t]).join(", ") : "");
|
|
262
|
+
list("By developer (alphabetical)", r.developers, (x) => {
|
|
263
|
+
const d = x;
|
|
264
|
+
return d.from === r.from && d.to === r.to ? "" : `${d.from} to ${d.to}`;
|
|
265
|
+
});
|
|
266
|
+
list("By repository", r.repos, toolsOf);
|
|
267
|
+
if (r.branches)
|
|
268
|
+
list("By branch", r.branches, toolsOf);
|
|
269
|
+
list("By tool", r.tools.map((t) => ({ ...t, name: TOOL_NAME[t.name] ?? t.name })), (x) => `${x.requests.toLocaleString("en-US")} requests`);
|
|
270
|
+
list("By model", r.models, (x) => (x.usd === 0 && x.unpriced ? "not priced" : ""));
|
|
271
|
+
const notes = [];
|
|
272
|
+
if (r.unpriced)
|
|
273
|
+
notes.push(`${r.unpriced.toLocaleString("en-US")} requests on models with no list price are counted, not in the dollars.`);
|
|
274
|
+
if (r.credits !== undefined || r.premium !== undefined)
|
|
275
|
+
notes.push(`Copilot CLI counted ${[r.credits !== undefined ? `${Math.round(r.credits).toLocaleString("en-US")} AI credits (${usd(r.credits / 100)} at $0.01)` : "", r.premium !== undefined ? `${Math.round(r.premium).toLocaleString("en-US")} premium requests` : ""].filter(Boolean).join(" and ")}, beside its tokens at list price.`);
|
|
276
|
+
for (const e of r.endsEarly)
|
|
277
|
+
notes.push(`${e.developer}'s export ends ${e.to}: the days after count nothing for them; a newer export fixes it.`);
|
|
278
|
+
if (r.overlaps)
|
|
279
|
+
notes.push(`${r.overlaps} ${r.overlaps === 1 ? "day" : "days"} in more than one file of the same developer: counted once, from the newer file.`);
|
|
280
|
+
for (const s of r.skipped)
|
|
281
|
+
notes.push(`Skipped ${s.file}: ${s.reason}.`);
|
|
282
|
+
if (notes.length)
|
|
283
|
+
lines.push("", ...notes);
|
|
284
|
+
lines.push("", `Tokens: ${formatTokens(r.tokens.input)} uncached in, ${formatTokens(r.tokens.read)} cache reads, ${formatTokens(r.tokens.write)} cache writes, ${formatTokens(r.tokens.output)} out.`);
|
|
285
|
+
return lines.map((l) => l.trimEnd()).join("\n");
|
|
286
|
+
}
|
package/dist/starts.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The start of every session and every subagent: the first request's prompt
|
|
3
|
+
* before the first message, per Claude Code entrypoint (the Desktop app, the
|
|
4
|
+
* terminal, the SDK) and per subagent type, priced across the period.
|
|
5
|
+
*
|
|
6
|
+
* Every later request re-reads that start: from the cache at the read price
|
|
7
|
+
* on a warm step, written again at the write price on a cold one. On the
|
|
8
|
+
* author's machine a Desktop-app session starts at a median ~70k tokens and a
|
|
9
|
+
* general-purpose subagent at ~52k, re-read at each of its steps (#105328:
|
|
10
|
+
* a terminal session starts at ~13k, because the tools the terminal defers
|
|
11
|
+
* behind tool search the app sends whole).
|
|
12
|
+
*
|
|
13
|
+
* Claude Code records what it sent: each transcript's `api-request-shape`
|
|
14
|
+
* rows carry the request's system prompt and every tool definition, with
|
|
15
|
+
* `defer_loading` on the ones held behind tool search, and the
|
|
16
|
+
* `deferred_tools_delta` attachments name the ones announced as deferred. So
|
|
17
|
+
* the part of a start that could be deferred, MCP tool definitions sent whole,
|
|
18
|
+
* is read from the request itself; its tokens are estimated from its length
|
|
19
|
+
* (Claude's ratios), the start itself is the API's own count.
|
|
20
|
+
*/
|
|
21
|
+
import { type Extractor } from "./scan.js";
|
|
22
|
+
/**
|
|
23
|
+
* What a start's measurement takes from a transcript: the entrypoint, the
|
|
24
|
+
* first request's query source (it names a subagent's type), the first user
|
|
25
|
+
* message's length (never its text), the tools announced as deferred before
|
|
26
|
+
* the first reply, and the first request's shape as names and lengths. A
|
|
27
|
+
* handful of records per transcript, read once (scan.ts).
|
|
28
|
+
*/
|
|
29
|
+
export declare const START_ROWS: Extractor<{
|
|
30
|
+
e?: 1;
|
|
31
|
+
q?: 1;
|
|
32
|
+
s?: 1;
|
|
33
|
+
u?: 1;
|
|
34
|
+
r?: 1;
|
|
35
|
+
}>;
|
|
36
|
+
/** An entrypoint as people call it. */
|
|
37
|
+
export declare function entrypointName(e: string | undefined): string;
|
|
38
|
+
/** The MCP server a tool name belongs to (`mcp__<server>__<tool>`), or undefined for a built-in. */
|
|
39
|
+
export declare function mcpServerOf(name: string): string | undefined;
|
|
40
|
+
export interface StartServer {
|
|
41
|
+
name: string;
|
|
42
|
+
/** Starts it went whole into. */
|
|
43
|
+
starts: number;
|
|
44
|
+
tools: number;
|
|
45
|
+
/** Its definitions' tokens on a start (an estimate from their length). */
|
|
46
|
+
tokens: number;
|
|
47
|
+
/** In the user's own MCP config (~/.claude.json, the folder's .mcp.json): `alwaysLoad: false` there defers it. */
|
|
48
|
+
configured?: "user" | "project" | ".mcp.json";
|
|
49
|
+
}
|
|
50
|
+
export interface StartGroup {
|
|
51
|
+
kind: "session" | "subagent";
|
|
52
|
+
/** The entrypoint as recorded ("claude-desktop", "cli", "sdk-cli"). */
|
|
53
|
+
entrypoint: string;
|
|
54
|
+
agentType?: string;
|
|
55
|
+
/** Starts measured (a first request over 1k tokens). */
|
|
56
|
+
starts: number;
|
|
57
|
+
median: number;
|
|
58
|
+
p10: number;
|
|
59
|
+
p90: number;
|
|
60
|
+
/** Requests in the period, every one of which re-read the start. */
|
|
61
|
+
requests: number;
|
|
62
|
+
/** The start's price over the period: read on warm steps, written on cold ones. */
|
|
63
|
+
usd: number;
|
|
64
|
+
/** Starts whose model has no price: `usd` undercounts. */
|
|
65
|
+
unpriced: number;
|
|
66
|
+
/** Starts with a recorded request shape (Claude Code 2.1.308 and later). */
|
|
67
|
+
shaped: number;
|
|
68
|
+
/** Median tokens of tool definitions sent whole, and of MCP tool definitions sent whole (estimates). */
|
|
69
|
+
wholeTokens?: number;
|
|
70
|
+
mcpTokens?: number;
|
|
71
|
+
wholeTools?: number;
|
|
72
|
+
/** The MCP part's share of `usd`: what deferring those definitions would have saved, at most. */
|
|
73
|
+
deferrableUsd?: number;
|
|
74
|
+
servers: StartServer[];
|
|
75
|
+
}
|
|
76
|
+
export interface StartsReport {
|
|
77
|
+
days: number;
|
|
78
|
+
groups: StartGroup[];
|
|
79
|
+
/** Desktop-app sessions against terminal ones, when both are in the period. */
|
|
80
|
+
gap?: {
|
|
81
|
+
desktop: number;
|
|
82
|
+
terminal: number;
|
|
83
|
+
tokens: number;
|
|
84
|
+
usd: number;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Every session's and subagent's start in the period, grouped by entrypoint
|
|
89
|
+
* and subagent type, each priced on every request that re-read it.
|
|
90
|
+
* `paths`: the main transcripts (subagents are found beside each).
|
|
91
|
+
*/
|
|
92
|
+
export declare function measureStarts(opts?: {
|
|
93
|
+
days?: number;
|
|
94
|
+
paths?: string[];
|
|
95
|
+
cwd?: string;
|
|
96
|
+
home?: string;
|
|
97
|
+
}): StartsReport;
|
|
98
|
+
/** The servers whose tools went whole into some start and that the user's own config holds: `alwaysLoad: false` defers them. */
|
|
99
|
+
export declare function deferrableConfigured(r: StartsReport): Array<{
|
|
100
|
+
name: string;
|
|
101
|
+
scope: NonNullable<StartServer["configured"]>;
|
|
102
|
+
tokens: number;
|
|
103
|
+
usd: number;
|
|
104
|
+
}>;
|
|
105
|
+
/** The starts section of `overhead`. */
|
|
106
|
+
export declare function renderStarts(r: StartsReport): string[];
|