@anthonymercer/contextscope 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +764 -2
- package/dist/cli/ansi.d.ts +31 -0
- package/dist/cli/ansi.js +80 -0
- package/dist/cli/args.d.ts +18 -0
- package/dist/cli/args.js +78 -0
- package/dist/cli/html-report.d.ts +2 -0
- package/dist/cli/html-report.js +119 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +138 -0
- package/dist/cli/json-report.d.ts +1 -0
- package/dist/cli/json-report.js +2 -0
- package/dist/cli/read-input.d.ts +3 -0
- package/dist/cli/read-input.js +43 -0
- package/dist/cli/terminal-report.d.ts +7 -0
- package/dist/cli/terminal-report.js +271 -0
- package/dist/cli/usage-html.d.ts +2 -0
- package/dist/cli/usage-html.js +33 -0
- package/dist/cli/version.d.ts +2 -0
- package/dist/cli/version.js +3 -0
- package/dist/cli/write-reports.d.ts +12 -0
- package/dist/cli/write-reports.js +82 -0
- package/dist/core/analyze.d.ts +13 -0
- package/dist/core/analyze.js +99 -0
- package/dist/core/anthropic-breakpoints.d.ts +6 -0
- package/dist/core/anthropic-breakpoints.js +48 -0
- package/dist/core/anthropic-cache-scope.d.ts +12 -0
- package/dist/core/anthropic-cache-scope.js +47 -0
- package/dist/core/anthropic-injected-settings.d.ts +14 -0
- package/dist/core/anthropic-injected-settings.js +57 -0
- package/dist/core/anthropic-reasoning.d.ts +13 -0
- package/dist/core/anthropic-reasoning.js +57 -0
- package/dist/core/anthropic-speed.d.ts +4 -0
- package/dist/core/anthropic-speed.js +27 -0
- package/dist/core/cache-anthropic.d.ts +2 -0
- package/dist/core/cache-anthropic.js +146 -0
- package/dist/core/cache-openai.d.ts +2 -0
- package/dist/core/cache-openai.js +72 -0
- package/dist/core/calibrate.d.ts +43 -0
- package/dist/core/calibrate.js +97 -0
- package/dist/core/decode-text.d.ts +9 -0
- package/dist/core/decode-text.js +21 -0
- package/dist/core/detect.d.ts +10 -0
- package/dist/core/detect.js +102 -0
- package/dist/core/duplicates.d.ts +12 -0
- package/dist/core/duplicates.js +153 -0
- package/dist/core/findings.d.ts +4 -0
- package/dist/core/findings.js +437 -0
- package/dist/core/group-findings.d.ts +23 -0
- package/dist/core/group-findings.js +69 -0
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.js +2 -0
- package/dist/core/json-report.d.ts +10 -0
- package/dist/core/json-report.js +46 -0
- package/dist/core/json-utils.d.ts +28 -0
- package/dist/core/json-utils.js +99 -0
- package/dist/core/media-accounting.d.ts +11 -0
- package/dist/core/media-accounting.js +76 -0
- package/dist/core/model-id.d.ts +16 -0
- package/dist/core/model-id.js +36 -0
- package/dist/core/model-summary.d.ts +10 -0
- package/dist/core/model-summary.js +44 -0
- package/dist/core/openai-breakpoints.d.ts +14 -0
- package/dist/core/openai-breakpoints.js +107 -0
- package/dist/core/openai-context.d.ts +15 -0
- package/dist/core/openai-context.js +54 -0
- package/dist/core/parse-anthropic.d.ts +4 -0
- package/dist/core/parse-anthropic.js +284 -0
- package/dist/core/parse-error.d.ts +3 -0
- package/dist/core/parse-error.js +4 -0
- package/dist/core/parse-openai.d.ts +10 -0
- package/dist/core/parse-openai.js +273 -0
- package/dist/core/parse.d.ts +3 -0
- package/dist/core/parse.js +164 -0
- package/dist/core/prefix.d.ts +23 -0
- package/dist/core/prefix.js +290 -0
- package/dist/core/presentation.d.ts +4 -0
- package/dist/core/presentation.js +5 -0
- package/dist/core/pricing.d.ts +76 -0
- package/dist/core/pricing.js +130 -0
- package/dist/core/prompt-identity.d.ts +5 -0
- package/dist/core/prompt-identity.js +84 -0
- package/dist/core/read-json.d.ts +7 -0
- package/dist/core/read-json.js +74 -0
- package/dist/core/report.d.ts +2 -0
- package/dist/core/report.js +31 -0
- package/dist/core/reported-usage.d.ts +7 -0
- package/dist/core/reported-usage.js +195 -0
- package/dist/core/threads.d.ts +48 -0
- package/dist/core/threads.js +189 -0
- package/dist/core/token-counter.d.ts +13 -0
- package/dist/core/token-counter.js +21 -0
- package/dist/core/tokenize-claude.d.ts +18 -0
- package/dist/core/tokenize-claude.js +56 -0
- package/dist/core/tokenize-openai.d.ts +1 -0
- package/dist/core/tokenize-openai.js +15 -0
- package/dist/core/types.d.ts +326 -0
- package/dist/core/types.js +12 -0
- package/dist/core/usage-comparison.d.ts +2 -0
- package/dist/core/usage-comparison.js +70 -0
- package/dist/core/usage-labels.d.ts +5 -0
- package/dist/core/usage-labels.js +18 -0
- package/dist/core/volatile.d.ts +12 -0
- package/dist/core/volatile.js +31 -0
- package/package.json +75 -4
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Minimal ANSI helpers - no chalk dependency; contextscope has almost no runtime deps by design. */
|
|
2
|
+
export declare const bold: (s: string) => string;
|
|
3
|
+
export declare const dim: (s: string) => string;
|
|
4
|
+
export declare const red: (s: string) => string;
|
|
5
|
+
export declare const green: (s: string) => string;
|
|
6
|
+
export declare const yellow: (s: string) => string;
|
|
7
|
+
export declare const blue: (s: string) => string;
|
|
8
|
+
export declare const magenta: (s: string) => string;
|
|
9
|
+
export declare const cyan: (s: string) => string;
|
|
10
|
+
/**
|
|
11
|
+
* `text` with each control character (bar tab and line breaks) written as a visible escape,
|
|
12
|
+
* `\x1b`. Model names, labels and messages can come from the requests, and a terminal obeys
|
|
13
|
+
* an escape sequence in what it is given: clears the screen, retitles the window, hides text.
|
|
14
|
+
*/
|
|
15
|
+
export declare function visible(text: string): string;
|
|
16
|
+
export declare function severityColor(severity: "info" | "warning" | "error"): (s: string) => string;
|
|
17
|
+
export declare function bar(fraction: number, width?: number): string;
|
|
18
|
+
export declare function fmtTokens(n: number | null): string;
|
|
19
|
+
export declare function fmtUsd(n: number | undefined): string;
|
|
20
|
+
/** Whole-dollar formatting with thousands separators, for the "per 1,000 sessions" projection -
|
|
21
|
+
* `fmtUsd`'s 4-decimal-place precision is the wrong shape once the number is in the hundreds/thousands. */
|
|
22
|
+
export declare function fmtUsdRounded(n: number): string;
|
|
23
|
+
export declare function fmtPct(n: number | undefined): string;
|
|
24
|
+
export declare function terminalWidth(): number;
|
|
25
|
+
/**
|
|
26
|
+
* Word-wraps `text` to `width` columns with a hanging indent: the first line is prefixed with
|
|
27
|
+
* `indent` spaces same as every following line, so a long finding description lines up under its
|
|
28
|
+
* own text instead of resetting to column 0 mid-sentence (the terminal's own soft-wrap would do
|
|
29
|
+
* the latter, since it has no notion of our indent).
|
|
30
|
+
*/
|
|
31
|
+
export declare function wrapIndented(text: string, indent: number, width?: number): string[];
|
package/dist/cli/ansi.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/** Minimal ANSI helpers - no chalk dependency; contextscope has almost no runtime deps by design. */
|
|
2
|
+
const colorEnabled = process.env["NO_COLOR"] === undefined && (process.stdout.isTTY === true || process.env["FORCE_COLOR"] !== undefined);
|
|
3
|
+
function wrap(code) {
|
|
4
|
+
return (s) => (colorEnabled ? `\u001b[${code}m${s}\u001b[0m` : s);
|
|
5
|
+
}
|
|
6
|
+
export const bold = wrap("1");
|
|
7
|
+
export const dim = wrap("2");
|
|
8
|
+
export const red = wrap("31");
|
|
9
|
+
export const green = wrap("32");
|
|
10
|
+
export const yellow = wrap("33");
|
|
11
|
+
export const blue = wrap("34");
|
|
12
|
+
export const magenta = wrap("35");
|
|
13
|
+
export const cyan = wrap("36");
|
|
14
|
+
/**
|
|
15
|
+
* `text` with each control character (bar tab and line breaks) written as a visible escape,
|
|
16
|
+
* `\x1b`. Model names, labels and messages can come from the requests, and a terminal obeys
|
|
17
|
+
* an escape sequence in what it is given: clears the screen, retitles the window, hides text.
|
|
18
|
+
*/
|
|
19
|
+
export function visible(text) {
|
|
20
|
+
return text.replace(/[^\P{Cc}\t\n\r]/gu, (ch) => `\\x${ch.charCodeAt(0).toString(16).padStart(2, "0")}`);
|
|
21
|
+
}
|
|
22
|
+
export function severityColor(severity) {
|
|
23
|
+
if (severity === "error")
|
|
24
|
+
return red;
|
|
25
|
+
if (severity === "warning")
|
|
26
|
+
return yellow;
|
|
27
|
+
return cyan;
|
|
28
|
+
}
|
|
29
|
+
export function bar(fraction, width = 24) {
|
|
30
|
+
const filled = Math.max(0, Math.min(width, Math.round(fraction * width)));
|
|
31
|
+
return "█".repeat(filled) + "░".repeat(width - filled);
|
|
32
|
+
}
|
|
33
|
+
export function fmtTokens(n) {
|
|
34
|
+
return n === null ? "n/a" : n.toLocaleString("en-US");
|
|
35
|
+
}
|
|
36
|
+
export function fmtUsd(n) {
|
|
37
|
+
if (n === undefined)
|
|
38
|
+
return "n/a";
|
|
39
|
+
return `$${n.toFixed(4)}`;
|
|
40
|
+
}
|
|
41
|
+
/** Whole-dollar formatting with thousands separators, for the "per 1,000 sessions" projection -
|
|
42
|
+
* `fmtUsd`'s 4-decimal-place precision is the wrong shape once the number is in the hundreds/thousands. */
|
|
43
|
+
export function fmtUsdRounded(n) {
|
|
44
|
+
return `$${n.toLocaleString("en-US", { maximumFractionDigits: 0 })}`;
|
|
45
|
+
}
|
|
46
|
+
export function fmtPct(n) {
|
|
47
|
+
if (n === undefined)
|
|
48
|
+
return "n/a";
|
|
49
|
+
return `${(n * 100).toFixed(1)}%`;
|
|
50
|
+
}
|
|
51
|
+
export function terminalWidth() {
|
|
52
|
+
return process.stdout.columns || 100;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Word-wraps `text` to `width` columns with a hanging indent: the first line is prefixed with
|
|
56
|
+
* `indent` spaces same as every following line, so a long finding description lines up under its
|
|
57
|
+
* own text instead of resetting to column 0 mid-sentence (the terminal's own soft-wrap would do
|
|
58
|
+
* the latter, since it has no notion of our indent).
|
|
59
|
+
*/
|
|
60
|
+
export function wrapIndented(text, indent, width = terminalWidth()) {
|
|
61
|
+
const usable = Math.max(20, width - indent);
|
|
62
|
+
const prefix = " ".repeat(indent);
|
|
63
|
+
const words = text.split(/\s+/);
|
|
64
|
+
const lines = [];
|
|
65
|
+
let current = "";
|
|
66
|
+
for (const word of words) {
|
|
67
|
+
const candidate = current.length === 0 ? word : `${current} ${word}`;
|
|
68
|
+
if (candidate.length > usable && current.length > 0) {
|
|
69
|
+
lines.push(prefix + current);
|
|
70
|
+
current = word;
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
current = candidate;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (current.length > 0)
|
|
77
|
+
lines.push(prefix + current);
|
|
78
|
+
return lines;
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=ansi.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { FindingSeverity } from "../core/index.js";
|
|
2
|
+
export interface CliArgs {
|
|
3
|
+
command: string | undefined;
|
|
4
|
+
file: string | undefined;
|
|
5
|
+
format: "anthropic" | "openai" | undefined;
|
|
6
|
+
model: string | undefined;
|
|
7
|
+
html: string | undefined;
|
|
8
|
+
json: string | undefined;
|
|
9
|
+
failOn: FindingSeverity | undefined;
|
|
10
|
+
calibrate: boolean;
|
|
11
|
+
verbose: boolean;
|
|
12
|
+
help: boolean;
|
|
13
|
+
version: boolean;
|
|
14
|
+
}
|
|
15
|
+
export declare class UsageError extends Error {
|
|
16
|
+
}
|
|
17
|
+
/** Parses argv (without the node/script prefix). Throws UsageError with a user-facing message. */
|
|
18
|
+
export declare function parseArgs(argv: string[]): CliArgs;
|
package/dist/cli/args.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export class UsageError extends Error {
|
|
2
|
+
}
|
|
3
|
+
/** Parses argv (without the node/script prefix). Throws UsageError with a user-facing message. */
|
|
4
|
+
export function parseArgs(argv) {
|
|
5
|
+
const args = [...argv];
|
|
6
|
+
const command = args[0]?.startsWith("-") ? undefined : args.shift();
|
|
7
|
+
const out = {
|
|
8
|
+
command,
|
|
9
|
+
file: undefined,
|
|
10
|
+
format: undefined,
|
|
11
|
+
model: undefined,
|
|
12
|
+
html: undefined,
|
|
13
|
+
json: undefined,
|
|
14
|
+
failOn: undefined,
|
|
15
|
+
calibrate: false,
|
|
16
|
+
verbose: false,
|
|
17
|
+
help: false,
|
|
18
|
+
version: false,
|
|
19
|
+
};
|
|
20
|
+
const value = (flag) => {
|
|
21
|
+
const v = args.shift();
|
|
22
|
+
if (v === undefined || v.startsWith("-"))
|
|
23
|
+
throw new UsageError(`${flag} needs a value.`);
|
|
24
|
+
return v;
|
|
25
|
+
};
|
|
26
|
+
while (args.length > 0) {
|
|
27
|
+
const arg = args.shift();
|
|
28
|
+
switch (arg) {
|
|
29
|
+
case "--format": {
|
|
30
|
+
const format = value(arg);
|
|
31
|
+
if (format !== "anthropic" && format !== "openai")
|
|
32
|
+
throw new UsageError(`--format must be "anthropic" or "openai", not "${format}".`);
|
|
33
|
+
out.format = format;
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
case "--model":
|
|
37
|
+
out.model = value(arg);
|
|
38
|
+
break;
|
|
39
|
+
case "--html":
|
|
40
|
+
out.html = value(arg);
|
|
41
|
+
break;
|
|
42
|
+
case "--json":
|
|
43
|
+
out.json = value(arg);
|
|
44
|
+
break;
|
|
45
|
+
case "--fail-on": {
|
|
46
|
+
const level = value(arg);
|
|
47
|
+
if (level !== "error" && level !== "warning" && level !== "info")
|
|
48
|
+
throw new UsageError(`--fail-on must be error, warning or info, not "${level}".`);
|
|
49
|
+
out.failOn = level;
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
case "--calibrate":
|
|
53
|
+
out.calibrate = true;
|
|
54
|
+
break;
|
|
55
|
+
case "-v":
|
|
56
|
+
case "--verbose":
|
|
57
|
+
out.verbose = true;
|
|
58
|
+
break;
|
|
59
|
+
case "-h":
|
|
60
|
+
case "--help":
|
|
61
|
+
out.help = true;
|
|
62
|
+
break;
|
|
63
|
+
case "-V":
|
|
64
|
+
case "--version":
|
|
65
|
+
out.version = true;
|
|
66
|
+
break;
|
|
67
|
+
default:
|
|
68
|
+
if (arg.startsWith("-") && arg !== "-")
|
|
69
|
+
throw new UsageError(`Unknown option "${arg}".`);
|
|
70
|
+
if (out.file !== undefined)
|
|
71
|
+
throw new UsageError(`Only one input file is supported (got "${out.file}" and "${arg}").`);
|
|
72
|
+
out.file = arg;
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=args.js.map
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { describeRequestIndices, groupFindings } from "../core/group-findings.js";
|
|
2
|
+
import { modelGroups, modelLabel, modelNotes, modelSummary } from "../core/model-summary.js";
|
|
3
|
+
import { renderUsageHtml } from "./usage-html.js";
|
|
4
|
+
import { usageNumber } from "../core/usage-labels.js";
|
|
5
|
+
function esc(s) {
|
|
6
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
7
|
+
}
|
|
8
|
+
const CATEGORY_COLOR = {
|
|
9
|
+
system: "#2a78d6",
|
|
10
|
+
tools: "#eb6834",
|
|
11
|
+
user: "#1baf7a",
|
|
12
|
+
assistant: "#eda100",
|
|
13
|
+
tool_call: "#e87ba4",
|
|
14
|
+
tool_result: "#008300",
|
|
15
|
+
image: "#4a3aa7",
|
|
16
|
+
thinking: "#e34948",
|
|
17
|
+
reference: "currentColor",
|
|
18
|
+
};
|
|
19
|
+
/** A single self-contained HTML file: no external requests, no JS framework - a static report
|
|
20
|
+
* meant to be opened locally or attached to a PR/ticket. The interactive web app is the place
|
|
21
|
+
* for exploration; this is the "send this to a teammate" artifact. */
|
|
22
|
+
/**
|
|
23
|
+
* The report is one file with no script in it, and this has the browser hold it to that:
|
|
24
|
+
* nothing in it may run or be fetched, whatever a tool or a message in the log is called.
|
|
25
|
+
* Text from the log is escaped; the policy is for the day some is not.
|
|
26
|
+
*/
|
|
27
|
+
const REPORT_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'";
|
|
28
|
+
export function renderHtmlReport(result) {
|
|
29
|
+
const { parse, reports, cacheSimulation, findings, duplicates } = result;
|
|
30
|
+
const mixedModels = modelGroups(result).length > 1;
|
|
31
|
+
const showSpeed = cacheSimulation.actual.some((step) => step.speed !== undefined);
|
|
32
|
+
const openai = cacheSimulation.provider === "openai";
|
|
33
|
+
const requestSections = reports
|
|
34
|
+
.map((report) => {
|
|
35
|
+
const rows = report.byCategory
|
|
36
|
+
.map((c) => `<tr><td><span class="swatch" style="background:${CATEGORY_COLOR[c.category]}"></span>${esc(c.category)}</td><td>${c.segmentCount}</td><td>${usageNumber(c.claudeTokensEstimate)}</td><td>${usageNumber(c.openaiTokens)}</td></tr>`)
|
|
37
|
+
.join("");
|
|
38
|
+
return `<section class="card"><h3>Request ${report.requestIndex + 1} · ${esc(modelLabel(report.model))}</h3>
|
|
39
|
+
<p class="muted">${report.totals.claudeTokensEstimate === null ? "Claude tokens unavailable" : `≈${usageNumber(report.totals.claudeTokensEstimate)} Claude tokens`} · ${report.totals.openaiTokens === null ? "OpenAI tokens unavailable" : `${usageNumber(report.totals.openaiTokens)} OpenAI tokens`}${report.percentOfContextWindow !== undefined ? ` · ${(report.percentOfContextWindow * 100).toFixed(1)}% of context window` : ""}</p>
|
|
40
|
+
<div class="table-scroll" tabindex="0" role="group" aria-label="Token categories for request ${report.requestIndex + 1}"><table><thead><tr><th>category</th><th>segments</th><th>≈Claude tok</th><th>OpenAI tok</th></tr></thead><tbody>${rows}</tbody></table></div>
|
|
41
|
+
</section>`;
|
|
42
|
+
})
|
|
43
|
+
.join("\n");
|
|
44
|
+
const cacheRows = cacheSimulation.actual
|
|
45
|
+
.map((step, i) => `<tr><td>req ${i + 1}</td>${showSpeed ? `<td>${esc(step.speed ?? "standard")}</td>` : ""}${openai ? `<td>${esc(step.cacheMode ?? "legacy")}</td>` : ""}${mixedModels ? `<td>${esc(modelLabel(reports[i].model))}</td>` : ""}<td>${usageNumber(step.readTokens)}</td>${openai ? `<td>${usageNumber(step.unavailableReason ? null : step.writeTokens30m ?? 0)}</td>` : `<td>${usageNumber(step.writeTokens5m)}</td><td>${usageNumber(step.writeTokens1h)}</td>`}<td>${usageNumber(step.uncachedTokens)}</td><td>${step.costUsd !== undefined ? `$${step.costUsd.toFixed(4)}` : "n/a"}</td></tr>`)
|
|
46
|
+
.join("");
|
|
47
|
+
const groups = groupFindings(findings);
|
|
48
|
+
const findingRows = groups
|
|
49
|
+
.map((g) => `<li class="finding ${esc(g.severity)}"><span class="pill">${esc(g.severity)}</span> <strong>${esc(g.title)}</strong> <span class="muted">(${describeRequestIndices(g.requestIndices)}${g.requestIndices.length > 1 ? `, ${g.requestIndices.length}×` : ""})</span><p>${esc(g.detail)}</p></li>`)
|
|
50
|
+
.join("");
|
|
51
|
+
const duplicateRows = duplicates
|
|
52
|
+
.map((g) => `<li>${g.members.length}× "${esc(g.members[0].label)}" — ${g.matchKind === "exact" ? "identical text" : `at least ${Math.floor(g.similarity * 100)}% word-shingle similarity`}; ≈${g.estimatedReviewTokens.toLocaleString("en-US")} tokens in later matches to review</li>`)
|
|
53
|
+
.join("");
|
|
54
|
+
const savings = cacheSimulation.totalActualCostUsd !== undefined && cacheSimulation.totalOptimizedCostUsd !== undefined
|
|
55
|
+
? cacheSimulation.totalActualCostUsd - cacheSimulation.totalOptimizedCostUsd
|
|
56
|
+
: undefined;
|
|
57
|
+
return `<!doctype html>
|
|
58
|
+
<html lang="en"><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${REPORT_CSP}"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
59
|
+
<title>contextscope report — ${esc(parse.format)}</title>
|
|
60
|
+
<style>
|
|
61
|
+
:root { color-scheme: light dark; }
|
|
62
|
+
body { font: 15px/1.5 ui-monospace, "IBM Plex Mono", "SFMono-Regular", Menlo, monospace; background: #0d0f13; color: #dfe3ea; max-width: 980px; margin: 0 auto; padding: 32px 20px 80px; }
|
|
63
|
+
@media (prefers-color-scheme: light) { body { background: #f5f4f0; color: #1b1f27; } }
|
|
64
|
+
h1 { font-size: 20px; margin: 0 0 4px; }
|
|
65
|
+
h2 { font-size: 16px; margin: 32px 0 0; }
|
|
66
|
+
h3 { font-size: 15px; margin: 0 0 8px; }
|
|
67
|
+
.muted { color: #929aaa; font-size: 13px; }
|
|
68
|
+
a { color: #7fb6fa; }
|
|
69
|
+
@media (prefers-color-scheme: light) { .muted { color: #5c6270; } a { color: #1b5dad; } }
|
|
70
|
+
.card { border: 1px solid rgba(127,127,127,.3); border-radius: 6px; padding: 16px; margin: 16px 0; }
|
|
71
|
+
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
|
72
|
+
th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid rgba(127,127,127,.2); }
|
|
73
|
+
.swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 6px; }
|
|
74
|
+
ul.findings { list-style: none; padding: 0; }
|
|
75
|
+
li.finding { border-left: 3px solid #7c8494; padding: 8px 12px; margin: 8px 0; }
|
|
76
|
+
li.finding.error { border-color: #e34948; }
|
|
77
|
+
li.finding.warning { border-color: #eda100; }
|
|
78
|
+
li.finding.info { border-color: #2a78d6; }
|
|
79
|
+
.pill { text-transform: uppercase; font-size: 10px; letter-spacing: .05em; opacity: .7; }
|
|
80
|
+
.savings { color: #1baf7a; font-weight: bold; }
|
|
81
|
+
@media (prefers-color-scheme: light) { .savings { color: #08764f; } }
|
|
82
|
+
.table-scroll { overflow-x: auto; margin: 12px 0; }
|
|
83
|
+
.table-scroll:focus-visible, summary:focus-visible, a:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
|
|
84
|
+
.usage-evidence { border-top: 1px solid rgba(127,127,127,.3); padding: 12px 0; scroll-margin-top: 12px; }
|
|
85
|
+
.usage-evidence code { overflow-wrap: anywhere; }
|
|
86
|
+
.usage-evidence summary { cursor: pointer; }
|
|
87
|
+
.card > h2 { margin-top: 0; }
|
|
88
|
+
</style></head>
|
|
89
|
+
<body><main>
|
|
90
|
+
<h1>contextscope report</h1>
|
|
91
|
+
<p class="muted">${esc(parse.format)} · ${parse.requests.length} request(s)${parse.autoDetected ? " · format auto-detected" : ""} · priced as ${esc(modelSummary(result))}${result.claudeTokenScale !== 1 ? ` · Claude estimates calibrated ×${result.claudeTokenScale.toFixed(3)}` : ""} · generated ${new Date().toISOString()}</p>
|
|
92
|
+
${!parse.complete || parse.warnings.length > 0 ? `<section class="card"><h2>${parse.complete ? "Parse notes" : "Incomplete input"}</h2>${!parse.complete ? `<p>${parse.skippedRecords} of ${parse.sourceRecords} source records skipped or not analyzable. Counts and simulations cover retained content only; review all warnings.</p>` : ""}<ul>${parse.warnings.map((warning) => `<li>${esc(warning.message)}</li>`).join("")}</ul></section>` : ""}
|
|
93
|
+
|
|
94
|
+
${modelNotes(result).map((note) => `<p class="muted">${esc(note)}</p>`).join("\n")}
|
|
95
|
+
${renderUsageHtml(result)}
|
|
96
|
+
|
|
97
|
+
<section class="card">
|
|
98
|
+
<h2>Findings (${groups.length} issue${groups.length === 1 ? "" : "s"}${findings.length > groups.length ? ` from ${findings.length} findings` : ""})</h2>
|
|
99
|
+
<ul class="findings">${findingRows || '<li class="muted">No supported cache or duplicate-content issues detected in the retained requests. This does not verify live cache hits.</li>'}</ul>
|
|
100
|
+
</section>
|
|
101
|
+
|
|
102
|
+
<section class="card">
|
|
103
|
+
<h2>Cache simulation (${esc(cacheSimulation.provider)})</h2>
|
|
104
|
+
${cacheSimulation.unavailableReason ? `<p class="muted">${esc(cacheSimulation.unavailableReason)}</p>` : ""}
|
|
105
|
+
<div class="table-scroll" tabindex="0" role="group" aria-label="Cache simulation"><table><thead><tr><th>request</th>${showSpeed ? "<th>modeled speed</th>" : ""}${openai ? "<th>mode</th>" : ""}${mixedModels ? "<th>model</th>" : ""}<th>read</th>${openai ? "<th>write 30m</th>" : "<th>write (5m)</th><th>write (1h)</th>"}<th>uncached</th><th>cost</th></tr></thead><tbody>${cacheRows}</tbody></table></div>
|
|
106
|
+
<p class="muted">total simulated: ${cacheSimulation.totalActualCostUsd !== undefined ? `$${cacheSimulation.totalActualCostUsd.toFixed(4)}` : "n/a"} · optimized simulated: ${cacheSimulation.totalOptimizedCostUsd !== undefined ? `$${cacheSimulation.totalOptimizedCostUsd.toFixed(4)}` : "n/a"}</p>
|
|
107
|
+
${savings !== undefined && savings >= 0.00005 ? `<p class="savings">Normalizing volatile text, JSON keys and tool order${cacheSimulation.provider === "anthropic" ? ", with a breakpoint on each request's last cacheable block (moving the last marker if all four slots are used)," : ""} would save $${savings.toFixed(4)} on this sequence — ≈$${Math.round(savings * 1000).toLocaleString("en-US")} per 1,000 sessions shaped like this one.</p>` : ""}
|
|
108
|
+
</section>
|
|
109
|
+
|
|
110
|
+
${duplicates.length > 0 ? `<section class="card"><h2>Duplicate content</h2><ul>${duplicateRows}</ul></section>` : ""}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
<h2>Requests</h2>
|
|
114
|
+
${requestSections}
|
|
115
|
+
|
|
116
|
+
<p class="muted">Generated by <a href="https://github.com/antonsoo/contextscope">contextscope</a>. Claude token counts are heuristic estimates (≈), not exact.</p>
|
|
117
|
+
</main></body></html>`;
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=html-report.js.map
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { analyze, countRequestTokens, parseInput, resolveModel } from "../core/index.js";
|
|
3
|
+
import { parseArgs } from "./args.js";
|
|
4
|
+
import { VERSION } from "./version.js";
|
|
5
|
+
import { renderTerminalReport } from "./terminal-report.js";
|
|
6
|
+
import { renderHtmlReport } from "./html-report.js";
|
|
7
|
+
import { readInputFile } from "./read-input.js";
|
|
8
|
+
import { toJsonReport } from "./json-report.js";
|
|
9
|
+
import { bold, red, visible } from "./ansi.js";
|
|
10
|
+
import { validateReportPaths, writeReports } from "./write-reports.js";
|
|
11
|
+
const HELP = `contextscope — see what's in your LLM context window
|
|
12
|
+
|
|
13
|
+
Usage:
|
|
14
|
+
contextscope analyze <file> [options]
|
|
15
|
+
|
|
16
|
+
<file> is JSON, a JSON array, or JSONL of Anthropic Messages or OpenAI (Chat
|
|
17
|
+
Completions or Responses) request bodies, optionally gzipped. Batch-API files
|
|
18
|
+
and logs that wrap each body in "params", "body", "request" or "request_body"
|
|
19
|
+
are unwrapped automatically. Response usage paired in the same record is compared
|
|
20
|
+
with the simulation; missing counters stay unavailable.
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--format <anthropic|openai> Override auto-detected format
|
|
24
|
+
--model <id> Price as this model (default: the model named in the requests)
|
|
25
|
+
--calibrate Anthropic only: count the largest request exactly with the
|
|
26
|
+
count_tokens endpoint (reads ANTHROPIC_API_KEY) and scale
|
|
27
|
+
every Claude estimate to match
|
|
28
|
+
--fail-on <error|warning|info> Exit with status 2 if any finding is at least this severe
|
|
29
|
+
--html <out.html> Also write a self-contained HTML report
|
|
30
|
+
--json <out.json> Also write the analysis as JSON: counts, findings and cache
|
|
31
|
+
steps for every request and segment, without the request text
|
|
32
|
+
-v, --verbose Show every request's breakdown and every prefix/cache row
|
|
33
|
+
-h, --help Show this help
|
|
34
|
+
-V, --version Show the version
|
|
35
|
+
|
|
36
|
+
Exit status: 0 on success, 1 on bad arguments or unreadable input,
|
|
37
|
+
2 when --fail-on is set and a finding meets it, input is incomplete, or reported
|
|
38
|
+
usage is invalid. Missing optional usage does not fail the analysis.
|
|
39
|
+
`;
|
|
40
|
+
function fail(message, showHelp = false) {
|
|
41
|
+
process.stderr.write(red(visible(message)) + "\n");
|
|
42
|
+
if (showHelp)
|
|
43
|
+
process.stderr.write("\n" + HELP);
|
|
44
|
+
process.exit(1);
|
|
45
|
+
}
|
|
46
|
+
async function calibrate(input, opts) {
|
|
47
|
+
const parse = parseInput(input, opts.format);
|
|
48
|
+
if (parse.format !== "anthropic")
|
|
49
|
+
fail("--calibrate uses Anthropic's count_tokens endpoint, so it only applies to Anthropic requests.");
|
|
50
|
+
if (parse.requests.some(r => r.segments.some(s => s.claudeTokensEstimate === null)))
|
|
51
|
+
fail("--calibrate cannot choose a largest request or recover unmodeled media or tool context. Keep measured counts as reported usage; a scalar calibration cannot establish missing cache boundaries.");
|
|
52
|
+
const apiKey = process.env["ANTHROPIC_API_KEY"];
|
|
53
|
+
if (!apiKey)
|
|
54
|
+
fail("--calibrate needs an Anthropic API key in ANTHROPIC_API_KEY (count_tokens is free, but authenticated).");
|
|
55
|
+
const largest = parse.requests.reduce((best, r) => (total(r) > total(best) ? r : best));
|
|
56
|
+
const model = resolveModel("anthropic", opts.model, [largest.model]);
|
|
57
|
+
return countRequestTokens(apiKey, model.id, largest, { browser: false });
|
|
58
|
+
}
|
|
59
|
+
function total(request) {
|
|
60
|
+
// Calibration rejects unmodeled media before choosing a request.
|
|
61
|
+
return request.segments.reduce((sum, s) => sum + s.claudeTokensEstimate, 0);
|
|
62
|
+
}
|
|
63
|
+
const SEVERITY_RANK = { info: 0, warning: 1, error: 2 };
|
|
64
|
+
async function main() {
|
|
65
|
+
let opts;
|
|
66
|
+
try {
|
|
67
|
+
opts = parseArgs(process.argv.slice(2));
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
fail(err.message, true);
|
|
71
|
+
}
|
|
72
|
+
if (opts.version) {
|
|
73
|
+
process.stdout.write(`contextscope ${VERSION}\n`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (opts.help) {
|
|
77
|
+
process.stdout.write(HELP);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (!opts.command)
|
|
81
|
+
fail("Missing command.", true);
|
|
82
|
+
if (opts.command !== "analyze")
|
|
83
|
+
fail(`Unknown command "${opts.command}". Only \`analyze\` is supported.`, true);
|
|
84
|
+
if (!opts.file)
|
|
85
|
+
fail("Missing input file.", true);
|
|
86
|
+
const reportPaths = [
|
|
87
|
+
...(opts.html ? [{ label: "HTML", path: opts.html }] : []),
|
|
88
|
+
...(opts.json ? [{ label: "JSON", path: opts.json }] : []),
|
|
89
|
+
];
|
|
90
|
+
try {
|
|
91
|
+
validateReportPaths(opts.file, reportPaths);
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
fail(`Could not prepare report files: ${err.message}`);
|
|
95
|
+
}
|
|
96
|
+
let input;
|
|
97
|
+
try {
|
|
98
|
+
input = readInputFile(opts.file);
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
fail(`Could not read "${opts.file}": ${err.message}`);
|
|
102
|
+
}
|
|
103
|
+
let calibration;
|
|
104
|
+
if (opts.calibrate) {
|
|
105
|
+
try {
|
|
106
|
+
calibration = await calibrate(input, opts);
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
fail(`Calibration failed: ${err.message}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
let result;
|
|
113
|
+
try {
|
|
114
|
+
result = analyze(input, { format: opts.format, model: opts.model, claudeTokenScale: calibration?.scale });
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
fail(`Could not analyze "${opts.file}": ${err.message}`);
|
|
118
|
+
}
|
|
119
|
+
process.stdout.write(renderTerminalReport(result, { verbose: opts.verbose, calibration }) + "\n");
|
|
120
|
+
try {
|
|
121
|
+
const reports = reportPaths.map((report) => ({ ...report,
|
|
122
|
+
text: report.label === "HTML" ? renderHtmlReport(result) : toJsonReport(result),
|
|
123
|
+
}));
|
|
124
|
+
writeReports(opts.file, reports);
|
|
125
|
+
for (const report of reports)
|
|
126
|
+
process.stdout.write(bold(`${report.label} report written to ${visible(report.path)}\n`));
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
fail(`Could not write reports: ${err.message}`);
|
|
130
|
+
}
|
|
131
|
+
if (opts.failOn !== undefined) {
|
|
132
|
+
const threshold = SEVERITY_RANK[opts.failOn];
|
|
133
|
+
if (!result.parse.complete || result.usageComparison.invalidRequestIndices.length > 0 || result.usageComparison.issues.length > 0 || result.findings.some((f) => SEVERITY_RANK[f.severity] >= threshold))
|
|
134
|
+
process.exitCode = 2;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
await main();
|
|
138
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { toJsonReport } from "../core/json-report.js";
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
2
|
+
import { gunzipSync } from "node:zlib";
|
|
3
|
+
import { decodeText } from "../core/decode-text.js";
|
|
4
|
+
export const MAX_INPUT_BYTES = 500 * 2 ** 20;
|
|
5
|
+
/** Bound both the input read (including pipes/growing files) and the inflated gzip output. */
|
|
6
|
+
export function readInputFile(path, maxBytes = MAX_INPUT_BYTES) {
|
|
7
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_INPUT_BYTES)
|
|
8
|
+
throw new Error("Invalid input byte limit.");
|
|
9
|
+
const mb = (n) => (n / 2 ** 20).toFixed(n < 2 ** 20 ? 3 : 0);
|
|
10
|
+
const tooLarge = () => new Error(`input exceeds the size limit; the most this tool can load at once is ${mb(maxBytes)} MB; split it, for example one session per file`);
|
|
11
|
+
const fd = openSync(path, "r");
|
|
12
|
+
const chunks = [];
|
|
13
|
+
let length = 0;
|
|
14
|
+
try {
|
|
15
|
+
if (fstatSync(fd).size > maxBytes)
|
|
16
|
+
throw tooLarge();
|
|
17
|
+
while (true) {
|
|
18
|
+
// Read at most one byte beyond the limit, even when stat cannot report the full size.
|
|
19
|
+
const chunk = Buffer.allocUnsafe(Math.min(2 ** 20, maxBytes - length + 1));
|
|
20
|
+
const read = readSync(fd, chunk);
|
|
21
|
+
if (read === 0)
|
|
22
|
+
break;
|
|
23
|
+
length += read;
|
|
24
|
+
if (length > maxBytes)
|
|
25
|
+
throw tooLarge();
|
|
26
|
+
chunks.push(chunk.subarray(0, read));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
closeSync(fd);
|
|
31
|
+
}
|
|
32
|
+
const buf = Buffer.concat(chunks, length);
|
|
33
|
+
const gzip = buf[0] === 0x1f && buf[1] === 0x8b;
|
|
34
|
+
try {
|
|
35
|
+
return decodeText(path.endsWith(".gz") || gzip ? gunzipSync(buf, { maxOutputLength: maxBytes }) : buf);
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
if (err.code === "ERR_BUFFER_TOO_LARGE")
|
|
39
|
+
throw tooLarge();
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
//# sourceMappingURL=read-input.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { AnalysisResult, CalibrationResult } from "../core/index.js";
|
|
2
|
+
export interface TerminalReportOptions {
|
|
3
|
+
/** Every request's breakdown, every prefix pair, and every cache row. */
|
|
4
|
+
verbose?: boolean;
|
|
5
|
+
calibration?: CalibrationResult | undefined;
|
|
6
|
+
}
|
|
7
|
+
export declare function renderTerminalReport(result: AnalysisResult, options?: TerminalReportOptions): string;
|