lakonai 1.2.8 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -7
- package/bin/lakonai.js +41 -1
- package/package.json +1 -1
- package/src/depth.js +212 -0
- package/src/hooks/prompt-depth.js +66 -0
- package/src/hooks/stop-hook.js +55 -1
- package/src/install/claude-commands.js +23 -0
- package/src/install/claude-hook.js +9 -0
- package/src/proxy/brevity.js +61 -0
- package/src/proxy/server.js +4 -1
- package/src/rules/lakonai.md +35 -0
- package/src/tracking.js +32 -1
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
<img src="https://img.shields.io/badge/node-%E2%89%A518-0F0F0F" alt="node ≥18" />
|
|
21
21
|
<img src="https://img.shields.io/badge/deps-0-0F0F0F" alt="zero dependencies" />
|
|
22
22
|
<img src="https://img.shields.io/badge/agents-6-0F0F0F" alt="6 AI agents" />
|
|
23
|
-
<img src="https://img.shields.io/badge/tests-
|
|
23
|
+
<img src="https://img.shields.io/badge/tests-998-0F0F0F" alt="998 tests" />
|
|
24
24
|
</p>
|
|
25
25
|
|
|
26
26
|
<p align="center">
|
|
@@ -83,6 +83,7 @@ All numbers from live projects using `lakonai@1.1.1`.
|
|
|
83
83
|
| Front | What it fixes | How |
|
|
84
84
|
|-------|--------------|-----|
|
|
85
85
|
| **Output** | _"Great question! Let me explain…"_ | Terse-response rule — no preamble, no recap. Auto-clarity for edge cases. |
|
|
86
|
+
| **Answer length** | A correct answer too long to read | Answer budget restated every turn: summary first, depth only when you ask (`lakonai depth on`) |
|
|
86
87
|
| **Shell input** | `git log` dumping 1.8k tokens of metadata | Filters **30+ commands** (git/ls/grep/tests/lint/docker/kubectl/aws…) before they hit context |
|
|
87
88
|
| **Reads** | `Read pnpm-lock.yaml` → 80k of nothing | Hook blocks lockfiles/`node_modules`, caps huge files and `Grep` |
|
|
88
89
|
| **Overflow** | 4k-line build logs no filter knows | Parks on disk, hands the agent a digest — `lakonai peek` reads it back |
|
|
@@ -255,6 +256,7 @@ Query it: lakonai peek 30930a0c --grep "error"
|
|
|
255
256
|
| Pixel (skill PNG) | ✅ | ✅ | — | — |
|
|
256
257
|
| MCP catalog compression | ✅ | — | — | — |
|
|
257
258
|
| Auto-learn new commands | ✅ | ✅ | ✅ | ✅ |
|
|
259
|
+
| Answer budget (per-turn) | ✅ hook | ✅ proxy | ✅ proxy | ✅ proxy |
|
|
258
260
|
|
|
259
261
|
**Primary target: Claude Code.** The proxy and graph layers intercept the Anthropic protocol and are Claude-Code-specific. CLI filters and the universal shim work on every agent. Every install is idempotent and reversible.
|
|
260
262
|
|
|
@@ -268,6 +270,8 @@ After `lakonai install`, these are available in Claude Code:
|
|
|
268
270
|
|---------|--------------|
|
|
269
271
|
| `/lakonai:gain` | Token savings — input (measured) and output (estimated) |
|
|
270
272
|
| `/lakonai:stats` | All layers: filters + proxy breakdown by content type |
|
|
273
|
+
| `/lakonai:deep` | Lift the answer budget for one reply, then back to brief |
|
|
274
|
+
| `/lakonai:brief` | Cancel a pending depth grant — back to summary-first |
|
|
271
275
|
|
|
272
276
|
---
|
|
273
277
|
|
|
@@ -283,6 +287,7 @@ After `lakonai install`, these are available in Claude Code:
|
|
|
283
287
|
| `lakonai pixel [--dry-run\|--revert\|--agent]` | Convert skill files to PNG |
|
|
284
288
|
| `lakonai compress-memory <file>` | Shrink a memory file via your local AI CLI |
|
|
285
289
|
| `lakonai peek [id]` | Read output parked in sandbox (`--grep/--offset/--limit`) |
|
|
290
|
+
| `lakonai depth [on\|off\|status]` | Answer budget: `on` buys one long reply, `off` cancels, `status` reports |
|
|
286
291
|
| `lakonai gain` | Token savings across all measured fronts |
|
|
287
292
|
| `lakonai inspect <cmd>` | Debug what filter applies to a command |
|
|
288
293
|
| `lakonai mcp [wrap\|unwrap]` | MCP catalog compression status/lifecycle |
|
|
@@ -342,16 +347,16 @@ Input is measured and deterministic. Output is estimated by your local AI CLI (n
|
|
|
342
347
|
|
|
343
348
|
## Test suite
|
|
344
349
|
|
|
345
|
-
|
|
350
|
+
998 tests across 61 suites — all passing, no mocks on I/O boundaries.
|
|
346
351
|
|
|
347
352
|
| Type | Suites | Tests |
|
|
348
353
|
|------|--------|-------|
|
|
349
|
-
| Unit |
|
|
350
|
-
| Integration (module + real FS) |
|
|
351
|
-
| E2E / CLI (spawn + real process) |
|
|
352
|
-
| **Total** | **
|
|
354
|
+
| Unit | 14 | 194 |
|
|
355
|
+
| Integration (module + real FS / real HTTP) | 32 | 614 |
|
|
356
|
+
| E2E / CLI (spawn + real process) | 15 | 190 |
|
|
357
|
+
| **Total** | **61** | **998** |
|
|
353
358
|
|
|
354
|
-
Coverage: **
|
|
359
|
+
Coverage: **90% statements · 85% branches · 93% functions** (gate: 80% global; target 100% per new file)
|
|
355
360
|
|
|
356
361
|
Branch ceiling is ~90% — the remaining gaps are canvas-native rendering, platform-specific `fs.watch` fallback, and the HTTPS transport branch (all marked `/* istanbul ignore next */` with justification).
|
|
357
362
|
|
package/bin/lakonai.js
CHANGED
|
@@ -46,6 +46,13 @@ Usage:
|
|
|
46
46
|
budget is spilled to disk automatically and replaced
|
|
47
47
|
with a digest - this is how you read the rest.
|
|
48
48
|
|
|
49
|
+
lakonai depth [on|off|status]
|
|
50
|
+
Output-side brevity. Answers are summary-first by
|
|
51
|
+
default (a line budget restated every turn); \`on\`
|
|
52
|
+
buys ONE long answer, \`off\` cancels it, \`status\`
|
|
53
|
+
reports the current mode. Saying "detalha" /
|
|
54
|
+
"more detail" in a prompt does the same as \`on\`.
|
|
55
|
+
|
|
49
56
|
lakonai gain Show token savings - INPUT (shell output, measured)
|
|
50
57
|
AND OUTPUT (how much terser the model writes; measured
|
|
51
58
|
weekly via your local AI CLI, no API key)
|
|
@@ -539,6 +546,35 @@ function drainPendingWork() {
|
|
|
539
546
|
try { require('../src/install/pending').drain(); } catch { /* best-effort */ }
|
|
540
547
|
}
|
|
541
548
|
|
|
549
|
+
// Output-side brevity control. `on` grants one long answer, `off` revokes,
|
|
550
|
+
// `status` reports. The grant is written under the global key because a slash
|
|
551
|
+
// command cannot learn the session id.
|
|
552
|
+
function runDepth(rest) {
|
|
553
|
+
const depth = require('../src/depth');
|
|
554
|
+
const sub = rest[0] || 'status';
|
|
555
|
+
|
|
556
|
+
if (sub === 'on') {
|
|
557
|
+
depth.grantDepth(null, 1);
|
|
558
|
+
process.stdout.write('lakonai depth: ON - the next answer may run long, then reverts to brief.\n');
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
if (sub === 'off') {
|
|
562
|
+
const had = depth.revokeDepth(null);
|
|
563
|
+
process.stdout.write(`lakonai depth: OFF - brief mode${had ? ' (pending grant cleared)' : ''}.\n`);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (sub === 'status') {
|
|
567
|
+
const active = depth.depthActive(null);
|
|
568
|
+
const b = depth.BUDGETS;
|
|
569
|
+
process.stdout.write(
|
|
570
|
+
`lakonai depth: ${active ? 'ON (one long answer pending)' : 'OFF - brief mode'}\n` +
|
|
571
|
+
` budget: factual <=${b.factual} lines | explanation <=${b.explanation} | plan/review <=${b.plan}\n`
|
|
572
|
+
);
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
process.stdout.write(`lakonai depth: unknown subcommand "${sub}" (use on|off|status)\n`);
|
|
576
|
+
}
|
|
577
|
+
|
|
542
578
|
async function main() {
|
|
543
579
|
const argv = process.argv.slice(2);
|
|
544
580
|
drainPendingWork();
|
|
@@ -587,6 +623,10 @@ async function main() {
|
|
|
587
623
|
runUpgrade();
|
|
588
624
|
return;
|
|
589
625
|
}
|
|
626
|
+
if (first === 'depth') {
|
|
627
|
+
runDepth(rest);
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
590
630
|
if (first === 'gain' || first === 'stats') {
|
|
591
631
|
process.stdout.write(tracking.report());
|
|
592
632
|
// Output side: measure how much terser the model writes (weekly, TTY-only,
|
|
@@ -644,4 +684,4 @@ if (require.main === module) {
|
|
|
644
684
|
});
|
|
645
685
|
}
|
|
646
686
|
|
|
647
|
-
module.exports = { runAndFilter, printVersion, main, runProxy, runMcp, HELP };
|
|
687
|
+
module.exports = { runAndFilter, printVersion, main, runProxy, runMcp, runDepth, HELP };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lakonai",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "lakonai — save AI context tokens. Filters & compresses CLI output (git, ls, grep, find, test runners, lint/build, docker/kubectl/aws) before it reaches Claude Code, Codex, Cursor, Windsurf, Cline or Gemini — and learns to filter new commands automatically the more you use it.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude",
|
package/src/depth.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Output-side brevity: lakonai's filters shrink what the model *reads*; this
|
|
4
|
+
// module shrinks what it *writes*. The contract is summary-first — every answer
|
|
5
|
+
// stays inside a line budget unless the user explicitly asks to go deeper.
|
|
6
|
+
//
|
|
7
|
+
// Depth is opt-in and consumable: one request for detail buys one long answer,
|
|
8
|
+
// not a permanently verbose session.
|
|
9
|
+
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const { homedir } = require('./install/paths');
|
|
13
|
+
|
|
14
|
+
function dataDir() {
|
|
15
|
+
/* istanbul ignore next -- LAKON_HOME is always set under test */
|
|
16
|
+
return process.env.LAKON_HOME || path.join(homedir(), '.lakon');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function statePath() {
|
|
20
|
+
return path.join(dataDir(), 'depth.json');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// A granted depth token outlives a couple of turns but not a whole day — a
|
|
24
|
+
// stale flag would silently turn brevity off for a session that never asked.
|
|
25
|
+
const TTL_MS = 2 * 60 * 60 * 1000;
|
|
26
|
+
|
|
27
|
+
// Line budgets by answer shape. These are caps on prose lines, never on code
|
|
28
|
+
// blocks, diffs or verbatim output (rule 6 outranks rule 8).
|
|
29
|
+
const BUDGETS = {
|
|
30
|
+
factual: 3,
|
|
31
|
+
explanation: 10,
|
|
32
|
+
plan: 20,
|
|
33
|
+
review: 20,
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const DEFAULT_BUDGET = BUDGETS.explanation;
|
|
37
|
+
|
|
38
|
+
function budgetFor(kind) {
|
|
39
|
+
return BUDGETS[kind] || DEFAULT_BUDGET;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Phrases that mean "open it up". Portuguese and English, since the rule block
|
|
43
|
+
// ships to users in both.
|
|
44
|
+
const DEPTH_TRIGGERS = [
|
|
45
|
+
/\bdetalh(a|e|ar|es|ando)\b/i,
|
|
46
|
+
/\baprofund(a|e|ar|ando)\b/i,
|
|
47
|
+
/\bexplica(\s+melhor|\s+direito|\s+tudo)\b/i,
|
|
48
|
+
/\bmais\s+(detalhes?|contexto|profundidade)\b/i,
|
|
49
|
+
/\bpor\s+extenso\b/i,
|
|
50
|
+
/\bsem\s+resumir\b/i,
|
|
51
|
+
/\b(be\s+)?verbose\b/i,
|
|
52
|
+
/\bin\s+(full|detail)\b/i,
|
|
53
|
+
/\bdeep\s*dive\b/i,
|
|
54
|
+
/\bwalk\s+me\s+through\b/i,
|
|
55
|
+
/\bmore\s+detail(s)?\b/i,
|
|
56
|
+
/\bexplain\s+(fully|in\s+depth)\b/i,
|
|
57
|
+
/\bdon'?t\s+summarize\b/i,
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
// Phrases that mean "back to short" — an explicit way out of a depth grant.
|
|
61
|
+
const BRIEF_TRIGGERS = [
|
|
62
|
+
/\bresum(e|a|ido|idamente)\b/i,
|
|
63
|
+
/\bmais\s+curto\b/i,
|
|
64
|
+
/\bs(e|ê|eja)\s+objetiv[oa]\b/i,
|
|
65
|
+
/\bbrief(ly)?\b/i,
|
|
66
|
+
/\bshorter\b/i,
|
|
67
|
+
/\btl;?dr\b/i,
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
function matchesAny(patterns, text) {
|
|
71
|
+
if (!text || typeof text !== 'string') return false;
|
|
72
|
+
return patterns.some((re) => re.test(text));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function wantsDepth(text) {
|
|
76
|
+
return matchesAny(DEPTH_TRIGGERS, text);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function wantsBrief(text) {
|
|
80
|
+
return matchesAny(BRIEF_TRIGGERS, text);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function readState() {
|
|
84
|
+
try {
|
|
85
|
+
const parsed = JSON.parse(fs.readFileSync(statePath(), 'utf8'));
|
|
86
|
+
if (!parsed || typeof parsed !== 'object' || !parsed.sessions) return { sessions: {} };
|
|
87
|
+
return parsed;
|
|
88
|
+
} catch {
|
|
89
|
+
return { sessions: {} };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function writeState(state) {
|
|
94
|
+
try {
|
|
95
|
+
fs.mkdirSync(dataDir(), { recursive: true });
|
|
96
|
+
fs.writeFileSync(statePath(), JSON.stringify(state), 'utf8');
|
|
97
|
+
return true;
|
|
98
|
+
/* istanbul ignore next -- never let a flag write break a hook */
|
|
99
|
+
} catch {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Drop expired grants so the file cannot grow without bound across sessions.
|
|
105
|
+
function prune(state, now = Date.now()) {
|
|
106
|
+
for (const [id, entry] of Object.entries(state.sessions)) {
|
|
107
|
+
if (!entry || typeof entry.t !== 'number' || now - entry.t > TTL_MS) {
|
|
108
|
+
delete state.sessions[id];
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return state;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const GLOBAL_KEY = 'default';
|
|
115
|
+
|
|
116
|
+
function sessionKey(sessionId) {
|
|
117
|
+
return sessionId || GLOBAL_KEY;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// A grant can be addressed to this session, or made globally by the CLI
|
|
121
|
+
// (`lakonai depth on`) — the slash command has no way to learn the session id,
|
|
122
|
+
// so it writes the global key and any session honours it.
|
|
123
|
+
function candidateKeys(sessionId) {
|
|
124
|
+
const own = sessionKey(sessionId);
|
|
125
|
+
return own === GLOBAL_KEY ? [GLOBAL_KEY] : [own, GLOBAL_KEY];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Grant depth for the next `turns` answers in this session.
|
|
129
|
+
function grantDepth(sessionId, turns = 1) {
|
|
130
|
+
const state = prune(readState());
|
|
131
|
+
state.sessions[sessionKey(sessionId)] = { turns: Math.max(1, turns), t: Date.now() };
|
|
132
|
+
writeState(state);
|
|
133
|
+
return turns;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Revoking clears the session's own grant *and* the global one — "resume isso"
|
|
137
|
+
// must not leave a CLI grant standing behind it.
|
|
138
|
+
function revokeDepth(sessionId) {
|
|
139
|
+
const state = prune(readState());
|
|
140
|
+
let had = false;
|
|
141
|
+
for (const key of candidateKeys(sessionId)) {
|
|
142
|
+
if (state.sessions[key]) had = true;
|
|
143
|
+
delete state.sessions[key];
|
|
144
|
+
}
|
|
145
|
+
writeState(state);
|
|
146
|
+
return had;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Is depth active right now? Read-only — does not spend the grant.
|
|
150
|
+
function depthActive(sessionId, now = Date.now()) {
|
|
151
|
+
const state = readState();
|
|
152
|
+
return candidateKeys(sessionId).some((key) => {
|
|
153
|
+
const entry = state.sessions[key];
|
|
154
|
+
if (!entry || typeof entry.t !== 'number') return false;
|
|
155
|
+
if (now - entry.t > TTL_MS) return false;
|
|
156
|
+
return (entry.turns || 0) > 0;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Spend one turn of the grant. Returns true if this turn is allowed to be long.
|
|
161
|
+
function consumeDepth(sessionId) {
|
|
162
|
+
const state = prune(readState());
|
|
163
|
+
for (const key of candidateKeys(sessionId)) {
|
|
164
|
+
const entry = state.sessions[key];
|
|
165
|
+
if (!entry || (entry.turns || 0) <= 0) continue;
|
|
166
|
+
entry.turns -= 1;
|
|
167
|
+
if (entry.turns <= 0) delete state.sessions[key];
|
|
168
|
+
writeState(state);
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// The per-turn reminder injected into context. Deliberately tiny — it is paid
|
|
175
|
+
// on every single turn, so spending 40 lines to ask for brevity would be
|
|
176
|
+
// self-defeating.
|
|
177
|
+
function briefReminder() {
|
|
178
|
+
return [
|
|
179
|
+
'lakonai brief mode — answer budget:',
|
|
180
|
+
` factual ≤${BUDGETS.factual} lines · explanation ≤${BUDGETS.explanation} · plan/review ≤${BUDGETS.plan}`,
|
|
181
|
+
' Summary first. Depth only when asked.',
|
|
182
|
+
' Code, diffs, identifiers and verbatim output do not count and are never truncated.',
|
|
183
|
+
' Cut something the user may want? End with one line: → ask "detalha" to expand.',
|
|
184
|
+
].join('\n');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function depthNotice() {
|
|
188
|
+
return 'lakonai depth mode — this one answer may run long. Reverts to brief next turn.';
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
module.exports = {
|
|
192
|
+
BUDGETS,
|
|
193
|
+
GLOBAL_KEY,
|
|
194
|
+
candidateKeys,
|
|
195
|
+
DEFAULT_BUDGET,
|
|
196
|
+
DEPTH_TRIGGERS,
|
|
197
|
+
BRIEF_TRIGGERS,
|
|
198
|
+
TTL_MS,
|
|
199
|
+
budgetFor,
|
|
200
|
+
wantsDepth,
|
|
201
|
+
wantsBrief,
|
|
202
|
+
grantDepth,
|
|
203
|
+
revokeDepth,
|
|
204
|
+
depthActive,
|
|
205
|
+
consumeDepth,
|
|
206
|
+
readState,
|
|
207
|
+
writeState,
|
|
208
|
+
prune,
|
|
209
|
+
statePath,
|
|
210
|
+
briefReminder,
|
|
211
|
+
depthNotice,
|
|
212
|
+
};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
// UserPromptSubmit: the enforcement point for output-side brevity.
|
|
5
|
+
//
|
|
6
|
+
// The rule block in ~/.claude/CLAUDE.md states the budget once, at session
|
|
7
|
+
// start, and then drifts out of attention as the context fills. This hook
|
|
8
|
+
// restates it on every single turn, which is the only way the contract survives
|
|
9
|
+
// a long session — and it is also where a depth request ("detalha") is detected
|
|
10
|
+
// and spent.
|
|
11
|
+
|
|
12
|
+
const depth = require('../depth');
|
|
13
|
+
|
|
14
|
+
/* istanbul ignore next -- I/O shell */
|
|
15
|
+
async function readStdin() {
|
|
16
|
+
let raw = '';
|
|
17
|
+
process.stdin.setEncoding('utf8');
|
|
18
|
+
for await (const chunk of process.stdin) raw += chunk;
|
|
19
|
+
return raw;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Pure decision: given a prompt, say which mode this turn runs in and what
|
|
23
|
+
// context to inject. No I/O beyond the depth flag file.
|
|
24
|
+
function decide({ sessionId, prompt }) {
|
|
25
|
+
if (process.env.LAKON_NO_BRIEF === '1') return { mode: 'off', context: null };
|
|
26
|
+
|
|
27
|
+
// An explicit "resume isso" cancels a standing grant before it is spent.
|
|
28
|
+
if (depth.wantsBrief(prompt)) depth.revokeDepth(sessionId);
|
|
29
|
+
else if (depth.wantsDepth(prompt)) depth.grantDepth(sessionId, 1);
|
|
30
|
+
|
|
31
|
+
if (depth.consumeDepth(sessionId)) {
|
|
32
|
+
return { mode: 'depth', context: depth.depthNotice() };
|
|
33
|
+
}
|
|
34
|
+
return { mode: 'brief', context: depth.briefReminder() };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function buildResponse(decision) {
|
|
38
|
+
if (!decision.context) return null;
|
|
39
|
+
return {
|
|
40
|
+
hookSpecificOutput: {
|
|
41
|
+
hookEventName: 'UserPromptSubmit',
|
|
42
|
+
additionalContext: decision.context,
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/* istanbul ignore next -- process entry point; decide()/buildResponse() are unit-tested */
|
|
48
|
+
async function main() {
|
|
49
|
+
try {
|
|
50
|
+
const raw = await readStdin();
|
|
51
|
+
if (!raw.trim()) process.exit(0);
|
|
52
|
+
const data = JSON.parse(raw);
|
|
53
|
+
const decision = decide({ sessionId: data.session_id, prompt: data.prompt || '' });
|
|
54
|
+
const response = buildResponse(decision);
|
|
55
|
+
if (response) process.stdout.write(JSON.stringify(response));
|
|
56
|
+
process.exit(0);
|
|
57
|
+
} catch {
|
|
58
|
+
// Never block a prompt because brevity bookkeeping failed.
|
|
59
|
+
process.exit(0);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/* istanbul ignore next */
|
|
64
|
+
if (require.main === module) main();
|
|
65
|
+
|
|
66
|
+
module.exports = { decide, buildResponse };
|
package/src/hooks/stop-hook.js
CHANGED
|
@@ -58,6 +58,57 @@ function extractUsage(transcriptPath) {
|
|
|
58
58
|
return null;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
// The assistant's own text for the turn that just ended, concatenated across
|
|
62
|
+
// text blocks. Tool calls and thinking are not part of what the user reads.
|
|
63
|
+
function extractLastAssistantText(transcriptPath) {
|
|
64
|
+
try {
|
|
65
|
+
const content = fs.readFileSync(transcriptPath, 'utf8');
|
|
66
|
+
const lines = content.split('\n').filter(Boolean);
|
|
67
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
68
|
+
let obj;
|
|
69
|
+
try { obj = JSON.parse(lines[i]); } catch { continue; }
|
|
70
|
+
const msg = obj.message;
|
|
71
|
+
if (!msg || msg.role !== 'assistant') continue;
|
|
72
|
+
if (typeof msg.content === 'string') return msg.content;
|
|
73
|
+
if (Array.isArray(msg.content)) {
|
|
74
|
+
const text = msg.content
|
|
75
|
+
.filter((b) => b && b.type === 'text' && typeof b.text === 'string')
|
|
76
|
+
.map((b) => b.text)
|
|
77
|
+
.join('\n');
|
|
78
|
+
if (text.trim()) return text;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/* istanbul ignore next -- unreadable transcript */
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Prose lines only. Fenced code, diffs and tables are exempt from the answer
|
|
89
|
+
// budget (rule 8), so counting them would misreport every turn that ships a
|
|
90
|
+
// patch as a budget violation.
|
|
91
|
+
function proseLines(text) {
|
|
92
|
+
if (!text || typeof text !== 'string') return 0;
|
|
93
|
+
let inFence = false;
|
|
94
|
+
let count = 0;
|
|
95
|
+
for (const raw of text.split('\n')) {
|
|
96
|
+
const line = raw.trim();
|
|
97
|
+
if (/^(```|~~~)/.test(line)) { inFence = !inFence; continue; }
|
|
98
|
+
if (inFence) continue;
|
|
99
|
+
if (!line) continue;
|
|
100
|
+
if (line.startsWith('|')) continue; // table row
|
|
101
|
+
count += 1;
|
|
102
|
+
}
|
|
103
|
+
return count;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function responseShape(transcriptPath) {
|
|
107
|
+
const text = extractLastAssistantText(transcriptPath);
|
|
108
|
+
if (text === null) return null;
|
|
109
|
+
return { out_lines: proseLines(text), out_chars: text.length };
|
|
110
|
+
}
|
|
111
|
+
|
|
61
112
|
/* istanbul ignore next */
|
|
62
113
|
async function main() {
|
|
63
114
|
try {
|
|
@@ -83,6 +134,9 @@ async function main() {
|
|
|
83
134
|
trackSession({
|
|
84
135
|
session_id: data.session_id || null,
|
|
85
136
|
...usage,
|
|
137
|
+
// Output-side brevity telemetry: without a baseline there is no way to
|
|
138
|
+
// tell whether the answer budget actually changed anything.
|
|
139
|
+
...(responseShape(data.transcript_path) || {}),
|
|
86
140
|
});
|
|
87
141
|
process.exit(0);
|
|
88
142
|
} catch {
|
|
@@ -92,4 +146,4 @@ async function main() {
|
|
|
92
146
|
/* istanbul ignore next */
|
|
93
147
|
if (require.main === module) main();
|
|
94
148
|
|
|
95
|
-
module.exports = { extractUsage, trackSession, lakonHome };
|
|
149
|
+
module.exports = { extractUsage, trackSession, lakonHome, extractLastAssistantText, proseLines, responseShape };
|
|
@@ -45,6 +45,29 @@ try {
|
|
|
45
45
|
} catch { console.log('proxy: no data yet'); }
|
|
46
46
|
"
|
|
47
47
|
\`\`\`
|
|
48
|
+
`,
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: 'deep',
|
|
52
|
+
body: `---
|
|
53
|
+
description: Lift the lakonai answer budget for ONE reply (then back to brief).
|
|
54
|
+
allowed-tools: Bash(lakonai depth:*)
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
Run \`lakonai depth on\`, then answer the user's previous question again — this
|
|
58
|
+
time in full, without the line budget. Keep the terse style (no preamble, no
|
|
59
|
+
restating), but do not truncate: give the reasoning, the alternatives and the
|
|
60
|
+
trade-offs you compressed away.
|
|
61
|
+
`,
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: 'brief',
|
|
65
|
+
body: `---
|
|
66
|
+
description: Cancel a pending depth grant — back to summary-first answers.
|
|
67
|
+
allowed-tools: Bash(lakonai depth:*)
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
Run \`lakonai depth off\` and confirm in one line. Resume summary-first answers.
|
|
48
71
|
`,
|
|
49
72
|
},
|
|
50
73
|
];
|
|
@@ -35,6 +35,15 @@ const HOOKS = [
|
|
|
35
35
|
event: 'PostToolUse',
|
|
36
36
|
matcher: 'Bash|Read|Grep|Glob|WebFetch|Task',
|
|
37
37
|
},
|
|
38
|
+
{
|
|
39
|
+
// Output-side brevity. The rule block states the answer budget once at
|
|
40
|
+
// session start and then drifts out of attention; this restates it on every
|
|
41
|
+
// turn, and is where a "detalha" request is detected and spent.
|
|
42
|
+
basename: 'lakon-prompt-depth.js',
|
|
43
|
+
src: path.join(__dirname, '..', 'hooks', 'prompt-depth.js'),
|
|
44
|
+
event: 'UserPromptSubmit',
|
|
45
|
+
matcher: null,
|
|
46
|
+
},
|
|
38
47
|
{
|
|
39
48
|
basename: 'lakon-stop-hook.js',
|
|
40
49
|
src: path.join(__dirname, '..', 'hooks', 'stop-hook.js'),
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Proxy-side half of output brevity.
|
|
4
|
+
//
|
|
5
|
+
// The UserPromptSubmit hook only exists inside Claude Code. Every other client
|
|
6
|
+
// that speaks the Messages API through this proxy (Codex, Cursor, a raw SDK
|
|
7
|
+
// script) gets the contract here instead, appended to the system prompt.
|
|
8
|
+
//
|
|
9
|
+
// Appended as a NEW trailing block, never by editing an existing one: the
|
|
10
|
+
// existing blocks carry the cache breakpoints, and rewriting them would
|
|
11
|
+
// invalidate the prompt cache on every request — spending far more tokens than
|
|
12
|
+
// brevity saves.
|
|
13
|
+
|
|
14
|
+
const depth = require('../depth');
|
|
15
|
+
|
|
16
|
+
const MARKER = 'lakonai brief mode';
|
|
17
|
+
|
|
18
|
+
function contract() {
|
|
19
|
+
return depth.briefReminder();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Already injected? Also catches the rule block a user installed into their own
|
|
23
|
+
// system prompt, so we never state the contract twice.
|
|
24
|
+
function hasContract(system) {
|
|
25
|
+
if (typeof system === 'string') return system.includes(MARKER);
|
|
26
|
+
if (Array.isArray(system)) {
|
|
27
|
+
return system.some((b) => typeof b === 'string' ? b.includes(MARKER) : String(b && b.text || '').includes(MARKER));
|
|
28
|
+
}
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Append the brevity contract to a request body's system prompt.
|
|
33
|
+
// Returns { body, injected } — body is the same object reference when untouched.
|
|
34
|
+
function injectBrevity(body, { active = true } = {}) {
|
|
35
|
+
if (!active) return { body, injected: false };
|
|
36
|
+
if (!body || typeof body !== 'object') return { body, injected: false };
|
|
37
|
+
if (hasContract(body.system)) return { body, injected: false };
|
|
38
|
+
|
|
39
|
+
const text = contract();
|
|
40
|
+
|
|
41
|
+
if (typeof body.system === 'string') {
|
|
42
|
+
return { body: { ...body, system: `${body.system}\n\n${text}` }, injected: true };
|
|
43
|
+
}
|
|
44
|
+
if (Array.isArray(body.system)) {
|
|
45
|
+
return { body: { ...body, system: [...body.system, { type: 'text', text }] }, injected: true };
|
|
46
|
+
}
|
|
47
|
+
if (body.system === undefined || body.system === null) {
|
|
48
|
+
return { body: { ...body, system: text }, injected: true };
|
|
49
|
+
}
|
|
50
|
+
// Unknown shape — leave it alone rather than risk a malformed request.
|
|
51
|
+
return { body, injected: false };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Whether the proxy should inject right now. A depth grant suppresses it so an
|
|
55
|
+
// explicit "detalha" is not overridden by the proxy a moment later.
|
|
56
|
+
function shouldInject() {
|
|
57
|
+
if (process.env.LAKON_NO_BRIEF === '1') return false;
|
|
58
|
+
return !depth.depthActive(null);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
module.exports = { injectBrevity, hasContract, contract, shouldInject, MARKER };
|
package/src/proxy/server.js
CHANGED
|
@@ -6,6 +6,7 @@ const fs = require('fs');
|
|
|
6
6
|
const path = require('path');
|
|
7
7
|
const os = require('os');
|
|
8
8
|
const { compressRequest } = require('./compress');
|
|
9
|
+
const { injectBrevity, shouldInject } = require('./brevity');
|
|
9
10
|
const state = require('./state');
|
|
10
11
|
|
|
11
12
|
const DEFAULT_PORT = state.DEFAULT_PORT;
|
|
@@ -53,7 +54,9 @@ function createServer(port = DEFAULT_PORT, upstream = DEFAULT_UPSTREAM) {
|
|
|
53
54
|
try {
|
|
54
55
|
const parsed = JSON.parse(rawBody.toString('utf8'));
|
|
55
56
|
const { body: compressed, stats } = compressRequest(parsed);
|
|
56
|
-
|
|
57
|
+
// Input side is now compressed; ask for a terse answer on the way out.
|
|
58
|
+
const { body: final } = injectBrevity(compressed, { active: shouldInject() });
|
|
59
|
+
bodyToSend = Buffer.from(JSON.stringify(final), 'utf8');
|
|
57
60
|
const existing = readStats();
|
|
58
61
|
mergeStats(existing, stats);
|
|
59
62
|
writeStats(existing);
|
package/src/rules/lakonai.md
CHANGED
|
@@ -11,12 +11,47 @@ You are operating in **lakonai mode** (named for Lakonía - the region of ancien
|
|
|
11
11
|
5. **One short line for what you did.** Not a paragraph. The diff speaks for itself.
|
|
12
12
|
6. **Keep precision.** Identifiers, file paths, line numbers, error messages - verbatim. Never compress these.
|
|
13
13
|
7. **End with the next step, when there is one.** One imperative line: "Run `npm test`." Not "you may want to test this". Omit it when the task is done - never invent follow-up work to have something to suggest.
|
|
14
|
+
8. **Stay inside the answer budget.** Summary first; depth only when asked. See below.
|
|
15
|
+
|
|
16
|
+
## Response budget - summary first, depth on demand
|
|
17
|
+
|
|
18
|
+
A correct answer that is too long to read has failed. Default to the shortest
|
|
19
|
+
form that is still complete, and let the user pull for more.
|
|
20
|
+
|
|
21
|
+
| Answer shape | Budget |
|
|
22
|
+
|-----------------------------------|--------------|
|
|
23
|
+
| Factual question, yes/no, lookup | <= 3 lines |
|
|
24
|
+
| Explanation, "how does X work" | <= 10 lines |
|
|
25
|
+
| Plan, review, design proposal | <= 20 lines |
|
|
26
|
+
|
|
27
|
+
What the budget does **not** count, and must never truncate:
|
|
28
|
+
|
|
29
|
+
- code blocks, diffs, patches, commit messages
|
|
30
|
+
- verbatim output: file paths, line numbers, identifiers, error messages, stack frames
|
|
31
|
+
- tables and command output the user asked to see
|
|
32
|
+
|
|
33
|
+
Rule 6 outranks rule 8 - never drop a path or an error string to fit a budget.
|
|
34
|
+
Cut the prose around it instead.
|
|
35
|
+
|
|
36
|
+
When you cut something the user might want, say so in one trailing line:
|
|
37
|
+
|
|
38
|
+
> -> pede "detalha" pra abrir
|
|
39
|
+
|
|
40
|
+
**Going deeper is opt-in.** Write the long version only when the user asks for
|
|
41
|
+
it - "detalha", "aprofunda", "explica melhor", "more detail", "in full",
|
|
42
|
+
`/lakonai:deep`, or `lakonai depth on`. One request buys one long answer; the
|
|
43
|
+
next turn is back to the budget. `/lakonai:brief` or `lakonai depth off`
|
|
44
|
+
cancels a pending grant.
|
|
45
|
+
|
|
46
|
+
Do not pre-empt the ask. Offering "want me to go deeper?" on every answer is
|
|
47
|
+
itself filler - only offer when you actually cut something load-bearing.
|
|
14
48
|
|
|
15
49
|
## When to drop the style (auto-clarity)
|
|
16
50
|
|
|
17
51
|
Switch to normal prose for:
|
|
18
52
|
|
|
19
53
|
- Security warnings or destructive/irreversible-action confirmations
|
|
54
|
+
- The user asked for depth (the budget is lifted, not the accuracy bar)
|
|
20
55
|
- Multi-step sequences where fragment order or an omitted conjunction could be misread
|
|
21
56
|
- Cases where compressing would itself create technical ambiguity
|
|
22
57
|
- The user is confused or repeating the same question
|
package/src/tracking.js
CHANGED
|
@@ -91,6 +91,27 @@ function byCommand(entries) {
|
|
|
91
91
|
return [...map.values()].sort((a, b) => b.saved - a.saved);
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
+
// Output side: how long the model's own answers are. Session entries are
|
|
95
|
+
// written by the Stop hook; `out_lines` only exists on entries recorded since
|
|
96
|
+
// the answer budget shipped, so older sessions are simply skipped.
|
|
97
|
+
function responseStats(entries) {
|
|
98
|
+
const turns = entries.filter((e) => isSessionEntry(e) && typeof e.out_lines === 'number');
|
|
99
|
+
if (!turns.length) return null;
|
|
100
|
+
const sum = (k) => turns.reduce((a, e) => a + (e[k] || 0), 0);
|
|
101
|
+
const lines = sum('out_lines');
|
|
102
|
+
const { BUDGETS } = require('./depth');
|
|
103
|
+
// The loosest budget (plan/review) is the conservative bar — a turn over it
|
|
104
|
+
// is long by any reading.
|
|
105
|
+
const overBudget = turns.filter((e) => e.out_lines > BUDGETS.plan).length;
|
|
106
|
+
return {
|
|
107
|
+
turns: turns.length,
|
|
108
|
+
lines,
|
|
109
|
+
tokens: sum('out_tokens'),
|
|
110
|
+
avgLines: Math.round((lines / turns.length) * 10) / 10,
|
|
111
|
+
overBudget,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
94
115
|
function pct(saved, raw) {
|
|
95
116
|
if (!raw) return 0;
|
|
96
117
|
return Math.round((saved / raw) * 100);
|
|
@@ -146,6 +167,16 @@ function report() {
|
|
|
146
167
|
lines.push(` ${pad(label, 11)}${green(tok(a.saved))} saved ${dim(`(${pct(a.saved, a.raw)}%)`)}`);
|
|
147
168
|
}
|
|
148
169
|
|
|
170
|
+
const resp = responseStats(entries);
|
|
171
|
+
if (resp) {
|
|
172
|
+
const share = Math.round((resp.overBudget / resp.turns) * 100);
|
|
173
|
+
lines.push('');
|
|
174
|
+
lines.push(
|
|
175
|
+
` ${pad('answers', 11)}${green(`${resp.avgLines} lines`)} avg across ${resp.turns} turns ` +
|
|
176
|
+
dim(`(${resp.overBudget} over budget, ${share}%)`)
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
149
180
|
const top = byCommand(entries).slice(0, 5);
|
|
150
181
|
if (top.length) {
|
|
151
182
|
lines.push('');
|
|
@@ -160,4 +191,4 @@ function reset() {
|
|
|
160
191
|
catch { return false; }
|
|
161
192
|
}
|
|
162
193
|
|
|
163
|
-
module.exports = { record, report, reset, readEntries, logPath };
|
|
194
|
+
module.exports = { record, report, reset, readEntries, logPath, responseStats };
|