leanprompt 0.0.1 → 0.1.0-dev.8

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.
Files changed (157) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-DOCS +396 -0
  3. package/NOTICE +11 -0
  4. package/README.md +86 -3
  5. package/cli/dist/detect.d.ts +23 -0
  6. package/cli/dist/detect.js +219 -0
  7. package/cli/dist/evalAudit.d.ts +32 -0
  8. package/cli/dist/evalAudit.js +161 -0
  9. package/cli/dist/facts.d.ts +14 -0
  10. package/cli/dist/facts.js +43 -0
  11. package/cli/dist/forms.d.ts +23 -0
  12. package/cli/dist/forms.js +199 -0
  13. package/cli/dist/frontmatter.d.ts +10 -0
  14. package/cli/dist/frontmatter.js +32 -0
  15. package/cli/dist/help.d.ts +27 -0
  16. package/cli/dist/help.js +118 -0
  17. package/cli/dist/init.d.ts +78 -0
  18. package/cli/dist/init.js +358 -0
  19. package/cli/dist/install.d.ts +20 -0
  20. package/cli/dist/install.js +225 -0
  21. package/cli/dist/isMain.d.ts +6 -0
  22. package/cli/dist/isMain.js +18 -0
  23. package/cli/dist/lesson.d.ts +16 -0
  24. package/cli/dist/lesson.js +205 -0
  25. package/cli/dist/lint/facts.d.ts +7 -0
  26. package/cli/dist/lint/facts.js +163 -0
  27. package/cli/dist/lint/numbers.d.ts +26 -0
  28. package/cli/dist/lint/numbers.js +163 -0
  29. package/cli/dist/lint/rules.d.ts +20 -0
  30. package/cli/dist/lint/rules.js +170 -0
  31. package/cli/dist/log/logger.d.ts +49 -0
  32. package/cli/dist/log/logger.js +148 -0
  33. package/cli/dist/log/record.d.ts +56 -0
  34. package/cli/dist/log/record.js +117 -0
  35. package/cli/dist/main.d.ts +6 -0
  36. package/cli/dist/main.js +67 -0
  37. package/cli/dist/profile.d.ts +93 -0
  38. package/cli/dist/profile.js +372 -0
  39. package/cli/dist/report/cost.d.ts +55 -0
  40. package/cli/dist/report/cost.js +151 -0
  41. package/cli/dist/report/html.d.ts +81 -0
  42. package/cli/dist/report/html.js +555 -0
  43. package/cli/dist/report/template.html +269 -0
  44. package/cli/dist/score/calibrate.d.ts +65 -0
  45. package/cli/dist/score/calibrate.js +213 -0
  46. package/cli/dist/score/measured.d.ts +66 -0
  47. package/cli/dist/score/measured.js +191 -0
  48. package/cli/dist/score/static.d.ts +112 -0
  49. package/cli/dist/score/static.js +172 -0
  50. package/cli/dist/score/write.d.ts +29 -0
  51. package/cli/dist/score/write.js +247 -0
  52. package/forms/AGENTS.block.md +25 -0
  53. package/forms/opencode/commands/leanprompt-audit.md +10 -0
  54. package/forms/opencode/commands/leanprompt.md +8 -0
  55. package/forms/skills/generation-economy/SKILL.md +89 -0
  56. package/forms/skills/generation-economy/rules/LP-GE-01.md +93 -0
  57. package/forms/skills/generation-economy/rules/LP-GE-02.md +82 -0
  58. package/forms/skills/generation-economy/rules/LP-GE-03.md +87 -0
  59. package/forms/skills/generation-economy/rules/LP-GE-04.md +118 -0
  60. package/forms/skills/generation-economy/rules/LP-GE-05.md +84 -0
  61. package/forms/skills/generation-economy/rules/LP-GE-06.md +76 -0
  62. package/forms/skills/generation-economy/rules/LP-GE-07.md +84 -0
  63. package/forms/skills/generation-economy/rules/LP-GE-08.md +71 -0
  64. package/forms/skills/generation-economy/rules/LP-GE-09.md +79 -0
  65. package/forms/skills/generation-economy/rules/LP-GE-10.md +104 -0
  66. package/forms/skills/leanprompt/SKILL.md +48 -0
  67. package/forms/skills/leanprompt/fix.md +15 -0
  68. package/forms/skills/leanprompt/init.md +30 -0
  69. package/forms/skills/llm-call-audit/SKILL.md +169 -0
  70. package/forms/skills/llm-call-audit/call-shapes.md +99 -0
  71. package/forms/skills/llm-call-audit/presenting.md +72 -0
  72. package/forms/skills/llm-call-audit/report-template.md +113 -0
  73. package/forms/skills/lmwarden/SKILL.md +97 -0
  74. package/forms/skills/lmwarden/rules/LP-LW-01.md +73 -0
  75. package/forms/skills/lmwarden/rules/LP-LW-02.md +78 -0
  76. package/forms/skills/lmwarden/rules/LP-LW-03.md +73 -0
  77. package/forms/skills/measure-loop/SKILL.md +155 -0
  78. package/forms/skills/measure-loop/templates/stable-head.template.ts +38 -0
  79. package/forms/skills/measure-loop/templates/stable_head_template.py +40 -0
  80. package/forms/skills/prefill-cache/SKILL.md +66 -0
  81. package/forms/skills/prefill-cache/rules/LP-PC-01.md +103 -0
  82. package/forms/skills/prefill-cache/rules/LP-PC-02.md +80 -0
  83. package/forms/skills/prefill-cache/rules/LP-PC-03.md +75 -0
  84. package/forms/skills/prefill-cache/rules/LP-PC-04.md +79 -0
  85. package/forms/skills/prefill-cache/rules/LP-PC-05.md +68 -0
  86. package/forms/skills/prefill-cache/rules/LP-PC-06.md +71 -0
  87. package/forms/skills/prefill-cache/rules/LP-PC-07.md +97 -0
  88. package/forms/skills/prefill-cache/rules/LP-PC-08.md +67 -0
  89. package/forms/skills/prefill-cache/rules/LP-PC-09.md +75 -0
  90. package/forms/skills/prefill-cache/rules/LP-PC-10.md +76 -0
  91. package/forms/skills/prefill-cache/rules/LP-PC-11.md +72 -0
  92. package/forms/skills/prefill-cache/rules/LP-PC-12.md +73 -0
  93. package/forms/skills/prompt-diet/SKILL.md +69 -0
  94. package/forms/skills/prompt-diet/rules/LP-PD-01.md +79 -0
  95. package/forms/skills/prompt-diet/rules/LP-PD-02.md +73 -0
  96. package/forms/skills/prompt-diet/rules/LP-PD-03.md +65 -0
  97. package/forms/skills/prompt-diet/rules/LP-PD-04.md +77 -0
  98. package/forms/skills/prompt-diet/rules/LP-PD-05.md +71 -0
  99. package/forms/skills/prompt-diet/rules/LP-PD-06.md +68 -0
  100. package/models/anthropic-thinking.md +38 -0
  101. package/models/openai-reasoning.md +35 -0
  102. package/models/qwen.md +34 -0
  103. package/package.json +31 -8
  104. package/providers/anthropic.md +83 -0
  105. package/providers/deepinfra.md +46 -0
  106. package/providers/gemini.md +61 -0
  107. package/providers/openai.md +73 -0
  108. package/providers/openrouter.md +66 -0
  109. package/providers/sglang.md +41 -0
  110. package/providers/vllm.md +52 -0
  111. package/runtimes/http-clients.md +20 -0
  112. package/skills/_template/RULE.md +31 -0
  113. package/skills/generation-economy/SKILL.md +88 -0
  114. package/skills/generation-economy/rules/LP-GE-01.md +92 -0
  115. package/skills/generation-economy/rules/LP-GE-02.md +81 -0
  116. package/skills/generation-economy/rules/LP-GE-03.md +86 -0
  117. package/skills/generation-economy/rules/LP-GE-04.md +117 -0
  118. package/skills/generation-economy/rules/LP-GE-05.md +83 -0
  119. package/skills/generation-economy/rules/LP-GE-06.md +75 -0
  120. package/skills/generation-economy/rules/LP-GE-07.md +83 -0
  121. package/skills/generation-economy/rules/LP-GE-08.md +70 -0
  122. package/skills/generation-economy/rules/LP-GE-09.md +78 -0
  123. package/skills/generation-economy/rules/LP-GE-10.md +103 -0
  124. package/skills/leanprompt/SKILL.md +47 -0
  125. package/skills/leanprompt/fix.md +14 -0
  126. package/skills/leanprompt/init.md +29 -0
  127. package/skills/llm-call-audit/SKILL.md +168 -0
  128. package/skills/llm-call-audit/call-shapes.md +98 -0
  129. package/skills/llm-call-audit/presenting.md +71 -0
  130. package/skills/llm-call-audit/report-template.md +112 -0
  131. package/skills/lmwarden/SKILL.md +96 -0
  132. package/skills/lmwarden/rules/LP-LW-01.md +72 -0
  133. package/skills/lmwarden/rules/LP-LW-02.md +77 -0
  134. package/skills/lmwarden/rules/LP-LW-03.md +72 -0
  135. package/skills/measure-loop/SKILL.md +154 -0
  136. package/skills/measure-loop/templates/stable-head.template.ts +38 -0
  137. package/skills/measure-loop/templates/stable_head_template.py +40 -0
  138. package/skills/prefill-cache/SKILL.md +65 -0
  139. package/skills/prefill-cache/rules/LP-PC-01.md +102 -0
  140. package/skills/prefill-cache/rules/LP-PC-02.md +79 -0
  141. package/skills/prefill-cache/rules/LP-PC-03.md +74 -0
  142. package/skills/prefill-cache/rules/LP-PC-04.md +78 -0
  143. package/skills/prefill-cache/rules/LP-PC-05.md +67 -0
  144. package/skills/prefill-cache/rules/LP-PC-06.md +70 -0
  145. package/skills/prefill-cache/rules/LP-PC-07.md +96 -0
  146. package/skills/prefill-cache/rules/LP-PC-08.md +66 -0
  147. package/skills/prefill-cache/rules/LP-PC-09.md +74 -0
  148. package/skills/prefill-cache/rules/LP-PC-10.md +75 -0
  149. package/skills/prefill-cache/rules/LP-PC-11.md +71 -0
  150. package/skills/prefill-cache/rules/LP-PC-12.md +72 -0
  151. package/skills/prompt-diet/SKILL.md +68 -0
  152. package/skills/prompt-diet/rules/LP-PD-01.md +78 -0
  153. package/skills/prompt-diet/rules/LP-PD-02.md +72 -0
  154. package/skills/prompt-diet/rules/LP-PD-03.md +64 -0
  155. package/skills/prompt-diet/rules/LP-PD-04.md +76 -0
  156. package/skills/prompt-diet/rules/LP-PD-05.md +70 -0
  157. package/skills/prompt-diet/rules/LP-PD-06.md +67 -0
@@ -0,0 +1,93 @@
1
+ import type { CacheFacts } from "./facts.js";
2
+ export declare const ENGINES: readonly ["vllm", "sglang", "llama.cpp", "lm-warden"];
3
+ export type Engine = (typeof ENGINES)[number];
4
+ export interface EngineFacts {
5
+ block_tokens?: number;
6
+ match_unit_tokens?: number;
7
+ speculative?: boolean;
8
+ kv_memory_gb?: number;
9
+ /** Measured prefill throughput of the engine, for the GPU time a finding costs. */
10
+ prefill_tokens_per_second?: number;
11
+ }
12
+ /** How many calls the app (or one backend) makes a month; `source` says where the number came from. */
13
+ export interface Volume {
14
+ calls_per_month: number;
15
+ source?: string;
16
+ }
17
+ /** Prices for one model, in US dollars per 1M tokens, with where they came from and when they were checked. */
18
+ export interface Price {
19
+ input: number;
20
+ output: number;
21
+ cached_input?: number;
22
+ cache_write?: number;
23
+ source: string;
24
+ /** YYYY-MM-DD */
25
+ checked: string;
26
+ }
27
+ /** One backend: a hosted provider or a self-hosted engine (exactly one in a `targets` entry). */
28
+ export interface Target {
29
+ provider?: string;
30
+ engine?: Engine;
31
+ model_family?: string;
32
+ context_tokens?: number;
33
+ /** `targets` entries only: globs of the files whose calls go to this backend (for the audit). */
34
+ files?: string[];
35
+ /** `targets` engine entries only: this engine's cache facts, in place of the top-level `engine:`. */
36
+ engine_facts?: EngineFacts;
37
+ /** `targets` entries only: this backend's monthly call volume. */
38
+ volume?: Volume;
39
+ }
40
+ export interface Profile {
41
+ /** The single target. Empty when the profile uses `targets`. */
42
+ target: Target;
43
+ /** Several backends, for an app that calls more than one (issue #4). Absent when `target` is used. */
44
+ targets?: Target[];
45
+ engine?: EngineFacts;
46
+ priority: {
47
+ cost: number;
48
+ speed: number;
49
+ quality: number;
50
+ };
51
+ ignore?: {
52
+ rule: string;
53
+ file: string;
54
+ }[];
55
+ /** Calls a month, for the money estimate. With `targets`, each entry carries its own instead. */
56
+ volume?: Volume;
57
+ /** Model name -> price, for the money estimate. */
58
+ prices?: Record<string, Price>;
59
+ }
60
+ /** Parse and validate the text of a leanprompt.yaml. Never throws; problems come back in `errors`. */
61
+ export declare function parseProfile(text: string): {
62
+ profile?: Profile;
63
+ errors: string[];
64
+ };
65
+ /** Read `<dir>/leanprompt.yaml`. Null when the file is absent; throws with every error when it is invalid. */
66
+ export declare function loadProfile(dir: string): Profile | null;
67
+ /** A usage record (or a caller) names no backend the profile can pick on its own: never guessed. */
68
+ export declare class AmbiguousTargetError extends Error {
69
+ readonly code = "ambiguous_target";
70
+ constructor(provider: string | undefined, count: number);
71
+ }
72
+ /** The profile's targets: the `targets` list, or the single `target` when it names a provider or engine. */
73
+ export declare function profileTargets(p: Profile): Target[];
74
+ /**
75
+ * Key into the provider cache tables for a profile with one target: the engine's table if `engine` is
76
+ * set, else `provider`, else null. Throws `AmbiguousTargetError` when the profile lists several targets.
77
+ */
78
+ export declare function targetKey(p: Profile): string | null;
79
+ /**
80
+ * The cache facts with the profile's engine values laid over them. `provider` is optional:
81
+ * when omitted the key comes from the profile's one target (callers holding a usage record pass the
82
+ * record's provider). Resolution, for a record:
83
+ * 1. A provider that names an engine (`lm-warden`, `vllm`, `sglang`, `llama.cpp`) goes through the
84
+ * engine table; the engine facts are those of the `targets` entry for that engine, else `engine:`.
85
+ * 2. A provider with its own table uses it.
86
+ * 3. A provider with no table of its own (an OpenAI-compatible host such as groq or together) falls back
87
+ * to the `targets` entry whose `provider` is that name (it has no table either, so: unknown provider),
88
+ * else to the single target. With several targets and no match it throws `AmbiguousTargetError`:
89
+ * the record is unmeasured (`ambiguous_target`), never guessed.
90
+ * Engine values apply only to block-mode (self-hosted) tables.
91
+ * `match_unit_tokens` replaces the block size (E9); `speculative` sets whether the last block is dropped.
92
+ */
93
+ export declare function effectiveFacts(p: Profile | null, facts: Map<string, CacheFacts>, provider?: string): CacheFacts;
@@ -0,0 +1,372 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { parse } from "yaml";
4
+ export const ENGINES = ["vllm", "sglang", "llama.cpp", "lm-warden"];
5
+ const KEYS = ["target", "targets", "engine", "priority", "ignore", "volume", "prices"];
6
+ const TARGET_KEYS = ["provider", "engine", "model_family", "context_tokens"];
7
+ const TARGETS_ENTRY_KEYS = [...TARGET_KEYS, "files", "engine_facts", "volume"];
8
+ const ENGINE_KEYS = ["block_tokens", "match_unit_tokens", "speculative", "kv_memory_gb", "prefill_tokens_per_second"];
9
+ const PRICE_KEYS = ["input", "output", "cached_input", "cache_write", "source", "checked"];
10
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
11
+ const PRIORITIES = ["cost", "speed", "quality"];
12
+ const isMap = (v) => !!v && typeof v === "object" && !Array.isArray(v);
13
+ const isNum = (v) => typeof v === "number" && Number.isFinite(v);
14
+ const isPosInt = (v) => isNum(v) && Number.isInteger(v) && v > 0;
15
+ const isStr = (v) => typeof v === "string" && v.trim() !== "";
16
+ function unknownKeys(m, allowed, prefix, errors) {
17
+ for (const k of Object.keys(m))
18
+ if (!allowed.includes(k))
19
+ errors.push(`unknown key: ${prefix}${k}`);
20
+ }
21
+ function section(raw, name, errors) {
22
+ if (raw === undefined || raw === null)
23
+ return undefined;
24
+ if (!isMap(raw)) {
25
+ errors.push(`${name} must be a mapping`);
26
+ return undefined;
27
+ }
28
+ return raw;
29
+ }
30
+ function parseTargetFields(t, out, at, errors) {
31
+ if (t.provider !== undefined)
32
+ isStr(t.provider) ? (out.provider = t.provider) : errors.push(`${at}.provider must be a string`);
33
+ if (t.engine !== undefined) {
34
+ if (typeof t.engine === "string" && ENGINES.includes(t.engine))
35
+ out.engine = t.engine;
36
+ else
37
+ errors.push(`${at}.engine must be one of ${ENGINES.join(", ")}`);
38
+ }
39
+ if (t.model_family !== undefined)
40
+ isStr(t.model_family) ? (out.model_family = t.model_family) : errors.push(`${at}.model_family must be a string`);
41
+ if (t.context_tokens !== undefined)
42
+ isPosInt(t.context_tokens) ? (out.context_tokens = t.context_tokens) : errors.push(`${at}.context_tokens must be a positive integer`);
43
+ }
44
+ function parseEngineFacts(raw, at, errors) {
45
+ const e = section(raw, at, errors);
46
+ if (!e)
47
+ return undefined;
48
+ unknownKeys(e, ENGINE_KEYS, `${at}.`, errors);
49
+ const engine = {};
50
+ for (const k of ["block_tokens", "match_unit_tokens"]) {
51
+ if (e[k] !== undefined)
52
+ isPosInt(e[k]) ? (engine[k] = e[k]) : errors.push(`${at}.${k} must be a positive integer`);
53
+ }
54
+ if (e.speculative !== undefined)
55
+ typeof e.speculative === "boolean" ? (engine.speculative = e.speculative) : errors.push(`${at}.speculative must be true or false`);
56
+ if (e.kv_memory_gb !== undefined)
57
+ isNum(e.kv_memory_gb) && e.kv_memory_gb > 0 ? (engine.kv_memory_gb = e.kv_memory_gb) : errors.push(`${at}.kv_memory_gb must be a positive number`);
58
+ if (e.prefill_tokens_per_second !== undefined) {
59
+ isNum(e.prefill_tokens_per_second) && e.prefill_tokens_per_second > 0
60
+ ? (engine.prefill_tokens_per_second = e.prefill_tokens_per_second)
61
+ : errors.push(`${at}.prefill_tokens_per_second must be a positive number`);
62
+ }
63
+ return engine;
64
+ }
65
+ function parseVolume(raw, at, errors) {
66
+ if (raw === undefined || raw === null)
67
+ return undefined;
68
+ if (!isMap(raw))
69
+ return void errors.push(`${at} must be a mapping: {calls_per_month: N}`);
70
+ unknownKeys(raw, ["calls_per_month", "source"], `${at}.`, errors);
71
+ if (!isPosInt(raw.calls_per_month))
72
+ return void errors.push(`${at}.calls_per_month must be a positive integer`);
73
+ const v = { calls_per_month: raw.calls_per_month };
74
+ if (raw.source !== undefined)
75
+ isStr(raw.source) ? (v.source = raw.source) : errors.push(`${at}.source must be a string`);
76
+ return v;
77
+ }
78
+ /** A YAML date may arrive as a string or, under some schemas, a Date. */
79
+ const dateText = (v) => v instanceof Date && !Number.isNaN(v.getTime()) ? v.toISOString().slice(0, 10) : typeof v === "string" && DATE.test(v) ? v : undefined;
80
+ function parsePrices(raw, errors) {
81
+ if (raw === undefined || raw === null)
82
+ return undefined;
83
+ if (!isMap(raw))
84
+ return void errors.push("prices must be a mapping of model name to price");
85
+ const out = {};
86
+ for (const [model, p] of Object.entries(raw)) {
87
+ const at = `prices.${model}`;
88
+ if (!isMap(p)) {
89
+ errors.push(`${at} must be a mapping`);
90
+ continue;
91
+ }
92
+ unknownKeys(p, PRICE_KEYS, `${at}.`, errors);
93
+ let ok = true;
94
+ const price = { source: "", checked: "" };
95
+ for (const k of ["input", "output", "cached_input", "cache_write"]) {
96
+ const v = p[k];
97
+ if (v === undefined) {
98
+ if (k === "input" || k === "output") {
99
+ errors.push(`${at}.${k} is required (US dollars per 1M tokens)`);
100
+ ok = false;
101
+ }
102
+ }
103
+ else if (isNum(v) && v >= 0)
104
+ price[k] = v;
105
+ else {
106
+ errors.push(`${at}.${k} must be a number >= 0 (US dollars per 1M tokens)`);
107
+ ok = false;
108
+ }
109
+ }
110
+ if (isStr(p.source))
111
+ price.source = p.source;
112
+ else {
113
+ errors.push(`${at}.source is required: the pricing page's URL, or where your own price comes from`);
114
+ ok = false;
115
+ }
116
+ const checked = dateText(p.checked);
117
+ if (checked)
118
+ price.checked = checked;
119
+ else {
120
+ errors.push(`${at}.checked is required: the date the price was read, as YYYY-MM-DD`);
121
+ ok = false;
122
+ }
123
+ if (ok)
124
+ out[model] = price;
125
+ }
126
+ return out;
127
+ }
128
+ function parsePriority(raw, errors) {
129
+ const third = 1 / 3;
130
+ const equal = { cost: third, speed: third, quality: third };
131
+ if (raw === undefined || raw === null)
132
+ return equal;
133
+ if (typeof raw === "string") {
134
+ if (PRIORITIES.includes(raw)) {
135
+ return { cost: 0, speed: 0, quality: 0, [raw]: 1 };
136
+ }
137
+ errors.push("priority must be cost, speed, quality or a weights object");
138
+ return equal;
139
+ }
140
+ if (!isMap(raw)) {
141
+ errors.push("priority must be cost, speed, quality or a weights object");
142
+ return equal;
143
+ }
144
+ unknownKeys(raw, [...PRIORITIES], "priority.", errors);
145
+ const w = {};
146
+ let ok = true;
147
+ for (const k of PRIORITIES) {
148
+ const v = raw[k];
149
+ if (!isNum(v) || v < 0) {
150
+ errors.push(`priority.${k} must be a number >= 0`);
151
+ ok = false;
152
+ }
153
+ else
154
+ w[k] = v;
155
+ }
156
+ if (!ok)
157
+ return equal;
158
+ if (Math.abs(w.cost + w.speed + w.quality - 1) > 0.01) {
159
+ errors.push("priority weights must sum to 1");
160
+ return equal;
161
+ }
162
+ return w;
163
+ }
164
+ /** Parse and validate the text of a leanprompt.yaml. Never throws; problems come back in `errors`. */
165
+ export function parseProfile(text) {
166
+ const errors = [];
167
+ let doc;
168
+ try {
169
+ doc = parse(text);
170
+ }
171
+ catch (e) {
172
+ return { errors: [`invalid YAML: ${e.message.split("\n")[0]}`] };
173
+ }
174
+ if (doc === null || doc === undefined)
175
+ doc = {};
176
+ if (!isMap(doc))
177
+ return { errors: ["leanprompt.yaml must be a mapping"] };
178
+ unknownKeys(doc, KEYS, "", errors);
179
+ const target = {};
180
+ const t = section(doc.target, "target", errors);
181
+ if (t) {
182
+ unknownKeys(t, TARGET_KEYS, "target.", errors);
183
+ parseTargetFields(t, target, "target", errors);
184
+ }
185
+ let targets;
186
+ if (doc.targets !== undefined && doc.targets !== null) {
187
+ if (!Array.isArray(doc.targets) || doc.targets.length === 0)
188
+ errors.push("targets must be a non-empty list of entries");
189
+ else {
190
+ targets = [];
191
+ doc.targets.forEach((raw, i) => {
192
+ const at = `targets[${i}]`;
193
+ if (!isMap(raw))
194
+ return void errors.push(`${at} must be a mapping`);
195
+ unknownKeys(raw, TARGETS_ENTRY_KEYS, `${at}.`, errors);
196
+ const entry = {};
197
+ parseTargetFields(raw, entry, at, errors);
198
+ if (raw.provider !== undefined && raw.engine !== undefined)
199
+ errors.push(`${at}: set provider or engine, not both`);
200
+ else if (raw.provider === undefined && raw.engine === undefined)
201
+ errors.push(`${at}: set provider or engine`);
202
+ if (raw.files !== undefined) {
203
+ if (Array.isArray(raw.files) && raw.files.length > 0 && raw.files.every(isStr))
204
+ entry.files = raw.files;
205
+ else
206
+ errors.push(`${at}.files must be a list of glob strings`);
207
+ }
208
+ if (raw.engine_facts !== undefined) {
209
+ if (raw.engine === undefined)
210
+ errors.push(`${at}.engine_facts applies only to an engine entry`);
211
+ else {
212
+ const f = parseEngineFacts(raw.engine_facts, `${at}.engine_facts`, errors);
213
+ if (f)
214
+ entry.engine_facts = f;
215
+ }
216
+ }
217
+ const vol = parseVolume(raw.volume, `${at}.volume`, errors);
218
+ if (vol)
219
+ entry.volume = vol;
220
+ targets.push(entry);
221
+ });
222
+ }
223
+ }
224
+ const engine = parseEngineFacts(doc.engine, "engine", errors);
225
+ const priority = parsePriority(doc.priority, errors);
226
+ const volume = parseVolume(doc.volume, "volume", errors);
227
+ const prices = parsePrices(doc.prices, errors);
228
+ if (doc.volume !== undefined && doc.volume !== null && doc.targets !== undefined && doc.targets !== null) {
229
+ errors.push("with targets, set volume on each targets entry, not at the top level");
230
+ }
231
+ let ignore;
232
+ if (doc.ignore !== undefined && doc.ignore !== null) {
233
+ if (!Array.isArray(doc.ignore))
234
+ errors.push("ignore must be a list of {rule, file} entries");
235
+ else {
236
+ ignore = [];
237
+ doc.ignore.forEach((it, i) => {
238
+ if (isMap(it) && isStr(it.rule) && isStr(it.file)) {
239
+ unknownKeys(it, ["rule", "file"], `ignore[${i}].`, errors);
240
+ ignore.push({ rule: it.rule, file: it.file });
241
+ }
242
+ else
243
+ errors.push(`ignore[${i}] must have a rule and a file`);
244
+ });
245
+ }
246
+ }
247
+ if (target.provider !== undefined && target.engine !== undefined)
248
+ errors.push("set target.provider or target.engine, not both");
249
+ if (t && doc.targets !== undefined && doc.targets !== null)
250
+ errors.push("set target or targets, not both");
251
+ if (engine && targets && targets.filter((x) => x.engine !== undefined).length > 1) {
252
+ errors.push("with several engine entries in targets, give each its own engine_facts instead of a top-level engine:");
253
+ }
254
+ if (errors.length)
255
+ return { errors };
256
+ const profile = { target, priority };
257
+ if (targets)
258
+ profile.targets = targets;
259
+ if (engine)
260
+ profile.engine = engine;
261
+ if (ignore)
262
+ profile.ignore = ignore;
263
+ if (volume)
264
+ profile.volume = volume;
265
+ if (prices)
266
+ profile.prices = prices;
267
+ return { profile, errors };
268
+ }
269
+ /** Read `<dir>/leanprompt.yaml`. Null when the file is absent; throws with every error when it is invalid. */
270
+ export function loadProfile(dir) {
271
+ const file = join(dir, "leanprompt.yaml");
272
+ if (!existsSync(file))
273
+ return null;
274
+ const { profile, errors } = parseProfile(readFileSync(file, "utf8"));
275
+ if (!profile)
276
+ throw new Error(`${file}: ${errors.join("; ")}`);
277
+ return profile;
278
+ }
279
+ /** Engines served through another engine's cache table. */
280
+ const ENGINE_TABLE = { vllm: "vllm", sglang: "sglang", "lm-warden": "vllm", "llama.cpp": null };
281
+ /** A usage record (or a caller) names no backend the profile can pick on its own: never guessed. */
282
+ export class AmbiguousTargetError extends Error {
283
+ code = "ambiguous_target";
284
+ constructor(provider, count) {
285
+ super(`ambiguous_target: ${provider === undefined ? "no provider given" : `provider ${provider} has no cache table and matches no entry`} among the ${count} targets in leanprompt.yaml`);
286
+ }
287
+ }
288
+ /** The profile's targets: the `targets` list, or the single `target` when it names a provider or engine. */
289
+ export function profileTargets(p) {
290
+ if (p.targets)
291
+ return p.targets;
292
+ return p.target.provider !== undefined || p.target.engine !== undefined ? [p.target] : [];
293
+ }
294
+ /** Table key of one target: the engine's table if it names an engine, else its provider. */
295
+ const keyOf = (t) => (t.engine ? ENGINE_TABLE[t.engine] : (t.provider ?? null));
296
+ /**
297
+ * Key into the provider cache tables for a profile with one target: the engine's table if `engine` is
298
+ * set, else `provider`, else null. Throws `AmbiguousTargetError` when the profile lists several targets.
299
+ */
300
+ export function targetKey(p) {
301
+ const ts = profileTargets(p);
302
+ if (ts.length > 1)
303
+ throw new AmbiguousTargetError(undefined, ts.length);
304
+ return ts[0] ? keyOf(ts[0]) : null;
305
+ }
306
+ /** The engine facts that apply to one engine target: its own `engine_facts`, else the top-level `engine:`. */
307
+ const engineFactsFor = (p, t) => t?.engine_facts ?? p?.engine;
308
+ /**
309
+ * The cache facts with the profile's engine values laid over them. `provider` is optional:
310
+ * when omitted the key comes from the profile's one target (callers holding a usage record pass the
311
+ * record's provider). Resolution, for a record:
312
+ * 1. A provider that names an engine (`lm-warden`, `vllm`, `sglang`, `llama.cpp`) goes through the
313
+ * engine table; the engine facts are those of the `targets` entry for that engine, else `engine:`.
314
+ * 2. A provider with its own table uses it.
315
+ * 3. A provider with no table of its own (an OpenAI-compatible host such as groq or together) falls back
316
+ * to the `targets` entry whose `provider` is that name (it has no table either, so: unknown provider),
317
+ * else to the single target. With several targets and no match it throws `AmbiguousTargetError`:
318
+ * the record is unmeasured (`ambiguous_target`), never guessed.
319
+ * Engine values apply only to block-mode (self-hosted) tables.
320
+ * `match_unit_tokens` replaces the block size (E9); `speculative` sets whether the last block is dropped.
321
+ */
322
+ export function effectiveFacts(p, facts, provider) {
323
+ const ts = p ? profileTargets(p) : [];
324
+ let key = provider;
325
+ let chosen;
326
+ if (key !== undefined && ENGINES.includes(key)) {
327
+ const table = ENGINE_TABLE[key];
328
+ if (table === null)
329
+ throw new Error(`no cache facts for ${key} yet`);
330
+ chosen = ts.find((t) => t.engine === key);
331
+ key = table;
332
+ }
333
+ else if (key !== undefined && !facts.has(key) && p) {
334
+ const match = ts.find((t) => t.provider === key);
335
+ if (match)
336
+ chosen = match;
337
+ else if (ts.length > 1)
338
+ throw new AmbiguousTargetError(key, ts.length);
339
+ else if (ts.length === 1) {
340
+ chosen = ts[0];
341
+ key = keyOf(chosen) ?? key;
342
+ }
343
+ }
344
+ if (key === undefined) {
345
+ if (!p)
346
+ throw new Error("no provider given and no profile to read one from");
347
+ if (ts.length > 1)
348
+ throw new AmbiguousTargetError(undefined, ts.length);
349
+ chosen = ts[0];
350
+ key = chosen ? (keyOf(chosen) ?? undefined) : undefined;
351
+ if (key === undefined) {
352
+ if (chosen?.engine)
353
+ throw new Error(`no cache facts for ${chosen.engine} yet`);
354
+ throw new Error("profile sets neither target.provider nor target.engine");
355
+ }
356
+ }
357
+ const base = facts.get(key);
358
+ if (!base)
359
+ throw new Error(`unknown provider: ${key}`);
360
+ const ef = engineFactsFor(p, chosen);
361
+ if (!ef || base.mode !== "block")
362
+ return base;
363
+ const out = { ...base };
364
+ const { block_tokens, match_unit_tokens, speculative } = ef;
365
+ if (block_tokens !== undefined)
366
+ out.block_tokens = block_tokens;
367
+ if (match_unit_tokens !== undefined)
368
+ out.block_tokens = match_unit_tokens;
369
+ if (speculative !== undefined)
370
+ out.drops_last_block = speculative;
371
+ return out;
372
+ }
@@ -0,0 +1,55 @@
1
+ import { type Price, type Profile } from "../profile.js";
2
+ import { type AverageCall, type Finding } from "../score/static.js";
3
+ /**
4
+ * What the findings cost, from the audit's token estimates and the user's own volume and dated prices
5
+ * in leanprompt.yaml. Money is never part of the score; this is a separate, labelled estimate, and it is
6
+ * only computed when a volume and a dated price are both present. Nothing here is invented: a missing
7
+ * input leaves the figure out and names the input in `missing`.
8
+ */
9
+ export interface CostRow {
10
+ finding: Finding;
11
+ /** prompt + uncached + output tokens per 1,000 calls. */
12
+ tokens: number;
13
+ dollars_per_month?: number;
14
+ /** Average seconds this finding adds to a call's first-token time on a self-hosted engine. */
15
+ ttft_seconds?: number;
16
+ gpu_hours_per_month?: number;
17
+ model?: string;
18
+ }
19
+ export interface CostSummary {
20
+ rows: CostRow[];
21
+ /** Open findings that are not open questions, with tokens. */
22
+ tokens_per_1k: number;
23
+ question_tokens_per_1k: number;
24
+ with_tokens: number;
25
+ measured: boolean;
26
+ /** Smallest number of calls behind a measured figure, when `measured`. */
27
+ measured_calls?: number;
28
+ money?: {
29
+ calls_per_month: number;
30
+ volume_source?: string;
31
+ lost_per_month: number;
32
+ saved_if_fixed: number;
33
+ saved_by_fixes?: number;
34
+ questions_per_month?: number;
35
+ bill_per_month?: number;
36
+ percent?: number;
37
+ prices: {
38
+ model: string;
39
+ price: Price;
40
+ }[];
41
+ };
42
+ gpu?: {
43
+ calls_per_month: number;
44
+ prefill_tokens_per_second: number;
45
+ hours_per_month: number;
46
+ };
47
+ /** One entry per missing input: what to add to leanprompt.yaml, a tab, and what it is. */
48
+ missing: string[];
49
+ average_call?: AverageCall;
50
+ }
51
+ export declare function costSummary(findings: readonly Finding[], profile: Profile | null, average_call?: AverageCall): CostSummary;
52
+ /** 950, 138k, 1.5M */
53
+ export declare function formatTokens(n: number): string;
54
+ /** $0.48, $12, $1,235 */
55
+ export declare function formatDollars(n: number): string;
@@ -0,0 +1,151 @@
1
+ import { profileTargets } from "../profile.js";
2
+ import { isOpenQuestion } from "../score/static.js";
3
+ const tokensOf = (f) => (f.tokens_per_1k?.prompt ?? 0) + (f.tokens_per_1k?.uncached ?? 0) + (f.tokens_per_1k?.output ?? 0);
4
+ function volumeOf(p) {
5
+ if (!p)
6
+ return undefined;
7
+ if (p.targets) {
8
+ if (!p.targets.every((t) => t.volume))
9
+ return undefined;
10
+ const sources = p.targets.map((t) => t.volume.source).filter((s) => !!s);
11
+ const v = { calls_per_month: p.targets.reduce((n, t) => n + t.volume.calls_per_month, 0) };
12
+ if (sources.length)
13
+ v.source = sources.join("; ");
14
+ return v;
15
+ }
16
+ return p.volume;
17
+ }
18
+ /** The one prefill throughput the profile gives, from `engine:` or an engine entry's `engine_facts`. */
19
+ function throughput(p) {
20
+ if (!p)
21
+ return undefined;
22
+ const all = new Set();
23
+ if (p.engine?.prefill_tokens_per_second)
24
+ all.add(p.engine.prefill_tokens_per_second);
25
+ for (const t of profileTargets(p))
26
+ if (t.engine_facts?.prefill_tokens_per_second)
27
+ all.add(t.engine_facts.prefill_tokens_per_second);
28
+ return all.size === 1 ? [...all][0] : undefined;
29
+ }
30
+ /** US dollars per 1,000 calls for one finding at one price, or a reason it cannot be priced. */
31
+ function dollarsPer1k(f, price) {
32
+ const t = f.tokens_per_1k ?? {};
33
+ if ((t.uncached ?? 0) > 0 && price.cached_input === undefined)
34
+ return "cached_input";
35
+ const perM = (t.prompt ?? 0) * price.input + (t.uncached ?? 0) * (price.input - (price.cached_input ?? 0)) + (t.output ?? 0) * price.output;
36
+ return perM / 1e6;
37
+ }
38
+ export function costSummary(findings, profile, average_call) {
39
+ const prices = profile?.prices ?? {};
40
+ const models = Object.keys(prices);
41
+ const volume = volumeOf(profile);
42
+ const tps = throughput(profile);
43
+ const missing = new Set();
44
+ const usedPrices = new Map();
45
+ const rows = [];
46
+ const priceFor = (f) => (f.model ? (prices[f.model] ? f.model : undefined) : models.length === 1 ? models[0] : undefined);
47
+ for (const f of findings) {
48
+ if (!f.tokens_per_1k)
49
+ continue;
50
+ const row = { finding: f, tokens: tokensOf(f) };
51
+ const model = priceFor(f);
52
+ if (model && volume) {
53
+ const d = dollarsPer1k(f, prices[model]);
54
+ if (typeof d === "number") {
55
+ row.dollars_per_month = (d * volume.calls_per_month) / 1000;
56
+ row.model = model;
57
+ usedPrices.set(model, prices[model]);
58
+ }
59
+ else {
60
+ missing.add(`prices.${model}.cached_input\tthe cached-input price, to price the tokens the cache could have served`);
61
+ }
62
+ }
63
+ else if (!f.fixed) {
64
+ if (!model && models.length > 1)
65
+ missing.add(`"model" on each finding\twhich of the models in prices: its calls use`);
66
+ if (!model && models.length > 0 && f.model)
67
+ missing.add(`prices.${f.model}\tthe price of the model this finding names`);
68
+ }
69
+ if (tps) {
70
+ const prefill = (f.tokens_per_1k.uncached ?? 0) + (f.tokens_per_1k.prompt ?? 0);
71
+ if ((f.tokens_per_1k.uncached ?? 0) > 0)
72
+ row.ttft_seconds = (f.tokens_per_1k.uncached / 1000) / tps;
73
+ if (volume && prefill > 0)
74
+ row.gpu_hours_per_month = ((prefill / 1000) * volume.calls_per_month) / tps / 3600;
75
+ }
76
+ rows.push(row);
77
+ }
78
+ const open = rows.filter((r) => !r.finding.fixed && !isOpenQuestion(r.finding));
79
+ const questions = rows.filter((r) => !r.finding.fixed && isOpenQuestion(r.finding));
80
+ const fixed = rows.filter((r) => r.finding.fixed);
81
+ const sum = (rs, k) => rs.reduce((n, r) => n + (r[k] ?? 0), 0);
82
+ const scored = rows.filter((r) => !r.finding.fixed);
83
+ const measuredCalls = scored.map((r) => r.finding.tokens_per_1k.measured_calls);
84
+ const measured = scored.length > 0 && measuredCalls.every((n) => n !== undefined);
85
+ const out = {
86
+ rows,
87
+ tokens_per_1k: sum(open, "tokens"),
88
+ question_tokens_per_1k: sum(questions, "tokens"),
89
+ with_tokens: open.length,
90
+ measured,
91
+ missing: [],
92
+ };
93
+ if (measured)
94
+ out.measured_calls = Math.min(...measuredCalls);
95
+ if (average_call)
96
+ out.average_call = average_call;
97
+ if (!volume)
98
+ missing.add("volume: {calls_per_month: N}\thow many calls the app makes a month (with targets:, on each entry)");
99
+ if (models.length === 0 && !tps) {
100
+ missing.add("prices\tper model: input, cached_input and output in US dollars per 1M tokens, with source and checked date (or, self-hosted, engine: {prefill_tokens_per_second: N})");
101
+ }
102
+ const openPriced = open.filter((r) => r.dollars_per_month !== undefined);
103
+ if (volume && openPriced.length > 0 && openPriced.length === open.length) {
104
+ const lost = sum(open, "dollars_per_month");
105
+ const money = {
106
+ calls_per_month: volume.calls_per_month,
107
+ lost_per_month: lost,
108
+ saved_if_fixed: lost,
109
+ prices: [...usedPrices].map(([model, price]) => ({ model, price })),
110
+ };
111
+ if (volume.source)
112
+ money.volume_source = volume.source;
113
+ if (fixed.some((r) => r.dollars_per_month !== undefined))
114
+ money.saved_by_fixes = sum(fixed, "dollars_per_month");
115
+ if (questions.some((r) => r.dollars_per_month !== undefined))
116
+ money.questions_per_month = sum(questions, "dollars_per_month");
117
+ if (average_call && usedPrices.size === 1) {
118
+ const p = [...usedPrices.values()][0];
119
+ money.bill_per_month = (volume.calls_per_month * (average_call.prompt_tokens * p.input + average_call.output_tokens * p.output)) / 1e6;
120
+ if (money.bill_per_month > 0)
121
+ money.percent = (100 * lost) / money.bill_per_month;
122
+ }
123
+ out.money = money;
124
+ }
125
+ if (tps && volume) {
126
+ const hours = sum(open, "gpu_hours_per_month");
127
+ if (hours > 0)
128
+ out.gpu = { calls_per_month: volume.calls_per_month, prefill_tokens_per_second: tps, hours_per_month: hours };
129
+ }
130
+ if (!out.money && !out.gpu)
131
+ out.missing = [...missing];
132
+ else
133
+ out.missing = [...missing].filter((m) => !m.startsWith("volume") && !m.startsWith("prices\t"));
134
+ return out;
135
+ }
136
+ /** 950, 138k, 1.5M */
137
+ export function formatTokens(n) {
138
+ if (n >= 1e6)
139
+ return `${Number((n / 1e6).toFixed(1))}M`;
140
+ if (n >= 1e4)
141
+ return `${Math.round(n / 1e3)}k`;
142
+ if (n >= 1e3)
143
+ return `${Number((n / 1e3).toFixed(1))}k`;
144
+ return `${Math.round(n)}`;
145
+ }
146
+ /** $0.48, $12, $1,235 */
147
+ export function formatDollars(n) {
148
+ if (n < 10)
149
+ return `$${n.toFixed(2)}`;
150
+ return `$${Math.round(n).toLocaleString("en-US")}`;
151
+ }