lakonai 1.2.8 → 1.4.1

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.
@@ -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,128 @@
1
+ 'use strict';
2
+
3
+ // Codex CLI hooks. Codex (0.16x+) reads Claude-compatible hooks from
4
+ // `~/.codex/hooks.json`: a PreToolUse handler matched on `Bash` gets
5
+ // `tool_input.command` and may answer `permissionDecision: "allow"` with
6
+ // `updatedInput.command`, which is exactly what bash-rewrite emits. So Codex
7
+ // gets the same automatic `lakonai` prefix as Claude Code, with no PATH shim.
8
+ //
9
+ // Codex only runs a non-managed hook after the user reviews and trusts it
10
+ // (`/hooks` in the TUI); until then it is skipped, never half-applied.
11
+
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const { backupFile } = require('./backup');
15
+ const { writeFileAtomic } = require('./atomic');
16
+
17
+ const HOOKS = [
18
+ {
19
+ basename: 'lakon-bash-rewrite.js',
20
+ src: path.join(__dirname, '..', 'hooks', 'bash-rewrite.js'),
21
+ event: 'PreToolUse',
22
+ matcher: '^Bash$',
23
+ },
24
+ ];
25
+
26
+ const BASENAMES = HOOKS.map((h) => h.basename);
27
+
28
+ function codexDir(home) {
29
+ return path.join(home, '.codex');
30
+ }
31
+
32
+ function hooksJsonPath(home) {
33
+ return path.join(codexDir(home), 'hooks.json');
34
+ }
35
+
36
+ function launcherPath(home, basename) {
37
+ return path.join(codexDir(home), 'hooks', basename);
38
+ }
39
+
40
+ function readHooksJson(home) {
41
+ const p = hooksJsonPath(home);
42
+ if (!fs.existsSync(p)) return { ok: true, data: {} };
43
+ try {
44
+ const data = JSON.parse(fs.readFileSync(p, 'utf8'));
45
+ return { ok: true, data: data && typeof data === 'object' ? data : {} };
46
+ } catch (err) {
47
+ return { ok: false, error: err.message };
48
+ }
49
+ }
50
+
51
+ const ownsHandler = (h) => !!h && typeof h.command === 'string' && BASENAMES.some((b) => h.command.includes(b));
52
+
53
+ // Drop every lakonai handler; returns the cleaned data (empty groups removed).
54
+ function stripOurs(data) {
55
+ if (!data.hooks || typeof data.hooks !== 'object') return data;
56
+ for (const event of Object.keys(data.hooks)) {
57
+ if (!Array.isArray(data.hooks[event])) continue;
58
+ data.hooks[event] = data.hooks[event]
59
+ .map((group) => {
60
+ if (!group || !Array.isArray(group.hooks)) return group;
61
+ const keep = group.hooks.filter((h) => !ownsHandler(h));
62
+ return keep.length ? { ...group, hooks: keep } : null;
63
+ })
64
+ .filter(Boolean);
65
+ if (!data.hooks[event].length) delete data.hooks[event];
66
+ }
67
+ if (!Object.keys(data.hooks).length) delete data.hooks;
68
+ return data;
69
+ }
70
+
71
+ function installCodexHooks(home) {
72
+ const { ok, data, error } = readHooksJson(home);
73
+ if (!ok) return { installed: false, note: `hooks.json could not be parsed (${error})` };
74
+ const p = hooksJsonPath(home);
75
+ if (fs.existsSync(p)) backupFile('codex', p);
76
+
77
+ stripOurs(data); // idempotent: re-install replaces, never duplicates
78
+ data.hooks = data.hooks || {};
79
+ for (const h of HOOKS) {
80
+ const dest = launcherPath(home, h.basename);
81
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
82
+ fs.writeFileSync(
83
+ dest,
84
+ `#!/usr/bin/env node\n// lakonai hook launcher (generated)\nrequire('module')._load(${JSON.stringify(h.src)}, null, true);\n`
85
+ );
86
+ fs.chmodSync(dest, 0o755);
87
+ data.hooks[h.event] = data.hooks[h.event] || [];
88
+ data.hooks[h.event].push({
89
+ matcher: h.matcher,
90
+ hooks: [{ type: 'command', command: dest, timeout: 10 }],
91
+ });
92
+ }
93
+ writeFileAtomic(p, JSON.stringify(data, null, 2) + '\n');
94
+ return { installed: true, path: p };
95
+ }
96
+
97
+ function uninstallCodexHooks(home) {
98
+ const { ok, data } = readHooksJson(home);
99
+ const p = hooksJsonPath(home);
100
+ if (ok && fs.existsSync(p)) {
101
+ stripOurs(data);
102
+ if (Object.keys(data).length) writeFileAtomic(p, JSON.stringify(data, null, 2) + '\n');
103
+ else fs.unlinkSync(p);
104
+ }
105
+ for (const b of BASENAMES) {
106
+ try {
107
+ fs.unlinkSync(launcherPath(home, b));
108
+ } catch {
109
+ /* already gone */
110
+ }
111
+ }
112
+ }
113
+
114
+ function codexHooksInstalled(home) {
115
+ const { ok, data } = readHooksJson(home);
116
+ if (!ok || !data.hooks) return false;
117
+ return JSON.stringify(data.hooks).includes('lakon-bash-rewrite.js');
118
+ }
119
+
120
+ module.exports = {
121
+ installCodexHooks,
122
+ uninstallCodexHooks,
123
+ codexHooksInstalled,
124
+ hooksJsonPath,
125
+ launcherPath,
126
+ stripOurs,
127
+ HOOKS,
128
+ };
@@ -5,6 +5,7 @@ const path = require('path');
5
5
  const { backupFile, restoreAllBackups } = require('./backup');
6
6
  const { installHook, uninstallHook } = require('./claude-hook');
7
7
  const { installCommands, uninstallCommands } = require('./claude-commands');
8
+ const { installCodexHooks, uninstallCodexHooks, codexHooksInstalled } = require('./codex-hook');
8
9
  const { wrapMcp, unwrapMcp } = require('./mcp');
9
10
  const { writeFileAtomic } = require('./atomic');
10
11
  const { claudeConfigDir } = require('./paths');
@@ -113,9 +114,22 @@ const PLATFORMS = [
113
114
  label: 'Codex CLI',
114
115
  scope: 'global',
115
116
  rulePath: (home) => path.join(home, '.codex', 'AGENTS.md'),
117
+ hasHooks: true,
118
+ hooksInstalled: (home) => codexHooksInstalled(home),
116
119
  detect: (home) => dirExists(path.join(home, '.codex')),
117
- install: ({ home, rule, id }) => upsertBlock(id, path.join(home, '.codex', 'AGENTS.md'), rule),
118
- uninstall: ({ home }) => stripBlock(path.join(home, '.codex', 'AGENTS.md')),
120
+ install: ({ home, rule, id }) => {
121
+ const rulePath = upsertBlock(id, path.join(home, '.codex', 'AGENTS.md'), rule);
122
+ const hooks = installCodexHooks(home);
123
+ /* istanbul ignore next -- the parse-failure note is covered in codex-hook tests */
124
+ const suffix = hooks.installed
125
+ ? '+ PreToolUse hook (trust it once with /hooks in Codex)'
126
+ : `(hook: ${hooks.note})`;
127
+ return `${rulePath} ${suffix}`;
128
+ },
129
+ uninstall: ({ home }) => {
130
+ uninstallCodexHooks(home);
131
+ return stripBlock(path.join(home, '.codex', 'AGENTS.md'));
132
+ },
119
133
  },
120
134
  {
121
135
  id: 'cursor',
@@ -3,6 +3,7 @@
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
5
  const os = require('os');
6
+ const { isLearnable } = require('./learn');
6
7
 
7
8
  const DAY_MS = 24 * 60 * 60 * 1000;
8
9
  const REPORT_TTL_MS = DAY_MS;
@@ -61,7 +62,7 @@ function readLogSinks() {
61
62
  function readUnfilteredSinks(isBuiltin) {
62
63
  const stats = readJson(statsPath(), {});
63
64
  return Object.entries(stats)
64
- .filter(([cmd]) => !isBuiltin(cmd))
65
+ .filter(([cmd]) => !isBuiltin(cmd) && isLearnable(cmd))
65
66
  .map(([cmd, s]) => ({
66
67
  cmd,
67
68
  calls: s.count,
package/src/learn.js CHANGED
@@ -15,6 +15,7 @@ const fs = require('fs');
15
15
  const path = require('path');
16
16
  const os = require('os');
17
17
  const { countTokensApprox } = require('./filters/utils');
18
+ const { splitCdPrefix } = require('./shell');
18
19
 
19
20
  const MIN_CALLS = Number(process.env.LAKON_LEARN_MIN_CALLS) || 3;
20
21
  const MIN_AVG_TOKENS = Number(process.env.LAKON_LEARN_MIN_TOKENS) || 300;
@@ -44,12 +45,44 @@ function writeJson(file, data) {
44
45
  }
45
46
  }
46
47
 
47
- // Base command of a shell string, skipping env assignments / sudo / env.
48
+ // A learnable command is a bare executable name. Paths, quoted fragments,
49
+ // flags and split-up arguments (`Support/…` from an unquoted
50
+ // `Application Support`, `-n`, `foo;`) were landing in learned.json.
51
+ const VALID_NAME = /^[A-Za-z0-9_][\w.+-]*$/;
52
+
53
+ // Never learned, even when they are loud:
54
+ // - shell builtins / keywords and lakonai itself — nothing to filter, or
55
+ // the output is already filtered;
56
+ // - agent tool names logged by the guards (Read, Grep, …);
57
+ // - interpreters and file mutators — a learned command is rewritten by the
58
+ // PreToolUse hook, which answers "allow", and `node -e …` or `rm` must
59
+ // keep going through the user's own permission rules.
60
+ const NEVER_LEARN = new Set([
61
+ 'cd', 'echo', 'printf', 'export', 'source', 'set', 'unset', 'eval', 'exec', 'exit',
62
+ 'command', 'builtin', 'type', 'which', 'alias', 'true', 'false', 'test',
63
+ 'for', 'while', 'until', 'if', 'then', 'else', 'fi', 'do', 'done', 'case', 'esac',
64
+ 'sleep', 'wait', 'read', 'pwd', 'time', 'lakonai',
65
+ 'Read', 'Grep', 'Glob', 'Bash', 'Edit', 'Write',
66
+ 'node', 'python', 'python3', 'ruby', 'perl', 'php', 'deno', 'bun',
67
+ 'bash', 'sh', 'zsh', 'fish', 'osascript',
68
+ 'rm', 'mv', 'cp', 'ln', 'chmod', 'chown', 'mkdir', 'rmdir', 'touch', 'kill', 'pkill',
69
+ 'dd', 'tee', 'xargs', 'sudo', 'env',
70
+ ]);
71
+
72
+ function isLearnable(cmd) {
73
+ return typeof cmd === 'string' && VALID_NAME.test(cmd) && !NEVER_LEARN.has(cmd);
74
+ }
75
+
76
+ // Base command of a shell string: skips `cd <dir> &&` prefixes, env
77
+ // assignments and sudo/env, and returns '' for anything that is not learnable.
48
78
  function baseCommand(command) {
49
- const tokens = String(command).trim().split(/\s+/);
79
+ let s = String(command).trim();
80
+ for (let cd = splitCdPrefix(s); cd; cd = splitCdPrefix(s)) s = cd.rest;
81
+ const tokens = s.split(/\s+/);
50
82
  let i = 0;
51
83
  while (i < tokens.length && (/^\w+=/.test(tokens[i]) || tokens[i] === 'sudo' || tokens[i] === 'env')) i++;
52
- return tokens[i] || '';
84
+ const cmd = tokens[i] || '';
85
+ return isLearnable(cmd) ? cmd : '';
53
86
  }
54
87
 
55
88
  // Parse a Claude Code transcript (JSONL) into [{ cmd, tokens }] for every Bash
@@ -97,7 +130,7 @@ function promote(stats, isBuiltin) {
97
130
  const learned = new Set(readJson(learnedPath(), []));
98
131
  let changed = false;
99
132
  for (const [cmd, s] of Object.entries(stats)) {
100
- if (learned.has(cmd) || isBuiltin(cmd)) continue;
133
+ if (learned.has(cmd) || isBuiltin(cmd) || !isLearnable(cmd)) continue;
101
134
  if (s.count >= MIN_CALLS && s.tokens / s.count >= MIN_AVG_TOKENS) {
102
135
  learned.add(cmd);
103
136
  changed = true;
@@ -154,7 +187,7 @@ function analyzeLog(isBuiltin) {
154
187
  continue;
155
188
  }
156
189
  const cmd = e && typeof e.cmd === 'string' ? e.cmd : null;
157
- if (!cmd || cmd === 'session' || isBuiltin(cmd)) continue;
190
+ if (!cmd || cmd === 'session' || isBuiltin(cmd) || !isLearnable(cmd)) continue;
158
191
  const s = stats[cmd] || { count: 0, tokens: 0 };
159
192
  s.count += 1;
160
193
  s.tokens += e.raw || 0;
@@ -179,7 +212,12 @@ function maybeLearnFromLog(isBuiltin, now = Date.now()) {
179
212
 
180
213
  let _learnedCache;
181
214
  function learnedCommands() {
182
- if (_learnedCache === undefined) _learnedCache = new Set(readJson(learnedPath(), []));
215
+ // Filter on read, so entries learned by older versions (paths, `node`)
216
+ // stop being rewritten without anyone editing learned.json by hand.
217
+ if (_learnedCache === undefined) {
218
+ const raw = readJson(learnedPath(), []);
219
+ _learnedCache = new Set(Array.isArray(raw) ? raw.filter(isLearnable) : []);
220
+ }
183
221
  return _learnedCache;
184
222
  }
185
223
  function isLearned(cmd) {
@@ -192,6 +230,8 @@ function _resetCache() {
192
230
 
193
231
  module.exports = {
194
232
  baseCommand,
233
+ isLearnable,
234
+ NEVER_LEARN,
195
235
  extractBashUsage,
196
236
  promote,
197
237
  analyzeTranscript,
@@ -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 };
@@ -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
- bodyToSend = Buffer.from(JSON.stringify(compressed), 'utf8');
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);
@@ -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/shell.js ADDED
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+
3
+ // A deliberately small shell lexer. lakonai never executes or rewrites shell
4
+ // syntax it does not understand: these helpers only answer two questions about
5
+ // a command string — "which control operators appear at the top level (outside
6
+ // quotes)?" and "does it start with a `cd <dir> &&` prefix?". Anything the
7
+ // lexer cannot account for (an unbalanced quote) makes the caller back off.
8
+
9
+ // Operators reported at the top level of a command:
10
+ // '&&' '||' ';' '&' '\n' '|' — command separators / pipes
11
+ // '$(' '`' — command substitution (also inside "…")
12
+ // '>' '<' — a redirection that touches a file
13
+ // 'dup' — an fd duplication such as `2>&1`
14
+ // 'null' — a redirection to /dev/null
15
+ // Returns [{ op, i }] in source order, or null for an unbalanced quote.
16
+ function topLevelOps(s) {
17
+ const ops = [];
18
+ let i = 0;
19
+ let quote = null;
20
+ while (i < s.length) {
21
+ const c = s[i];
22
+ if (quote === "'") {
23
+ if (c === "'") quote = null;
24
+ i++;
25
+ continue;
26
+ }
27
+ if (quote === '"') {
28
+ if (c === '\\') {
29
+ i += 2;
30
+ continue;
31
+ }
32
+ if (c === '"') quote = null;
33
+ else if (c === '`') ops.push({ op: '`', i });
34
+ else if (c === '$' && s[i + 1] === '(') ops.push({ op: '$(', i });
35
+ i++;
36
+ continue;
37
+ }
38
+ if (c === '\\') {
39
+ i += 2;
40
+ continue;
41
+ }
42
+ if (c === "'" || c === '"') {
43
+ quote = c;
44
+ i++;
45
+ continue;
46
+ }
47
+ if (c === '`') {
48
+ ops.push({ op: '`', i });
49
+ i++;
50
+ continue;
51
+ }
52
+ if (c === '$' && s[i + 1] === '(') {
53
+ ops.push({ op: '$(', i });
54
+ i += 2;
55
+ continue;
56
+ }
57
+ if (c === ';' || c === '\n') {
58
+ ops.push({ op: c, i });
59
+ i++;
60
+ continue;
61
+ }
62
+ if (c === '&' || c === '|') {
63
+ if (s[i + 1] === c) {
64
+ ops.push({ op: c + c, i });
65
+ i += 2;
66
+ } else {
67
+ ops.push({ op: c, i });
68
+ i++;
69
+ }
70
+ continue;
71
+ }
72
+ if (c === '>') {
73
+ const rest = s.slice(i + 1);
74
+ const dup = /^&[0-9]/.exec(rest);
75
+ if (dup && /[0-9]/.test(s[i - 1] || '')) {
76
+ ops.push({ op: 'dup', i });
77
+ i += 1 + dup[0].length;
78
+ continue;
79
+ }
80
+ const devnull = /^\s*\/dev\/null(?=\s|$)/.exec(rest);
81
+ if (devnull) {
82
+ ops.push({ op: 'null', i });
83
+ i += 1 + devnull[0].length;
84
+ continue;
85
+ }
86
+ ops.push({ op: '>', i });
87
+ i++;
88
+ continue;
89
+ }
90
+ if (c === '<') {
91
+ ops.push({ op: '<', i });
92
+ i++;
93
+ continue;
94
+ }
95
+ i++;
96
+ }
97
+ return quote ? null : ops;
98
+ }
99
+
100
+ // True when `s` is exactly one shell word: no top-level whitespace, quotes
101
+ // balanced. `"my dir"` and `my\ dir` are one word; `a b` is two.
102
+ function isSingleWord(s) {
103
+ if (!s) return false;
104
+ let quote = null;
105
+ for (let i = 0; i < s.length; i++) {
106
+ const c = s[i];
107
+ if (quote) {
108
+ if (c === '\\' && quote === '"') i++;
109
+ else if (c === quote) quote = null;
110
+ continue;
111
+ }
112
+ if (c === '\\') {
113
+ i++;
114
+ continue;
115
+ }
116
+ if (c === "'" || c === '"') quote = c;
117
+ else if (/\s/.test(c)) return false;
118
+ }
119
+ return !quote;
120
+ }
121
+
122
+ // Split a leading `cd <dir> && rest` / `cd <dir>; rest` into its parts. Agents
123
+ // prefix most commands this way, and a first-word match alone never sees the
124
+ // command that actually produces the output. Returns { dir, op, rest } or null
125
+ // when the command does not start with exactly that shape.
126
+ function splitCdPrefix(command) {
127
+ const s = String(command).trim();
128
+ const m = /^cd[ \t]+/.exec(s);
129
+ if (!m) return null;
130
+ const ops = topLevelOps(s);
131
+ if (!ops || !ops.length) return null;
132
+ const first = ops[0];
133
+ if (first.op !== '&&' && first.op !== ';') return null;
134
+ const dir = s.slice(m[0].length, first.i).trim();
135
+ if (!isSingleWord(dir)) return null;
136
+ const rest = s.slice(first.i + first.op.length).trim();
137
+ if (!rest) return null;
138
+ return { dir, op: first.op, rest };
139
+ }
140
+
141
+ module.exports = { topLevelOps, isSingleWord, splitCdPrefix };