leanprompt 0.0.0-stage → 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 +89 -2
  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 +32 -4
  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,170 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join, sep } from "node:path";
3
+ import { parseDoc } from "../frontmatter.js";
4
+ import { isMain } from "../isMain.js";
5
+ /** A path for display: always "/" separators, whatever the OS. */
6
+ export const posix = (p) => p.split(sep).join("/");
7
+ export const REQUIRED_SECTIONS = ["Rule", "Why", "Detect in code", "Fix", "Don't break meaning", "Verify", "Waste signal"];
8
+ const SKILL_CODES = { PC: "prefill-cache", GE: "generation-economy", PD: "prompt-diet", LW: "lmwarden" };
9
+ const ID_RE = /^LP-(PC|GE|PD|LW)-\d{2}$/;
10
+ const SAVES = ["prefill", "generation", "both"];
11
+ const SEVERITY = ["high", "medium", "low"];
12
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
13
+ /** Ids from the `| E<n> |` rows of docs/evidence.md. */
14
+ export function loadEvidenceIds(root) {
15
+ const ids = new Set();
16
+ const p = join(root, "docs", "evidence.md");
17
+ if (!existsSync(p))
18
+ return ids;
19
+ for (const line of readFileSync(p, "utf8").split("\n")) {
20
+ const m = /^\|\s*(E\d+)\s*\|/.exec(line);
21
+ if (m)
22
+ ids.add(m[1]);
23
+ }
24
+ return ids;
25
+ }
26
+ export function ruleFiles(root) {
27
+ const skills = join(root, "skills");
28
+ if (!existsSync(skills))
29
+ return [];
30
+ const out = [];
31
+ for (const s of readdirSync(skills, { withFileTypes: true })) {
32
+ if (!s.isDirectory() || s.name.startsWith("_"))
33
+ continue;
34
+ const dir = join(skills, s.name, "rules");
35
+ if (!existsSync(dir))
36
+ continue;
37
+ for (const f of readdirSync(dir).sort())
38
+ if (f.endsWith(".md"))
39
+ out.push(posix(join("skills", s.name, "rules", f)));
40
+ }
41
+ return out;
42
+ }
43
+ /** Rule id -> title and skill, from the frontmatter of skills/*\/rules/*.md. */
44
+ export function loadRules(root) {
45
+ const out = new Map();
46
+ for (const file of ruleFiles(root)) {
47
+ try {
48
+ const m = parseDoc(readFileSync(join(root, file), "utf8")).meta;
49
+ if (typeof m.id === "string" && typeof m.title === "string" && typeof m.skill === "string")
50
+ out.set(m.id, { title: m.title, skill: m.skill });
51
+ }
52
+ catch {
53
+ /* lint:rules reports it */
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+ /** Rule ids (`LP-PC-01`, ...) declared in the skills rules directories; files with bad frontmatter are skipped. */
59
+ export function loadRuleIds(root) {
60
+ const ids = new Set();
61
+ for (const file of ruleFiles(root)) {
62
+ try {
63
+ const id = parseDoc(readFileSync(join(root, file), "utf8")).meta.id;
64
+ if (typeof id === "string" && ID_RE.test(id))
65
+ ids.add(id);
66
+ }
67
+ catch {
68
+ /* lintRules reports it */
69
+ }
70
+ }
71
+ return ids;
72
+ }
73
+ export function lintRules(root) {
74
+ const issues = [];
75
+ const evidence = loadEvidenceIds(root);
76
+ const evidenceMissing = !existsSync(join(root, "docs", "evidence.md"));
77
+ if (evidenceMissing) {
78
+ // One clear error instead of an unknown-evidence error per rule.
79
+ issues.push({ file: "docs/evidence.md", level: "error", msg: "missing docs/evidence.md" });
80
+ }
81
+ const seen = new Map();
82
+ for (const file of ruleFiles(root)) {
83
+ const err = (msg) => issues.push({ file, level: "error", msg });
84
+ let doc;
85
+ try {
86
+ doc = parseDoc(readFileSync(join(root, file), "utf8"));
87
+ }
88
+ catch (e) {
89
+ err(`bad frontmatter: ${e.message.split("\n")[0]}`);
90
+ continue;
91
+ }
92
+ const { meta, sections } = doc;
93
+ const dirSkill = file.split(/[\\/]/)[1];
94
+ for (const k of ["id", "title", "skill", "applies_to", "saves", "severity", "evidence"]) {
95
+ if (meta[k] === undefined || meta[k] === null || meta[k] === "")
96
+ err(`missing field: ${k}`);
97
+ }
98
+ const id = meta.id;
99
+ if (id !== undefined) {
100
+ if (typeof id !== "string" || !ID_RE.test(id))
101
+ err(`bad id ${String(id)}`);
102
+ else {
103
+ const prev = seen.get(id);
104
+ if (prev)
105
+ err(`duplicate id ${id} (also in ${prev})`);
106
+ else
107
+ seen.set(id, file);
108
+ const expected = SKILL_CODES[id.split("-")[1]];
109
+ if (meta.skill !== undefined && meta.skill !== expected)
110
+ err(`id ${id} does not match skill ${String(meta.skill)}`);
111
+ }
112
+ }
113
+ if (typeof meta.skill === "string" && meta.skill !== dirSkill)
114
+ err(`skill ${meta.skill} does not match directory ${dirSkill}`);
115
+ if (meta.applies_to !== undefined && !Array.isArray(meta.applies_to))
116
+ err("applies_to must be a list");
117
+ if (meta.saves !== undefined && !SAVES.includes(String(meta.saves)))
118
+ err(`bad saves ${String(meta.saves)}`);
119
+ if (meta.severity !== undefined && !SEVERITY.includes(String(meta.severity)))
120
+ err(`bad severity ${String(meta.severity)}`);
121
+ if (meta.evidence !== undefined) {
122
+ if (!Array.isArray(meta.evidence))
123
+ err("evidence must be a list");
124
+ else
125
+ for (const ev of meta.evidence) {
126
+ if (typeof ev === "string") {
127
+ if (!evidenceMissing && !evidence.has(ev))
128
+ err(`unknown evidence ${ev}`);
129
+ }
130
+ else if (ev && typeof ev === "object" && "doc" in ev) {
131
+ const e = ev;
132
+ const checked = e.checked instanceof Date ? e.checked.toISOString().slice(0, 10) : e.checked;
133
+ if (typeof checked !== "string" || !DATE_RE.test(checked))
134
+ err("doc evidence needs checked date");
135
+ if (typeof e.doc !== "string" || !e.doc)
136
+ err("doc evidence needs doc url");
137
+ }
138
+ else
139
+ err("bad evidence entry");
140
+ }
141
+ }
142
+ const headings = sections.map((s) => s.heading);
143
+ let missing = false;
144
+ for (const h of REQUIRED_SECTIONS) {
145
+ if (!headings.includes(h)) {
146
+ err(`missing section: ${h}`);
147
+ missing = true;
148
+ }
149
+ }
150
+ if (!missing) {
151
+ const order = headings.filter((h) => REQUIRED_SECTIONS.includes(h));
152
+ if (order.join("\n") !== REQUIRED_SECTIONS.join("\n"))
153
+ err("sections out of order");
154
+ }
155
+ for (const s of sections)
156
+ if (REQUIRED_SECTIONS.includes(s.heading) && !s.body)
157
+ err(`empty section: ${s.heading}`);
158
+ }
159
+ return issues;
160
+ }
161
+ // CLI entry for `npm run lint:rules`: lint the repo root, exit 1 on any error.
162
+ if (isMain(import.meta.url)) {
163
+ const root = process.argv[2] ?? process.cwd();
164
+ const issues = lintRules(root);
165
+ for (const i of issues)
166
+ process.stderr.write(`${i.level}: ${i.file}: ${i.msg}\n`);
167
+ const errors = issues.filter((i) => i.level === "error").length;
168
+ process.stdout.write(`lint:rules: ${errors} error(s), ${issues.length - errors} warning(s)\n`);
169
+ process.exit(errors ? 1 : 0);
170
+ }
@@ -0,0 +1,49 @@
1
+ import { Key, type Canon, type Dialect } from "@kvsig/core";
2
+ import { type Flags } from "./record.js";
3
+ export { parseUsageLog, usageFrom, finishFrom } from "./record.js";
4
+ export type { Flags, UsageRecord, Finish, Tokens, RecordIds } from "./record.js";
5
+ export interface LoggerOptions {
6
+ path: string;
7
+ /**
8
+ * A kvsig Key, or the raw 32 key bytes. Raw bytes are wrapped as epoch 1, the same convention
9
+ * as the Python logger, so one key gives the same ids in both languages. Every kvsig id starts
10
+ * with the epoch byte: pass a Key with another epoch only if every logger of the app does.
11
+ */
12
+ key: Key | Uint8Array;
13
+ provider: string;
14
+ model: string;
15
+ }
16
+ export interface LogRequest {
17
+ dialect: Dialect | "other";
18
+ body: unknown;
19
+ params?: Record<string, unknown>;
20
+ breakpoints?: number[];
21
+ }
22
+ export interface LogResponse {
23
+ usage: unknown;
24
+ finish?: string;
25
+ }
26
+ /** HMAC-SHA256 over the canonical JSON of the params (keys sorted), keyed by the kvsig key; first 16 hex characters. */
27
+ export declare function paramsHash(key: Key, params: Record<string, unknown> | undefined): string;
28
+ /**
29
+ * node_chars[i]: code points of the canonical JSON text of the head messages, the tools and
30
+ * body messages 0..i, the same per-message text kvsig hashes. One entry per prefix node.
31
+ */
32
+ export declare function nodeChars(canon: Canon): number[];
33
+ export interface Logger {
34
+ /**
35
+ * Returns the record's 0-based index among the valid records of the file (the value to pass as
36
+ * `flags.retry_of` on a later retry), or null when no record could be built. The index is computed
37
+ * in memory and the line is appended in the background, in call order, one write at a time, so
38
+ * `log()` never touches the disk. The counter starts at the file's existing valid-record count.
39
+ * If a background write later fails, that record is dropped and later indexes run ahead of the file.
40
+ */
41
+ log(req: LogRequest, res: LogResponse, flags?: Flags): number | null;
42
+ /**
43
+ * Resolves when every record accepted so far has been written (or its write has failed). Never rejects.
44
+ * Await it before a script or test ends: records still queued are lost on `process.exit()`, a
45
+ * crash or a signal unless flush() has been awaited.
46
+ */
47
+ flush(): Promise<void>;
48
+ }
49
+ export declare function createLogger(options: LoggerOptions): Logger;
@@ -0,0 +1,148 @@
1
+ // The TypeScript usage logger. It writes ids, counts and flags, never prompt or completion text,
2
+ // and never throws into the caller's request path.
3
+ import { readFileSync } from "node:fs";
4
+ import { appendFile, mkdir } from "node:fs/promises";
5
+ import { dirname } from "node:path";
6
+ import { canonicalJson, canonicalize, hmacSha256, ids, Key, parseJson, SUPPORTED } from "@kvsig/core";
7
+ import { finishFrom, parseUsageLog, usageFrom } from "./record.js";
8
+ export { parseUsageLog, usageFrom, finishFrom } from "./record.js";
9
+ const enc = new TextEncoder();
10
+ const hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
11
+ const codePoints = (s) => {
12
+ let n = 0;
13
+ for (const _ of s)
14
+ n++;
15
+ return n;
16
+ };
17
+ /** Canonical JSON text of any plain value (object key order is kept unless `sort`). */
18
+ function canonText(v, sort = false) {
19
+ return canonicalJson(parseJson(JSON.stringify(v)), sort);
20
+ }
21
+ /** HMAC-SHA256 over the canonical JSON of the params (keys sorted), keyed by the kvsig key; first 16 hex characters. */
22
+ export function paramsHash(key, params) {
23
+ return hex(hmacSha256(key.bytes(), enc.encode(canonText(params ?? {}, true)))).slice(0, 16);
24
+ }
25
+ /**
26
+ * node_chars[i]: code points of the canonical JSON text of the head messages, the tools and
27
+ * body messages 0..i, the same per-message text kvsig hashes. One entry per prefix node.
28
+ */
29
+ export function nodeChars(canon) {
30
+ let total = 0;
31
+ for (const m of canon.head)
32
+ total += codePoints(canonText(m));
33
+ for (const t of canon.tools)
34
+ total += codePoints(canonText(t));
35
+ return canon.messages.map((m) => (total += codePoints(canonText(m))));
36
+ }
37
+ function identify(key, dialect, body) {
38
+ if (!SUPPORTED.includes(dialect))
39
+ return null;
40
+ const canon = canonicalize(body, dialect, { onError: () => { } });
41
+ if (canon === null || canon.stateful)
42
+ return null;
43
+ const i = ids(canon, key);
44
+ return { ids: { conv: i.conv, head: i.head, nodes: [...i.nodes] }, node_chars: nodeChars(canon) };
45
+ }
46
+ /** Valid records already in the file (0 when it is missing or unreadable). */
47
+ function existingRecords(path) {
48
+ try {
49
+ return parseUsageLog(readFileSync(path, "utf8")).records.length;
50
+ }
51
+ catch {
52
+ return 0;
53
+ }
54
+ }
55
+ // A process that exits while records are still queued loses them unless it awaits flush().
56
+ // This hook is a fallback only (it runs when the event loop empties, never on process.exit() or a crash);
57
+ // the documented contract is to await flush().
58
+ const pendingLoggers = new Set();
59
+ let exitHook = false;
60
+ function ensureExitHook() {
61
+ if (exitHook)
62
+ return;
63
+ exitHook = true;
64
+ process.on("beforeExit", () => {
65
+ for (const flush of [...pendingLoggers])
66
+ void flush();
67
+ });
68
+ }
69
+ export function createLogger(options) {
70
+ const opts = { ...options, key: options.key instanceof Key ? options.key : new Key(1, options.key) };
71
+ let next = existingRecords(opts.path);
72
+ let queue = [];
73
+ let running = null;
74
+ const drain = async () => {
75
+ while (queue.length > 0) {
76
+ const text = queue.join("");
77
+ queue = [];
78
+ try {
79
+ await mkdir(dirname(opts.path), { recursive: true });
80
+ await appendFile(opts.path, text);
81
+ }
82
+ catch {
83
+ // Logging must never break the app; the batch is dropped.
84
+ }
85
+ }
86
+ };
87
+ const flush = async () => {
88
+ while (running !== null)
89
+ await running;
90
+ };
91
+ const enqueue = (line) => {
92
+ queue.push(line);
93
+ if (running !== null)
94
+ return;
95
+ ensureExitHook();
96
+ pendingLoggers.add(flush);
97
+ // Start on a later tick so log() returns before any disk work begins.
98
+ running = Promise.resolve()
99
+ .then(drain)
100
+ .finally(() => {
101
+ running = null;
102
+ pendingLoggers.delete(flush);
103
+ if (queue.length > 0)
104
+ enqueue("");
105
+ });
106
+ };
107
+ return {
108
+ flush,
109
+ log(req, res, flags = {}) {
110
+ try {
111
+ let who = null;
112
+ try {
113
+ who = identify(opts.key, req.dialect, req.body);
114
+ }
115
+ catch {
116
+ who = null;
117
+ }
118
+ let params = "";
119
+ try {
120
+ params = paramsHash(opts.key, req.params);
121
+ }
122
+ catch {
123
+ params = "";
124
+ }
125
+ const record = {
126
+ v: 1,
127
+ ts: new Date().toISOString(),
128
+ provider: opts.provider,
129
+ model: opts.model,
130
+ dialect: req.dialect,
131
+ ids: who?.ids ?? null,
132
+ node_chars: who?.node_chars ?? null,
133
+ breakpoints: (req.breakpoints ?? []).filter((n) => Number.isInteger(n)),
134
+ params,
135
+ ...usageFrom(opts.provider, res.usage),
136
+ finish: finishFrom(res.finish),
137
+ flags,
138
+ };
139
+ enqueue(JSON.stringify(record) + "\n");
140
+ return next++;
141
+ }
142
+ catch {
143
+ // Logging must never break the app's call path.
144
+ return null;
145
+ }
146
+ },
147
+ };
148
+ }
@@ -0,0 +1,56 @@
1
+ export type Finish = "stop" | "length" | "tool" | "error";
2
+ export interface Flags {
3
+ /**
4
+ * The call this one retries: the 0-based index of the earlier record among the valid records of
5
+ * the same usage file, in file order. A value not smaller than this record's own index is ignored.
6
+ * Retry links hold within one file written by one process; concatenating logs from several
7
+ * processes is not supported for retry linking.
8
+ */
9
+ retry_of?: number;
10
+ parse_failed?: true;
11
+ }
12
+ export interface RecordIds {
13
+ conv: string | null;
14
+ head: string;
15
+ nodes: string[];
16
+ }
17
+ export interface UsageRecord {
18
+ v: 1;
19
+ ts: string;
20
+ provider: string;
21
+ model: string;
22
+ dialect: string;
23
+ ids: RecordIds | null;
24
+ node_chars: number[] | null;
25
+ breakpoints: number[];
26
+ params: string;
27
+ prompt_tokens: number;
28
+ cached_tokens: number;
29
+ cache_write_tokens: number;
30
+ output_tokens: number;
31
+ finish: Finish;
32
+ flags: Flags;
33
+ }
34
+ export interface Tokens {
35
+ prompt_tokens: number;
36
+ cached_tokens: number;
37
+ cache_write_tokens: number;
38
+ output_tokens: number;
39
+ }
40
+ /**
41
+ * Token counts from a provider's usage object.
42
+ * The Anthropic shape (provider "anthropic", or cache_read_input_tokens / cache_creation_input_tokens
43
+ * present, as from Bedrock, Vertex or a proxy) reports input_tokens apart from the cache counters, so the prompt is their sum.
44
+ * OpenAI-compatible APIs report prompt_tokens with the cached part inside it. Gemini's native
45
+ * usageMetadata is read too, and so is the Vercel AI SDK's camelCase usage (v4 promptTokens /
46
+ * completionTokens; v5 inputTokens / outputTokens / cachedInputTokens, where Anthropic's inputTokens
47
+ * leaves out the cache read; v6 inputTokens as the total with inputTokenDetails). Anything unreadable counts as 0.
48
+ */
49
+ export declare function usageFrom(provider: string, usage: unknown): Tokens;
50
+ /** Provider finish reasons mapped onto the record's four values; unknown reasons count as "stop". */
51
+ export declare function finishFrom(finish: string | undefined): Finish;
52
+ /** Reads a usage.jsonl text. A malformed or non-record line is skipped and counted in `bad`; blank lines are ignored. */
53
+ export declare function parseUsageLog(text: string): {
54
+ records: UsageRecord[];
55
+ bad: number;
56
+ };
@@ -0,0 +1,117 @@
1
+ // The usage record (`leanprompt/usage/1`): one JSON object per line in .leanprompt/usage.jsonl.
2
+ // It holds ids, counts and flags only. It never holds prompt or completion text.
3
+ const isObj = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
4
+ const num = (x) => (typeof x === "number" && Number.isFinite(x) && x >= 0 ? x : 0);
5
+ /**
6
+ * Token counts from a provider's usage object.
7
+ * The Anthropic shape (provider "anthropic", or cache_read_input_tokens / cache_creation_input_tokens
8
+ * present, as from Bedrock, Vertex or a proxy) reports input_tokens apart from the cache counters, so the prompt is their sum.
9
+ * OpenAI-compatible APIs report prompt_tokens with the cached part inside it. Gemini's native
10
+ * usageMetadata is read too, and so is the Vercel AI SDK's camelCase usage (v4 promptTokens /
11
+ * completionTokens; v5 inputTokens / outputTokens / cachedInputTokens, where Anthropic's inputTokens
12
+ * leaves out the cache read; v6 inputTokens as the total with inputTokenDetails). Anything unreadable counts as 0.
13
+ */
14
+ export function usageFrom(provider, usage) {
15
+ const u = isObj(usage) ? usage : {};
16
+ if ("inputTokens" in u || "promptTokens" in u || "outputTokens" in u || "completionTokens" in u) {
17
+ const out = num(u.outputTokens ?? u.completionTokens);
18
+ if (isObj(u.inputTokenDetails)) {
19
+ const d = u.inputTokenDetails;
20
+ return { prompt_tokens: num(u.inputTokens), cached_tokens: num(d.cacheReadTokens), cache_write_tokens: num(d.cacheWriteTokens), output_tokens: out };
21
+ }
22
+ const input = num(u.inputTokens ?? u.promptTokens);
23
+ const cached = num(u.cachedInputTokens);
24
+ return {
25
+ prompt_tokens: provider === "anthropic" ? input + cached : input,
26
+ cached_tokens: cached,
27
+ cache_write_tokens: 0,
28
+ output_tokens: out,
29
+ };
30
+ }
31
+ if (provider === "anthropic" || "cache_read_input_tokens" in u || "cache_creation_input_tokens" in u) {
32
+ const read = num(u.cache_read_input_tokens);
33
+ const write = num(u.cache_creation_input_tokens);
34
+ return {
35
+ prompt_tokens: num(u.input_tokens) + read + write,
36
+ cached_tokens: read,
37
+ cache_write_tokens: write,
38
+ output_tokens: num(u.output_tokens),
39
+ };
40
+ }
41
+ if (isObj(u.usageMetadata) || "promptTokenCount" in u) {
42
+ const m = isObj(u.usageMetadata) ? u.usageMetadata : u;
43
+ return {
44
+ prompt_tokens: num(m.promptTokenCount),
45
+ cached_tokens: num(m.cachedContentTokenCount),
46
+ cache_write_tokens: 0,
47
+ output_tokens: num(m.candidatesTokenCount),
48
+ };
49
+ }
50
+ const details = isObj(u.prompt_tokens_details)
51
+ ? u.prompt_tokens_details
52
+ : isObj(u.input_tokens_details)
53
+ ? u.input_tokens_details
54
+ : {};
55
+ return {
56
+ prompt_tokens: num(u.prompt_tokens ?? u.input_tokens),
57
+ cached_tokens: num(details.cached_tokens),
58
+ cache_write_tokens: num(details.cache_write_tokens),
59
+ output_tokens: num(u.completion_tokens ?? u.output_tokens),
60
+ };
61
+ }
62
+ /** Provider finish reasons mapped onto the record's four values; unknown reasons count as "stop". */
63
+ export function finishFrom(finish) {
64
+ switch (finish) {
65
+ case "length":
66
+ case "max_tokens":
67
+ case "max_output_tokens":
68
+ return "length";
69
+ case "tool":
70
+ case "tool_calls":
71
+ case "tool_use":
72
+ case "function_call":
73
+ return "tool";
74
+ case "error":
75
+ return "error";
76
+ default:
77
+ return "stop";
78
+ }
79
+ }
80
+ function validRecord(r) {
81
+ if (!isObj(r) || r.v !== 1)
82
+ return false;
83
+ for (const k of ["ts", "provider", "model", "dialect", "params"])
84
+ if (typeof r[k] !== "string")
85
+ return false;
86
+ for (const k of ["prompt_tokens", "cached_tokens", "cache_write_tokens", "output_tokens"]) {
87
+ if (typeof r[k] !== "number")
88
+ return false;
89
+ }
90
+ if (r.ids !== null && !(isObj(r.ids) && Array.isArray(r.ids.nodes) && typeof r.ids.head === "string"))
91
+ return false;
92
+ if (r.node_chars !== null && !Array.isArray(r.node_chars))
93
+ return false;
94
+ if (!Array.isArray(r.breakpoints) || !isObj(r.flags))
95
+ return false;
96
+ return typeof r.finish === "string";
97
+ }
98
+ /** Reads a usage.jsonl text. A malformed or non-record line is skipped and counted in `bad`; blank lines are ignored. */
99
+ export function parseUsageLog(text) {
100
+ const records = [];
101
+ let bad = 0;
102
+ for (const line of text.split("\n")) {
103
+ if (line.trim() === "")
104
+ continue;
105
+ try {
106
+ const r = JSON.parse(line);
107
+ if (validRecord(r))
108
+ records.push(r);
109
+ else
110
+ bad++;
111
+ }
112
+ catch {
113
+ bad++;
114
+ }
115
+ }
116
+ return { records, bad };
117
+ }
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ export declare const VERSION: string;
3
+ type Handler = (args: string[]) => Promise<number>;
4
+ export declare const commands: Record<string, Handler>;
5
+ export declare function main(argv: string[]): Promise<number>;
6
+ export {};
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { profileCommand } from "./detect.js";
4
+ import { evalAuditCommand } from "./evalAudit.js";
5
+ import { helpText, overviewText, SPECS } from "./help.js";
6
+ import { installCommand, updateCommand } from "./install.js";
7
+ import { lessonCommand } from "./lesson.js";
8
+ import { isMain } from "./isMain.js";
9
+ import { reportCommand } from "./report/html.js";
10
+ import { calibrateCommand } from "./score/calibrate.js";
11
+ import { scoreCommand } from "./score/write.js";
12
+ // cli/src and cli/dist are the same depth below the package root.
13
+ const pkgUrl = new URL("../../package.json", import.meta.url);
14
+ export const VERSION = JSON.parse(readFileSync(pkgUrl, "utf8")).version;
15
+ export const commands = {
16
+ install: (args) => installCommand(args),
17
+ init: (args) => installCommand(args, undefined, "init"),
18
+ update: (args) => updateCommand(args),
19
+ score: scoreCommand,
20
+ calibrate: (args) => calibrateCommand(args),
21
+ report: reportCommand,
22
+ profile: profileCommand,
23
+ lesson: lessonCommand,
24
+ "eval-audit": evalAuditCommand,
25
+ };
26
+ function helpFor(name) {
27
+ if (name === undefined) {
28
+ process.stdout.write(overviewText(Object.keys(commands)));
29
+ return 0;
30
+ }
31
+ const key = name === "profile" ? "profile detect" : name;
32
+ if (!SPECS.some((s) => s.name === key)) {
33
+ process.stderr.write(`unknown command: ${name}\nRun leanprompt --help for the commands.\n`);
34
+ return 2;
35
+ }
36
+ process.stdout.write(helpText(key));
37
+ return 0;
38
+ }
39
+ export async function main(argv) {
40
+ const [cmd, ...rest] = argv;
41
+ if (cmd === "--version" || cmd === "-v") {
42
+ process.stdout.write(`${VERSION}\n`);
43
+ return 0;
44
+ }
45
+ if (cmd === undefined || cmd === "--help" || cmd === "-h") {
46
+ process.stdout.write(overviewText(Object.keys(commands)));
47
+ return 0;
48
+ }
49
+ if (cmd === "help")
50
+ return helpFor(rest[0]);
51
+ if (rest.includes("--help") || rest.includes("-h")) {
52
+ if (Object.hasOwn(commands, cmd))
53
+ return helpFor(cmd === "profile" ? "profile detect" : cmd);
54
+ }
55
+ const handler = Object.hasOwn(commands, cmd) ? commands[cmd] : undefined;
56
+ if (!handler) {
57
+ process.stderr.write(`unknown command: ${cmd}\nRun leanprompt --help for the commands.\n`);
58
+ return 2;
59
+ }
60
+ return handler(rest);
61
+ }
62
+ if (isMain(import.meta.url)) {
63
+ main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
64
+ process.stderr.write(`leanprompt: ${e instanceof Error ? e.message : String(e)}\n`);
65
+ process.exit(1);
66
+ });
67
+ }