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.
- package/LICENSE +202 -0
- package/LICENSE-DOCS +396 -0
- package/NOTICE +11 -0
- package/README.md +86 -3
- package/cli/dist/detect.d.ts +23 -0
- package/cli/dist/detect.js +219 -0
- package/cli/dist/evalAudit.d.ts +32 -0
- package/cli/dist/evalAudit.js +161 -0
- package/cli/dist/facts.d.ts +14 -0
- package/cli/dist/facts.js +43 -0
- package/cli/dist/forms.d.ts +23 -0
- package/cli/dist/forms.js +199 -0
- package/cli/dist/frontmatter.d.ts +10 -0
- package/cli/dist/frontmatter.js +32 -0
- package/cli/dist/help.d.ts +27 -0
- package/cli/dist/help.js +118 -0
- package/cli/dist/init.d.ts +78 -0
- package/cli/dist/init.js +358 -0
- package/cli/dist/install.d.ts +20 -0
- package/cli/dist/install.js +225 -0
- package/cli/dist/isMain.d.ts +6 -0
- package/cli/dist/isMain.js +18 -0
- package/cli/dist/lesson.d.ts +16 -0
- package/cli/dist/lesson.js +205 -0
- package/cli/dist/lint/facts.d.ts +7 -0
- package/cli/dist/lint/facts.js +163 -0
- package/cli/dist/lint/numbers.d.ts +26 -0
- package/cli/dist/lint/numbers.js +163 -0
- package/cli/dist/lint/rules.d.ts +20 -0
- package/cli/dist/lint/rules.js +170 -0
- package/cli/dist/log/logger.d.ts +49 -0
- package/cli/dist/log/logger.js +148 -0
- package/cli/dist/log/record.d.ts +56 -0
- package/cli/dist/log/record.js +117 -0
- package/cli/dist/main.d.ts +6 -0
- package/cli/dist/main.js +67 -0
- package/cli/dist/profile.d.ts +93 -0
- package/cli/dist/profile.js +372 -0
- package/cli/dist/report/cost.d.ts +55 -0
- package/cli/dist/report/cost.js +151 -0
- package/cli/dist/report/html.d.ts +81 -0
- package/cli/dist/report/html.js +555 -0
- package/cli/dist/report/template.html +269 -0
- package/cli/dist/score/calibrate.d.ts +65 -0
- package/cli/dist/score/calibrate.js +213 -0
- package/cli/dist/score/measured.d.ts +66 -0
- package/cli/dist/score/measured.js +191 -0
- package/cli/dist/score/static.d.ts +112 -0
- package/cli/dist/score/static.js +172 -0
- package/cli/dist/score/write.d.ts +29 -0
- package/cli/dist/score/write.js +247 -0
- package/forms/AGENTS.block.md +25 -0
- package/forms/opencode/commands/leanprompt-audit.md +10 -0
- package/forms/opencode/commands/leanprompt.md +8 -0
- package/forms/skills/generation-economy/SKILL.md +89 -0
- package/forms/skills/generation-economy/rules/LP-GE-01.md +93 -0
- package/forms/skills/generation-economy/rules/LP-GE-02.md +82 -0
- package/forms/skills/generation-economy/rules/LP-GE-03.md +87 -0
- package/forms/skills/generation-economy/rules/LP-GE-04.md +118 -0
- package/forms/skills/generation-economy/rules/LP-GE-05.md +84 -0
- package/forms/skills/generation-economy/rules/LP-GE-06.md +76 -0
- package/forms/skills/generation-economy/rules/LP-GE-07.md +84 -0
- package/forms/skills/generation-economy/rules/LP-GE-08.md +71 -0
- package/forms/skills/generation-economy/rules/LP-GE-09.md +79 -0
- package/forms/skills/generation-economy/rules/LP-GE-10.md +104 -0
- package/forms/skills/leanprompt/SKILL.md +48 -0
- package/forms/skills/leanprompt/fix.md +15 -0
- package/forms/skills/leanprompt/init.md +30 -0
- package/forms/skills/llm-call-audit/SKILL.md +169 -0
- package/forms/skills/llm-call-audit/call-shapes.md +99 -0
- package/forms/skills/llm-call-audit/presenting.md +72 -0
- package/forms/skills/llm-call-audit/report-template.md +113 -0
- package/forms/skills/lmwarden/SKILL.md +97 -0
- package/forms/skills/lmwarden/rules/LP-LW-01.md +73 -0
- package/forms/skills/lmwarden/rules/LP-LW-02.md +78 -0
- package/forms/skills/lmwarden/rules/LP-LW-03.md +73 -0
- package/forms/skills/measure-loop/SKILL.md +155 -0
- package/forms/skills/measure-loop/templates/stable-head.template.ts +38 -0
- package/forms/skills/measure-loop/templates/stable_head_template.py +40 -0
- package/forms/skills/prefill-cache/SKILL.md +66 -0
- package/forms/skills/prefill-cache/rules/LP-PC-01.md +103 -0
- package/forms/skills/prefill-cache/rules/LP-PC-02.md +80 -0
- package/forms/skills/prefill-cache/rules/LP-PC-03.md +75 -0
- package/forms/skills/prefill-cache/rules/LP-PC-04.md +79 -0
- package/forms/skills/prefill-cache/rules/LP-PC-05.md +68 -0
- package/forms/skills/prefill-cache/rules/LP-PC-06.md +71 -0
- package/forms/skills/prefill-cache/rules/LP-PC-07.md +97 -0
- package/forms/skills/prefill-cache/rules/LP-PC-08.md +67 -0
- package/forms/skills/prefill-cache/rules/LP-PC-09.md +75 -0
- package/forms/skills/prefill-cache/rules/LP-PC-10.md +76 -0
- package/forms/skills/prefill-cache/rules/LP-PC-11.md +72 -0
- package/forms/skills/prefill-cache/rules/LP-PC-12.md +73 -0
- package/forms/skills/prompt-diet/SKILL.md +69 -0
- package/forms/skills/prompt-diet/rules/LP-PD-01.md +79 -0
- package/forms/skills/prompt-diet/rules/LP-PD-02.md +73 -0
- package/forms/skills/prompt-diet/rules/LP-PD-03.md +65 -0
- package/forms/skills/prompt-diet/rules/LP-PD-04.md +77 -0
- package/forms/skills/prompt-diet/rules/LP-PD-05.md +71 -0
- package/forms/skills/prompt-diet/rules/LP-PD-06.md +68 -0
- package/models/anthropic-thinking.md +38 -0
- package/models/openai-reasoning.md +35 -0
- package/models/qwen.md +34 -0
- package/package.json +31 -8
- package/providers/anthropic.md +83 -0
- package/providers/deepinfra.md +46 -0
- package/providers/gemini.md +61 -0
- package/providers/openai.md +73 -0
- package/providers/openrouter.md +66 -0
- package/providers/sglang.md +41 -0
- package/providers/vllm.md +52 -0
- package/runtimes/http-clients.md +20 -0
- package/skills/_template/RULE.md +31 -0
- package/skills/generation-economy/SKILL.md +88 -0
- package/skills/generation-economy/rules/LP-GE-01.md +92 -0
- package/skills/generation-economy/rules/LP-GE-02.md +81 -0
- package/skills/generation-economy/rules/LP-GE-03.md +86 -0
- package/skills/generation-economy/rules/LP-GE-04.md +117 -0
- package/skills/generation-economy/rules/LP-GE-05.md +83 -0
- package/skills/generation-economy/rules/LP-GE-06.md +75 -0
- package/skills/generation-economy/rules/LP-GE-07.md +83 -0
- package/skills/generation-economy/rules/LP-GE-08.md +70 -0
- package/skills/generation-economy/rules/LP-GE-09.md +78 -0
- package/skills/generation-economy/rules/LP-GE-10.md +103 -0
- package/skills/leanprompt/SKILL.md +47 -0
- package/skills/leanprompt/fix.md +14 -0
- package/skills/leanprompt/init.md +29 -0
- package/skills/llm-call-audit/SKILL.md +168 -0
- package/skills/llm-call-audit/call-shapes.md +98 -0
- package/skills/llm-call-audit/presenting.md +71 -0
- package/skills/llm-call-audit/report-template.md +112 -0
- package/skills/lmwarden/SKILL.md +96 -0
- package/skills/lmwarden/rules/LP-LW-01.md +72 -0
- package/skills/lmwarden/rules/LP-LW-02.md +77 -0
- package/skills/lmwarden/rules/LP-LW-03.md +72 -0
- package/skills/measure-loop/SKILL.md +154 -0
- package/skills/measure-loop/templates/stable-head.template.ts +38 -0
- package/skills/measure-loop/templates/stable_head_template.py +40 -0
- package/skills/prefill-cache/SKILL.md +65 -0
- package/skills/prefill-cache/rules/LP-PC-01.md +102 -0
- package/skills/prefill-cache/rules/LP-PC-02.md +79 -0
- package/skills/prefill-cache/rules/LP-PC-03.md +74 -0
- package/skills/prefill-cache/rules/LP-PC-04.md +78 -0
- package/skills/prefill-cache/rules/LP-PC-05.md +67 -0
- package/skills/prefill-cache/rules/LP-PC-06.md +70 -0
- package/skills/prefill-cache/rules/LP-PC-07.md +96 -0
- package/skills/prefill-cache/rules/LP-PC-08.md +66 -0
- package/skills/prefill-cache/rules/LP-PC-09.md +74 -0
- package/skills/prefill-cache/rules/LP-PC-10.md +75 -0
- package/skills/prefill-cache/rules/LP-PC-11.md +71 -0
- package/skills/prefill-cache/rules/LP-PC-12.md +72 -0
- package/skills/prompt-diet/SKILL.md +68 -0
- package/skills/prompt-diet/rules/LP-PD-01.md +78 -0
- package/skills/prompt-diet/rules/LP-PD-02.md +72 -0
- package/skills/prompt-diet/rules/LP-PD-03.md +64 -0
- package/skills/prompt-diet/rules/LP-PD-04.md +76 -0
- package/skills/prompt-diet/rules/LP-PD-05.md +70 -0
- package/skills/prompt-diet/rules/LP-PD-06.md +67 -0
package/README.md
CHANGED
|
@@ -1,7 +1,90 @@
|
|
|
1
1
|
# leanprompt
|
|
2
2
|
|
|
3
|
-
**
|
|
3
|
+
**Get more from every LLM call your app makes.**
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Effective, efficient and affordable: your coding assistant makes prompts cacheable, cuts dead weight, stops wasted output and speeds up first tokens, without changing the answers. leanprompt is a set of skills for coding agents, by the LM Warden Team. It is not a prompt-compression library, and it works on the app the assistant is building, not on the assistant's own bill.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
[](https://github.com/Podwarden/leanprompt/actions/workflows/ci.yml)
|
|
9
|
+
[](docs/install.md)
|
|
10
|
+
<!-- pending: this repo's own leanprompt badge, once .leanprompt/score.json is committed from a measured run -->
|
|
11
|
+
|
|
12
|
+
From your project root:
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
npx leanprompt install
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The npm package is being published and that line does not work yet. Until it does, run `npx github:Podwarden/leanprompt install` (Node 20.19 or newer). It finds the assistants you use, asks whether to install for this project or for all your projects, shows every file it will write, and asks before writing.
|
|
19
|
+
|
|
20
|
+
Reload your assistant, then type `/leanprompt init` (`$leanprompt init` in Codex).
|
|
21
|
+
|
|
22
|
+
Works with Claude Code, Codex, Cursor, OpenCode and any agent that reads `AGENTS.md`. In Claude Code you can install the plugin instead, inside a session: `/plugin marketplace add Podwarden/leanprompt`, then `/plugin install leanprompt@leanprompt`; then the command is `/leanprompt:leanprompt`, or `/leanprompt` when no other command has that name ([docs/install.md](docs/install.md)).
|
|
23
|
+
|
|
24
|
+
| Without leanprompt | With leanprompt |
|
|
25
|
+
|---|---|
|
|
26
|
+
|  |  |
|
|
27
|
+
|
|
28
|
+
The same example app, [`examples/dated-chat`](examples/dated-chat/README.md), audited before and after one fix. Before, the system prompt starts with the time to the second, so no call can reuse the handbook that follows it. After, the time moves to the newest message and the prompt head stays the same on every call. Both pages show estimates from the code, not measurements; `/leanprompt measure` turns a fix into a before and after number.
|
|
29
|
+
|
|
30
|
+
## Commands
|
|
31
|
+
|
|
32
|
+
Type `/leanprompt` alone to see them in your assistant. `npx leanprompt --help` lists the terminal commands.
|
|
33
|
+
|
|
34
|
+
| | Commands |
|
|
35
|
+
|---|---|
|
|
36
|
+
| **Set up** | `npx leanprompt install` installs the skills · `npx leanprompt update` refreshes them · `/leanprompt init` writes `leanprompt.yaml`: your targets, priority, volume and prices |
|
|
37
|
+
| **Audit** | `/leanprompt audit` finds every LLM call and ranks where it loses tokens and time · `/leanprompt score` scores the app, measured or static |
|
|
38
|
+
| **Fix and prove** | `/leanprompt fix` checks each finding, shows a diff, applies it on your yes · `/leanprompt measure` proves it with a before and after |
|
|
39
|
+
| **Share** | `/leanprompt report` writes a local page in plain English · `/leanprompt lesson` drafts a lesson-learned issue, sending nothing · `npx leanprompt score --github` annotates a pull request ([docs/ci.md](docs/ci.md)) |
|
|
40
|
+
|
|
41
|
+
Until the npm release, run each `npx leanprompt <cmd>` as `npx github:Podwarden/leanprompt <cmd>`. The usage logger that `measure` adds to your app installs from GitHub too: `npm i github:Podwarden/leanprompt#v0.1.0-dev.1`, or for Python `pip install "git+https://github.com/Podwarden/leanprompt#subdirectory=python"`; your assistant asks first.
|
|
42
|
+
|
|
43
|
+
No telemetry, no proxy, no hosted service, no account. It does not edit your code without asking.
|
|
44
|
+
|
|
45
|
+
## Why
|
|
46
|
+
|
|
47
|
+
Every call to an LLM resends the system prompt, the tool list and the history. Providers cache the part that did not change, but only if it really did not change, byte for byte, from the first token. Most apps break that without knowing: a timestamp on the first line, tools built from an unsorted dict, a client that never sends Anthropic's cache marks. Then they pay again for output: a retry after a truncation, one request per sample, a parse failure re-asked from scratch.
|
|
48
|
+
|
|
49
|
+
| What changed | Before | After |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| Replayed coding-agent sessions on Anthropic: did the client send cache marks? No marks: Codex and OpenCode sessions; 3 marks: a Claude Code session | no marks: 0 tokens from cache on 29 turns (E1) | 3 marks: 92% of prompt tokens from cache on one session (435,661 of 471,607) (E1) |
|
|
52
|
+
| Thinking toggled between turns vs kept the same, one session on a self-hosted vLLM (Qwen hybrid model) | toggled turns lost 47% of what they could have reused (E7) | turns with the same setting as the turn before lost nothing beyond the engine rule (E7) |
|
|
53
|
+
| Cache-aware replica routing (LM Warden, an engine setting, not a prompt rule); synthetic load, 8 concurrent agent sessions, one run per arm; at 24+ sessions (overload) the median got worse | median time to first byte 2.33 s; 44% of prompt tokens from cache (E10) | median time to first byte 0.48 s; 86% from cache; output tokens a minute +29% (E10) |
|
|
54
|
+
|
|
55
|
+
<!-- pending: eval/results (example apps before/after, measured; one row per app once real runs are committed) -->
|
|
56
|
+
|
|
57
|
+
And one that went the other way: moving the date to the end of the prompt cut correct date answers from 10/12 to 1/12 and did not help the cache (E6). leanprompt's rules keep meaning first. Every figure above is a row in [docs/evidence.md](docs/evidence.md), with its source and its limits.
|
|
58
|
+
|
|
59
|
+
## What's in the box
|
|
60
|
+
|
|
61
|
+
Seven skills, each a folder with a `SKILL.md`; the rule skills have one file per rule.
|
|
62
|
+
|
|
63
|
+
- [`leanprompt`](skills/leanprompt/SKILL.md): the entry point; routes each command to the skill below that does the work.
|
|
64
|
+
- [`llm-call-audit`](skills/llm-call-audit/SKILL.md): finds every LLM call, checks it against the rules, ranks the findings and writes the report.
|
|
65
|
+
- [`prefill-cache`](skills/prefill-cache/SKILL.md): prompts the provider's prefix cache can reuse (LP-PC-01 to LP-PC-12).
|
|
66
|
+
- [`generation-economy`](skills/generation-economy/SKILL.md): samples, budgets, timeouts, retries and batching that do not waste calls or output (LP-GE-01 to LP-GE-10).
|
|
67
|
+
- [`prompt-diet`](skills/prompt-diet/SKILL.md): dead weight in what each call sends, every trim with an answer check (LP-PD-01 to LP-PD-06).
|
|
68
|
+
- [`measure-loop`](skills/measure-loop/SKILL.md): measure, change one thing, measure again; the usage logger, the stable-head CI test, the score.
|
|
69
|
+
- [`lmwarden`](skills/lmwarden/SKILL.md): self-hosted engines (vLLM, SGLang, LM Warden): engine settings, replica routing, cache isolation (LP-LW-01 to LP-LW-03).
|
|
70
|
+
|
|
71
|
+
## Learn more
|
|
72
|
+
|
|
73
|
+
- [Install and update](docs/install.md): every assistant, project or global, the Claude Code plugin, Windows.
|
|
74
|
+
- [How it works](docs/how-it-works.md): the audit, the rules at a glance, and how to prove a fix.
|
|
75
|
+
- [The score and the badge](docs/score.md), [calibration](docs/calibration.md) and [leanprompt in CI](docs/ci.md).
|
|
76
|
+
- [Provider notes](docs/providers.md) and [self-hosting](docs/self-hosting.md), including LM Warden and its limits.
|
|
77
|
+
- [All docs](docs/README.md), including the [evidence table](docs/evidence.md) and the [changelog](docs/CHANGELOG.md).
|
|
78
|
+
|
|
79
|
+
## Contributing
|
|
80
|
+
|
|
81
|
+
Issues and pull requests are welcome. A new rule needs a "Verify" section and either a measured example or a dated provider-doc source; commits carry a DCO sign-off. See [CONTRIBUTING.md](.github/CONTRIBUTING.md), [GOVERNANCE.md](.github/GOVERNANCE.md) and [SECURITY.md](.github/SECURITY.md). If leanprompt helped you, or a rule misled you, share a lesson in general terms with the [Lesson learned form](https://github.com/Podwarden/leanprompt/issues/new?template=lesson-learned.yml); credit is optional ([THANKYOU.md](docs/THANKYOU.md)).
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
Code (`cli/`, `eval/`, `examples/`, `python/`, `scripts/`) is under [Apache-2.0](LICENSE). The skills, provider and model tables, docs and this README are under [CC BY 4.0](LICENSE-DOCS). Copyright the LM Warden Team. "PodWarden" and "LM Warden" are trademarks of their owners; see [NOTICE](NOTICE).
|
|
86
|
+
|
|
87
|
+
## Related projects
|
|
88
|
+
|
|
89
|
+
- [kvsig](https://github.com/Podwarden/kvsig): the open spec for keyed conversation and prefix ids that the stable-head test and the measured score use.
|
|
90
|
+
- [LM Warden](https://github.com/Podwarden/lm-warden): self-hosted, cache-aware model serving on your own NVIDIA GPUs.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type Profile } from "./profile.js";
|
|
2
|
+
export interface Detected {
|
|
3
|
+
engine: NonNullable<Profile["engine"]>;
|
|
4
|
+
context_tokens?: number;
|
|
5
|
+
/** Fields the server could not determine; left out of the profile. */
|
|
6
|
+
unknown: string[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Engine facts from the response of `GET /api/me/engine` (v1). With several models `model` picks one;
|
|
10
|
+
* without it the error lists the names. A value that is null (named in `unknown`) is left out.
|
|
11
|
+
*/
|
|
12
|
+
export declare function detectFromLmWarden(json: unknown, model?: string): Detected;
|
|
13
|
+
export interface DetectDeps {
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
env?: Record<string, string | undefined>;
|
|
16
|
+
cwd?: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* `leanprompt profile detect`: read the engine's cache facts from LM Warden and write them to `engine:`,
|
|
20
|
+
* or, in a profile with `targets:`, to the lm-warden (else vllm) entry's `engine_facts`.
|
|
21
|
+
*/
|
|
22
|
+
export declare function detectCommand(args: string[], deps?: DetectDeps): Promise<number>;
|
|
23
|
+
export declare const profileCommand: (args: string[]) => Promise<number>;
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { isMap, isSeq, parseDocument } from "yaml";
|
|
5
|
+
import { optionsFor } from "./help.js";
|
|
6
|
+
import { parseProfile } from "./profile.js";
|
|
7
|
+
const USAGE = "usage: leanprompt profile detect --lmwarden <url> [--token-env LMWARDEN_API_KEY] [--model <name>]\n";
|
|
8
|
+
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
9
|
+
const posInt = (v) => typeof v === "number" && Number.isInteger(v) && v > 0;
|
|
10
|
+
/**
|
|
11
|
+
* Engine facts from the response of `GET /api/me/engine` (v1). With several models `model` picks one;
|
|
12
|
+
* without it the error lists the names. A value that is null (named in `unknown`) is left out.
|
|
13
|
+
*/
|
|
14
|
+
export function detectFromLmWarden(json, model) {
|
|
15
|
+
if (!isObj(json) || !Array.isArray(json.models))
|
|
16
|
+
throw new Error("unexpected response: no models list");
|
|
17
|
+
if (json.v !== undefined && json.v !== 1)
|
|
18
|
+
throw new Error(`unsupported response version ${String(json.v)}; upgrade leanprompt`);
|
|
19
|
+
const rows = json.models.filter(isObj);
|
|
20
|
+
if (rows.length === 0)
|
|
21
|
+
throw new Error("this key can use no models");
|
|
22
|
+
const names = rows.map((r) => String(r.model)).join(", ");
|
|
23
|
+
let row;
|
|
24
|
+
if (model !== undefined) {
|
|
25
|
+
const hit = rows.find((r) => r.model === model);
|
|
26
|
+
if (!hit)
|
|
27
|
+
throw new Error(`no model "${model}" for this key; models: ${names}`);
|
|
28
|
+
row = hit;
|
|
29
|
+
}
|
|
30
|
+
else if (rows.length > 1) {
|
|
31
|
+
throw new Error(`this key can use several models; pass --model <name>. Models: ${names}`);
|
|
32
|
+
}
|
|
33
|
+
else
|
|
34
|
+
row = rows[0];
|
|
35
|
+
const unknown = new Set(Array.isArray(row.unknown) ? row.unknown.map(String) : []);
|
|
36
|
+
const engine = {};
|
|
37
|
+
if (posInt(row.engine_block_tokens))
|
|
38
|
+
engine.block_tokens = row.engine_block_tokens;
|
|
39
|
+
else
|
|
40
|
+
unknown.add("engine_block_tokens");
|
|
41
|
+
if (posInt(row.engine_match_unit_tokens))
|
|
42
|
+
engine.match_unit_tokens = row.engine_match_unit_tokens;
|
|
43
|
+
else
|
|
44
|
+
unknown.add("engine_match_unit_tokens");
|
|
45
|
+
if (row.speculative === null || row.speculative === undefined) {
|
|
46
|
+
if (unknown.has("speculative") || row.speculative === undefined)
|
|
47
|
+
unknown.add("speculative");
|
|
48
|
+
else
|
|
49
|
+
engine.speculative = false;
|
|
50
|
+
}
|
|
51
|
+
else
|
|
52
|
+
engine.speculative = true;
|
|
53
|
+
const out = { engine, unknown: [...unknown] };
|
|
54
|
+
if (posInt(row.max_model_len))
|
|
55
|
+
out.context_tokens = row.max_model_len;
|
|
56
|
+
else
|
|
57
|
+
unknown.add("max_model_len"), (out.unknown = [...unknown]);
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
61
|
+
const isLoopback = (host) => host === "localhost" || host.endsWith(".localhost") || /^127(?:\.\d{1,3}){3}$/.test(host) || host === "[::1]" || host === "::1";
|
|
62
|
+
/**
|
|
63
|
+
* `leanprompt profile detect`: read the engine's cache facts from LM Warden and write them to `engine:`,
|
|
64
|
+
* or, in a profile with `targets:`, to the lm-warden (else vllm) entry's `engine_facts`.
|
|
65
|
+
*/
|
|
66
|
+
export async function detectCommand(args, deps = {}) {
|
|
67
|
+
let secrets = [];
|
|
68
|
+
const fail = (msg, code = 1) => {
|
|
69
|
+
for (const x of secrets)
|
|
70
|
+
if (x)
|
|
71
|
+
msg = msg.split(x).join("***");
|
|
72
|
+
process.stderr.write(`${msg}\n`);
|
|
73
|
+
return code;
|
|
74
|
+
};
|
|
75
|
+
let values;
|
|
76
|
+
try {
|
|
77
|
+
values = parseArgs({ args, options: optionsFor("profile detect"), strict: true }).values;
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
// Never echo a bare value: it may be a key pasted in the wrong place.
|
|
81
|
+
let msg = e.message;
|
|
82
|
+
for (const a of args)
|
|
83
|
+
if (a && !a.startsWith("-"))
|
|
84
|
+
msg = msg.split(a).join("***");
|
|
85
|
+
return fail(`${msg}\n${USAGE.trimEnd()}`, 2);
|
|
86
|
+
}
|
|
87
|
+
const base = values.lmwarden;
|
|
88
|
+
if (!base)
|
|
89
|
+
return fail(`--lmwarden <url> is required\n${USAGE.trimEnd()}`, 2);
|
|
90
|
+
const tokenEnv = values["token-env"] ?? "LMWARDEN_API_KEY";
|
|
91
|
+
if (!ENV_NAME.test(tokenEnv)) {
|
|
92
|
+
return fail(`--token-env takes the name of an environment variable (letters, digits and _), not the key itself; put the key in a variable and pass its name\n${USAGE.trimEnd()}`, 2);
|
|
93
|
+
}
|
|
94
|
+
const model = values.model;
|
|
95
|
+
let url;
|
|
96
|
+
try {
|
|
97
|
+
url = new URL(base);
|
|
98
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
99
|
+
throw new Error("not http");
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return fail(`--lmwarden must be an http:// or https:// URL\n${USAGE.trimEnd()}`, 2);
|
|
103
|
+
}
|
|
104
|
+
const rawToken = (deps.env ?? process.env)[tokenEnv] ?? "";
|
|
105
|
+
const token = rawToken.trim();
|
|
106
|
+
secrets = [rawToken, token];
|
|
107
|
+
if (rawToken && !token)
|
|
108
|
+
return fail(`the environment variable ${tokenEnv} is empty after trimming whitespace; set it to an LM Warden API key`);
|
|
109
|
+
if (!token)
|
|
110
|
+
return fail(`no token: set the environment variable ${tokenEnv} (or name another with --token-env <VAR>) to an LM Warden API key`);
|
|
111
|
+
if (url.protocol === "http:" && !isLoopback(url.hostname)) {
|
|
112
|
+
process.stderr.write(`warning: sending the API key over plain http to ${url.hostname}; anyone on the network path can read it. Use https:// unless this network is trusted.\n`);
|
|
113
|
+
}
|
|
114
|
+
let res;
|
|
115
|
+
try {
|
|
116
|
+
res = await (deps.fetch ?? fetch)(`${base.replace(/\/+$/, "")}/api/me/engine`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } });
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
return fail(`could not reach LM Warden at ${base}: ${e instanceof Error ? e.message : String(e)}`);
|
|
120
|
+
}
|
|
121
|
+
if (res.status === 401)
|
|
122
|
+
return fail(`LM Warden returned 401: check the API key in ${tokenEnv}`);
|
|
123
|
+
if (res.status === 404)
|
|
124
|
+
return fail("this LM Warden does not have /api/me/engine yet; it needs a newer release");
|
|
125
|
+
if (!res.ok)
|
|
126
|
+
return fail(`LM Warden returned ${res.status}`);
|
|
127
|
+
let found;
|
|
128
|
+
try {
|
|
129
|
+
found = detectFromLmWarden(await res.json(), model);
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
return fail(e instanceof Error ? e.message : String(e));
|
|
133
|
+
}
|
|
134
|
+
const { engine, unknown } = found;
|
|
135
|
+
if (Object.keys(engine).length === 0 && found.context_tokens === undefined)
|
|
136
|
+
return fail("LM Warden could not determine any engine facts for this model yet; is it loaded?");
|
|
137
|
+
const file = join(deps.cwd ?? process.cwd(), "leanprompt.yaml");
|
|
138
|
+
const doc = parseDocument(existsSync(file) ? readFileSync(file, "utf8") : "target:\n engine: lm-warden\n");
|
|
139
|
+
if (doc.errors.length)
|
|
140
|
+
return fail(`${file}: invalid YAML: ${doc.errors[0].message.split("\n")[0]}`);
|
|
141
|
+
let note = "";
|
|
142
|
+
let where = "engine";
|
|
143
|
+
const list = doc.get("targets", true);
|
|
144
|
+
if (isSeq(list)) {
|
|
145
|
+
// Several backends: write into the lm-warden entry, else the vllm one, else add an lm-warden entry.
|
|
146
|
+
const entries = list.items.filter((x) => isMap(x));
|
|
147
|
+
const engineOf = (m) => m.get("engine");
|
|
148
|
+
let pick;
|
|
149
|
+
for (const name of ["lm-warden", "vllm"]) {
|
|
150
|
+
const hits = entries.filter((m) => engineOf(m) === name);
|
|
151
|
+
if (hits.length > 1)
|
|
152
|
+
return fail(`not writing ${file}: targets has several ${name} entries; give the facts to the right one by hand (engine_facts, see docs/profile.md)`);
|
|
153
|
+
if (hits.length === 1) {
|
|
154
|
+
pick = hits[0];
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (!pick) {
|
|
159
|
+
pick = doc.createNode({ engine: "lm-warden" });
|
|
160
|
+
list.add(pick);
|
|
161
|
+
note = "added {engine: lm-warden} to targets";
|
|
162
|
+
}
|
|
163
|
+
if (found.context_tokens !== undefined && !pick.has("context_tokens"))
|
|
164
|
+
pick.set("context_tokens", found.context_tokens);
|
|
165
|
+
if (Object.keys(engine).length) {
|
|
166
|
+
const engineEntries = entries.filter((m) => typeof engineOf(m) === "string").length + (note ? 1 : 0);
|
|
167
|
+
const top = doc.get("engine", true);
|
|
168
|
+
const own = pick.get("engine_facts", true);
|
|
169
|
+
if (isMap(own))
|
|
170
|
+
for (const [k, v] of Object.entries(engine))
|
|
171
|
+
own.set(k, v);
|
|
172
|
+
else if (isMap(top) && engineEntries === 1)
|
|
173
|
+
for (const [k, v] of Object.entries(engine))
|
|
174
|
+
top.set(k, v);
|
|
175
|
+
else
|
|
176
|
+
pick.set("engine_facts", doc.createNode(engine));
|
|
177
|
+
if (!(isMap(top) && engineEntries === 1 && !isMap(own)))
|
|
178
|
+
where = `targets[${list.items.indexOf(pick)}].engine_facts`;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
if (!doc.has("target") || doc.get("target") === null)
|
|
183
|
+
doc.set("target", doc.createNode({ engine: "lm-warden" }));
|
|
184
|
+
const target = doc.get("target", true);
|
|
185
|
+
if (isMap(target)) {
|
|
186
|
+
if (target.has("provider"))
|
|
187
|
+
note = `target.provider is ${String(target.get("provider"))}, left as is; the engine: values apply only to calls logged with a self-hosted engine name (see docs/profile.md)`;
|
|
188
|
+
else if (!target.has("engine"))
|
|
189
|
+
target.set("engine", "lm-warden");
|
|
190
|
+
}
|
|
191
|
+
if (found.context_tokens !== undefined && isMap(target) && !target.has("context_tokens"))
|
|
192
|
+
target.set("context_tokens", found.context_tokens);
|
|
193
|
+
if (Object.keys(engine).length) {
|
|
194
|
+
const existing = doc.get("engine", true);
|
|
195
|
+
if (isMap(existing))
|
|
196
|
+
for (const [k, v] of Object.entries(engine))
|
|
197
|
+
existing.set(k, v);
|
|
198
|
+
else
|
|
199
|
+
doc.set("engine", doc.createNode(engine));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const text = String(doc);
|
|
203
|
+
const { errors } = parseProfile(text);
|
|
204
|
+
if (errors.length)
|
|
205
|
+
return fail(`not writing ${file}: ${errors.join("; ")}`);
|
|
206
|
+
writeFileSync(file, text);
|
|
207
|
+
process.stdout.write(`wrote ${file}: ${Object.entries(engine).map(([k, v]) => `${where}.${k}=${v}`).join(", ")}\n`);
|
|
208
|
+
if (unknown.length)
|
|
209
|
+
process.stdout.write(`not reported by LM Warden, left out: ${unknown.join(", ")}\n`);
|
|
210
|
+
if (note)
|
|
211
|
+
process.stdout.write(`${note}\n`);
|
|
212
|
+
return 0;
|
|
213
|
+
}
|
|
214
|
+
export const profileCommand = async (args) => {
|
|
215
|
+
if (args[0] === "detect")
|
|
216
|
+
return detectCommand(args.slice(1));
|
|
217
|
+
process.stderr.write(USAGE);
|
|
218
|
+
return 2;
|
|
219
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Finding } from "./score/static.js";
|
|
2
|
+
export interface ExpectedFinding {
|
|
3
|
+
rule: string;
|
|
4
|
+
/** Path relative to the case directory, e.g. `before/bot.py`. */
|
|
5
|
+
file: string;
|
|
6
|
+
line: number;
|
|
7
|
+
}
|
|
8
|
+
export type Expected = readonly ExpectedFinding[];
|
|
9
|
+
export interface Comparison {
|
|
10
|
+
/** Share of expected findings that were found, 1 when none were expected. */
|
|
11
|
+
recall: number;
|
|
12
|
+
/** Findings on files under `after/`, where the seeded problems are already fixed. */
|
|
13
|
+
falsePositives: Finding[];
|
|
14
|
+
missed: ExpectedFinding[];
|
|
15
|
+
}
|
|
16
|
+
/** A finding matches an expected one with the same rule, in the same file, within this many lines. */
|
|
17
|
+
export declare const LINE_TOLERANCE = 3;
|
|
18
|
+
/** Each expected finding is matched by at most one reported finding, and each reported finding fills at most one. */
|
|
19
|
+
export declare function compareFindings(expected: Expected, got: readonly Finding[]): Comparison;
|
|
20
|
+
/** Parse an expected file: a JSON array of `{rule, file, line}`. */
|
|
21
|
+
export declare function parseExpected(text: string): Expected;
|
|
22
|
+
export type Form = "before" | "after";
|
|
23
|
+
/** Case name -> directory for `<root>/fixtures/<lang>/<case>`. Throws when two languages use the same case name. */
|
|
24
|
+
export declare function listCases(auditDir: string): Map<string, string>;
|
|
25
|
+
/**
|
|
26
|
+
* Map a reported path to `<form>/<path inside the form>`, or null when it matches no file of the case.
|
|
27
|
+
* A `before/` or `after/` segment decides the form and the part after the last such segment is the path.
|
|
28
|
+
* Otherwise the path is relative to the copied folder (possibly absolute under a copy root): leading
|
|
29
|
+
* segments are dropped until the remainder is a file of `defaultForm`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function mapPath(caseDir: string, file: string, defaultForm: Form): string | null;
|
|
32
|
+
export declare function evalAuditCommand(args: string[]): Promise<number>;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// compareFindings() is pure; evalAuditCommand() reads the case's expected file and an assistant's findings.json.
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, join, resolve } from "node:path";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { optionsFor } from "./help.js";
|
|
6
|
+
import { loadRuleIds } from "./lint/rules.js";
|
|
7
|
+
import { EXTERNAL, parseFindings } from "./score/static.js";
|
|
8
|
+
import { PACKAGE_ROOT } from "./score/write.js";
|
|
9
|
+
/** A finding matches an expected one with the same rule, in the same file, within this many lines. */
|
|
10
|
+
export const LINE_TOLERANCE = 3;
|
|
11
|
+
function normalize(file) {
|
|
12
|
+
return file.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
|
|
13
|
+
}
|
|
14
|
+
/** Each expected finding is matched by at most one reported finding, and each reported finding fills at most one. */
|
|
15
|
+
export function compareFindings(expected, got) {
|
|
16
|
+
const used = new Set();
|
|
17
|
+
const missed = [];
|
|
18
|
+
for (const e of expected) {
|
|
19
|
+
const i = got.findIndex((g, idx) => !used.has(idx) && g.rule === e.rule && normalize(g.file) === normalize(e.file) && Math.abs(g.line - e.line) <= LINE_TOLERANCE);
|
|
20
|
+
if (i < 0)
|
|
21
|
+
missed.push(e);
|
|
22
|
+
else
|
|
23
|
+
used.add(i);
|
|
24
|
+
}
|
|
25
|
+
const falsePositives = got.filter((g) => normalize(g.file).startsWith("after/"));
|
|
26
|
+
const recall = expected.length === 0 ? 1 : (expected.length - missed.length) / expected.length;
|
|
27
|
+
return { recall, falsePositives, missed };
|
|
28
|
+
}
|
|
29
|
+
/** Parse an expected file: a JSON array of `{rule, file, line}`. */
|
|
30
|
+
export function parseExpected(text) {
|
|
31
|
+
const doc = JSON.parse(text);
|
|
32
|
+
if (!Array.isArray(doc))
|
|
33
|
+
throw new Error("expected file must be a JSON array");
|
|
34
|
+
return doc.map((r, i) => {
|
|
35
|
+
const o = r;
|
|
36
|
+
if (!o || typeof o.rule !== "string" || typeof o.file !== "string" || !Number.isInteger(o.line)) {
|
|
37
|
+
throw new Error(`expected[${i}] needs rule, file and line`);
|
|
38
|
+
}
|
|
39
|
+
return { rule: o.rule, file: o.file, line: o.line };
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** Case name -> directory for `<root>/fixtures/<lang>/<case>`. Throws when two languages use the same case name. */
|
|
43
|
+
export function listCases(auditDir) {
|
|
44
|
+
const cases = new Map();
|
|
45
|
+
const fixtures = join(auditDir, "fixtures");
|
|
46
|
+
for (const lang of readdirSync(fixtures)) {
|
|
47
|
+
for (const c of readdirSync(join(fixtures, lang))) {
|
|
48
|
+
const dir = join(fixtures, lang, c);
|
|
49
|
+
if (cases.has(c))
|
|
50
|
+
throw new Error(`duplicate case name ${c}: ${cases.get(c)} and ${dir}`);
|
|
51
|
+
cases.set(c, dir);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return cases;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Map a reported path to `<form>/<path inside the form>`, or null when it matches no file of the case.
|
|
58
|
+
* A `before/` or `after/` segment decides the form and the part after the last such segment is the path.
|
|
59
|
+
* Otherwise the path is relative to the copied folder (possibly absolute under a copy root): leading
|
|
60
|
+
* segments are dropped until the remainder is a file of `defaultForm`.
|
|
61
|
+
*/
|
|
62
|
+
export function mapPath(caseDir, file, defaultForm) {
|
|
63
|
+
const segs = file.replace(/\\/g, "/").split("/").filter((x) => x !== "" && x !== ".");
|
|
64
|
+
let at = -1;
|
|
65
|
+
segs.forEach((x, i) => {
|
|
66
|
+
if (x === "before" || x === "after")
|
|
67
|
+
at = i;
|
|
68
|
+
});
|
|
69
|
+
const isFile = (form, parts) => {
|
|
70
|
+
const p = join(caseDir, form, ...parts);
|
|
71
|
+
return parts.length > 0 && existsSync(p) && statSync(p).isFile();
|
|
72
|
+
};
|
|
73
|
+
if (at >= 0) {
|
|
74
|
+
const form = segs[at];
|
|
75
|
+
const rest = segs.slice(at + 1);
|
|
76
|
+
return isFile(form, rest) ? `${form}/${rest.join("/")}` : null;
|
|
77
|
+
}
|
|
78
|
+
for (let i = 0; i < segs.length; i++) {
|
|
79
|
+
if (isFile(defaultForm, segs.slice(i)))
|
|
80
|
+
return `${defaultForm}/${segs.slice(i).join("/")}`;
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
export async function evalAuditCommand(args) {
|
|
85
|
+
const fail = (msg) => {
|
|
86
|
+
process.stderr.write(`leanprompt: ${msg}\n`);
|
|
87
|
+
return 2;
|
|
88
|
+
};
|
|
89
|
+
let parsed;
|
|
90
|
+
try {
|
|
91
|
+
parsed = parseArgs({ args, options: optionsFor("eval-audit"), allowPositionals: true, strict: true });
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
return fail(e.message);
|
|
95
|
+
}
|
|
96
|
+
const form = parsed.values.form ?? "before";
|
|
97
|
+
if (form !== "before" && form !== "after")
|
|
98
|
+
return fail("--form must be before or after");
|
|
99
|
+
const [caseArg, findingsArg] = parsed.positionals;
|
|
100
|
+
if (parsed.positionals.length !== 2)
|
|
101
|
+
return fail("usage: leanprompt eval-audit <case-dir> <findings.json> [--form before|after]");
|
|
102
|
+
const caseDir = resolve(caseArg);
|
|
103
|
+
const findingsPath = resolve(findingsArg);
|
|
104
|
+
if (!existsSync(caseDir) || !statSync(caseDir).isDirectory())
|
|
105
|
+
return fail(`case directory not found: ${caseArg}`);
|
|
106
|
+
if (!existsSync(findingsPath))
|
|
107
|
+
return fail(`findings file not found: ${findingsArg}`);
|
|
108
|
+
const auditDir = join(PACKAGE_ROOT, "eval", "audit");
|
|
109
|
+
try {
|
|
110
|
+
listCases(auditDir);
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
return fail(e.message);
|
|
114
|
+
}
|
|
115
|
+
const expectedPath = join(auditDir, "expected", `${basename(caseDir)}.json`);
|
|
116
|
+
if (!existsSync(expectedPath))
|
|
117
|
+
return fail(`no expected file for case ${basename(caseDir)} (looked for ${expectedPath})`);
|
|
118
|
+
let expected;
|
|
119
|
+
try {
|
|
120
|
+
expected = parseExpected(readFileSync(expectedPath, "utf8"));
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
return fail(`${expectedPath}: ${e.message}`);
|
|
124
|
+
}
|
|
125
|
+
const { findings, errors } = parseFindings(readFileSync(findingsPath, "utf8"), loadRuleIds(PACKAGE_ROOT));
|
|
126
|
+
if (errors.length > 0 && findings.length === 0)
|
|
127
|
+
return fail(`invalid findings file: ${errors.join("; ")}`);
|
|
128
|
+
for (const e of errors)
|
|
129
|
+
process.stderr.write(`leanprompt: warning: ${e}\n`);
|
|
130
|
+
const got = [];
|
|
131
|
+
const unmatched = [];
|
|
132
|
+
// A finding outside the repository has no file in the case to match: it counts toward neither
|
|
133
|
+
// recall nor false positives. The seeded cases expect none.
|
|
134
|
+
const external = findings.filter((f) => f.file === EXTERNAL).length;
|
|
135
|
+
for (const f of findings) {
|
|
136
|
+
if (f.file === EXTERNAL)
|
|
137
|
+
continue;
|
|
138
|
+
const mapped = mapPath(caseDir, f.file, form);
|
|
139
|
+
if (mapped === null)
|
|
140
|
+
unmatched.push(f);
|
|
141
|
+
else
|
|
142
|
+
got.push({ ...f, file: mapped });
|
|
143
|
+
}
|
|
144
|
+
for (const f of unmatched)
|
|
145
|
+
process.stderr.write(`leanprompt: warning: ${f.file} matches no file of the ${form} form of this case; not counted\n`);
|
|
146
|
+
const { recall, missed, falsePositives } = compareFindings(expected, got);
|
|
147
|
+
const out = [`case: ${basename(caseDir)} (${form} run)`];
|
|
148
|
+
if (form === "before") {
|
|
149
|
+
out.push(`recall: ${recall.toFixed(2)} (${expected.length - missed.length}/${expected.length})`);
|
|
150
|
+
out.push(`missed: ${missed.length}`, ...missed.map((m) => ` ${m.rule} ${m.file}:${m.line}`));
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
out.push("recall: not measured on an after run");
|
|
154
|
+
}
|
|
155
|
+
out.push(`false positives: ${falsePositives.length}`, ...falsePositives.map((f) => ` ${f.rule} ${f.file}:${f.line}`));
|
|
156
|
+
out.push(`unmatched paths: ${unmatched.length}`, ...unmatched.map((f) => ` ${f.rule} ${f.file}:${f.line}`));
|
|
157
|
+
if (external > 0)
|
|
158
|
+
out.push(`external findings: ${external} (not counted)`);
|
|
159
|
+
process.stdout.write(out.join("\n") + "\n");
|
|
160
|
+
return 0;
|
|
161
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface CacheFacts {
|
|
2
|
+
mode: "automatic" | "breakpoints" | "block";
|
|
3
|
+
min_tokens: number;
|
|
4
|
+
step_tokens?: number;
|
|
5
|
+
block_tokens?: number;
|
|
6
|
+
drops_last_block?: boolean;
|
|
7
|
+
max_breakpoints?: number;
|
|
8
|
+
ttl_seconds: number;
|
|
9
|
+
}
|
|
10
|
+
export declare const CACHE_MODES: readonly ["automatic", "breakpoints", "block"];
|
|
11
|
+
/** `cache:` blocks of providers/*.md, keyed by the `provider` frontmatter field. Files without a cache block are skipped. */
|
|
12
|
+
export declare function loadCacheFacts(root: string): Map<string, CacheFacts>;
|
|
13
|
+
/** Tokens of a `reusable`-token shared prefix that the provider could cache. */
|
|
14
|
+
export declare function cap(facts: CacheFacts, reusable: number): number;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { parseDoc } from "./frontmatter.js";
|
|
4
|
+
export const CACHE_MODES = ["automatic", "breakpoints", "block"];
|
|
5
|
+
/** `cache:` blocks of providers/*.md, keyed by the `provider` frontmatter field. Files without a cache block are skipped. */
|
|
6
|
+
export function loadCacheFacts(root) {
|
|
7
|
+
const out = new Map();
|
|
8
|
+
const dir = join(root, "providers");
|
|
9
|
+
if (!existsSync(dir))
|
|
10
|
+
return out;
|
|
11
|
+
for (const f of readdirSync(dir).sort()) {
|
|
12
|
+
if (!f.endsWith(".md"))
|
|
13
|
+
continue;
|
|
14
|
+
const { meta } = parseDoc(readFileSync(join(dir, f), "utf8"));
|
|
15
|
+
if (typeof meta.provider === "string" && meta.cache && typeof meta.cache === "object") {
|
|
16
|
+
out.set(meta.provider, meta.cache);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
/** Tokens of a `reusable`-token shared prefix that the provider could cache. */
|
|
22
|
+
export function cap(facts, reusable) {
|
|
23
|
+
if (reusable < facts.min_tokens)
|
|
24
|
+
return 0;
|
|
25
|
+
switch (facts.mode) {
|
|
26
|
+
case "breakpoints":
|
|
27
|
+
// Missing breakpoints are the app's to fix (D1), so they do not reduce the cap.
|
|
28
|
+
return reusable;
|
|
29
|
+
case "automatic": {
|
|
30
|
+
const step = facts.step_tokens;
|
|
31
|
+
if (!step)
|
|
32
|
+
return reusable;
|
|
33
|
+
return facts.min_tokens + Math.floor((reusable - facts.min_tokens) / step) * step;
|
|
34
|
+
}
|
|
35
|
+
case "block": {
|
|
36
|
+
const block = facts.block_tokens;
|
|
37
|
+
if (!block)
|
|
38
|
+
return reusable;
|
|
39
|
+
const blocks = Math.floor(reusable / block) - (facts.drops_last_block ? 1 : 0);
|
|
40
|
+
return Math.max(0, blocks) * block;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export declare const SKILLS: readonly ["leanprompt", "llm-call-audit", "prefill-cache", "generation-economy", "prompt-diet", "measure-loop", "lmwarden"];
|
|
2
|
+
export declare const BLOCK_BEGIN = "<!-- leanprompt:begin -->";
|
|
3
|
+
export declare const BLOCK_END = "<!-- leanprompt:end -->";
|
|
4
|
+
export declare const GENERATED_MARK = "<!-- leanprompt:generated";
|
|
5
|
+
export declare const generatedStamp: (version: string) => string;
|
|
6
|
+
/** The stamp as a line comment, for the code templates (`//` for .ts, `#` for .py). */
|
|
7
|
+
export declare const codeStamp: (comment: "//" | "#", version: string) => string;
|
|
8
|
+
/** True when a file's text carries any form of the generated stamp (markdown or code comment). */
|
|
9
|
+
export declare const isGenerated: (text: string) => boolean;
|
|
10
|
+
export declare const REPO = "https://github.com/Podwarden/leanprompt";
|
|
11
|
+
export declare function listFiles(dir: string, rel?: string): string[];
|
|
12
|
+
/**
|
|
13
|
+
* Rewrite markdown links in `text`, which lives at repo path `fromFile`.
|
|
14
|
+
* mode "skills": links that stay inside skills/ remain relative; everything else becomes a GitHub URL.
|
|
15
|
+
* mode "flat": every local link becomes a GitHub URL (the file is installed outside the skills tree).
|
|
16
|
+
*/
|
|
17
|
+
export declare function rewriteLinks(text: string, fromFile: string, mode: "skills" | "flat", root: string, version: string): string;
|
|
18
|
+
export declare function agentsBlock(): string;
|
|
19
|
+
export declare function spliceBlock(existing: string | null, block: string): string;
|
|
20
|
+
/** Everything generated from the source tree: repo-relative path -> content. */
|
|
21
|
+
export declare function buildForms(root: string): Map<string, string>;
|
|
22
|
+
/** Files under forms/ on disk that buildForms no longer produces. */
|
|
23
|
+
export declare function staleFiles(root: string, built: Map<string, string>): string[];
|