@arthovlabs/liber 0.0.0-stage → 0.5.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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +348 -2
  3. package/bin/liber +706 -0
  4. package/bin/liber-tui +244 -0
  5. package/bin/liber-tui.py +825 -0
  6. package/bin/liberd-entry +17 -0
  7. package/liber.yaml +84 -0
  8. package/package.json +43 -4
  9. package/resources/icons/appIcon.png +0 -0
  10. package/resources/icons/appIcon.svg +20 -0
  11. package/resources/icons/appIcon@512.png +0 -0
  12. package/resources/icons/atom-transparent-256.png +0 -0
  13. package/resources/icons/atom-transparent.png +0 -0
  14. package/resources/icons/atom-transparent.svg +19 -0
  15. package/resources/icons/make-atom.js +168 -0
  16. package/src/cli/ui.js +520 -0
  17. package/src/daemon/core/auth.js +217 -0
  18. package/src/daemon/core/automations.js +130 -0
  19. package/src/daemon/core/budget.js +145 -0
  20. package/src/daemon/core/circuit-breaker.js +31 -0
  21. package/src/daemon/core/config-apply.js +223 -0
  22. package/src/daemon/core/connectors.js +131 -0
  23. package/src/daemon/core/engine.js +1029 -0
  24. package/src/daemon/core/evidence.js +306 -0
  25. package/src/daemon/core/executor.js +10 -0
  26. package/src/daemon/core/grounding.js +420 -0
  27. package/src/daemon/core/injection.js +24 -0
  28. package/src/daemon/core/journal.js +81 -0
  29. package/src/daemon/core/liber-soul.js +157 -0
  30. package/src/daemon/core/lock.js +32 -0
  31. package/src/daemon/core/memory.js +106 -0
  32. package/src/daemon/core/model-switch.js +58 -0
  33. package/src/daemon/core/policy.js +102 -0
  34. package/src/daemon/core/providers.js +503 -0
  35. package/src/daemon/core/registry.js +356 -0
  36. package/src/daemon/core/secrets.js +35 -0
  37. package/src/daemon/core/skills.js +264 -0
  38. package/src/daemon/core/tools/browser-tool.js +280 -0
  39. package/src/daemon/core/tools/file-tools.js +277 -0
  40. package/src/daemon/core/tools/memory-tool.js +127 -0
  41. package/src/daemon/core/tools/skill-tool.js +44 -0
  42. package/src/daemon/core/tools/task-tool.js +41 -0
  43. package/src/daemon/core/tools/terminal-tool.js +449 -0
  44. package/src/daemon/core/tools/todo-tool.js +100 -0
  45. package/src/daemon/core/tools/web-tool.js +181 -0
  46. package/src/daemon/core/trace.js +40 -0
  47. package/src/daemon/core/validate.js +105 -0
  48. package/src/daemon/core/vault.js +158 -0
  49. package/src/daemon/core/verifier.js +98 -0
  50. package/src/daemon/core/voice.js +83 -0
  51. package/src/daemon/core/workspace.js +199 -0
  52. package/src/daemon/liberd.js +1343 -0
  53. package/src/daemon/llm/adapters/anthropic-adapter.js +190 -0
  54. package/src/daemon/llm/adapters/gemini-adapter.js +148 -0
  55. package/src/daemon/llm/adapters/ollama-adapter.js +74 -0
  56. package/src/daemon/llm/adapters/openai-adapter.js +148 -0
  57. package/src/daemon/llm/base.js +31 -0
  58. package/src/daemon/llm/manager.js +134 -0
  59. package/src/utils/config-loader.js +109 -0
  60. package/src/utils/logger.js +56 -0
@@ -0,0 +1,356 @@
1
+ // src/daemon/core/registry.js — Liber Tool Registry & Schema Engine
2
+ const { readFile, writeFile, patchFile, searchFiles } = require('./tools/file-tools');
3
+ const { runTerminal, isCommandSensitive } = require('./tools/terminal-tool');
4
+ const { manageTodo } = require('./tools/todo-tool');
5
+ const { manageMemory } = require('./tools/memory-tool');
6
+ const { fetchUrl, searchWeb } = require('./tools/web-tool');
7
+ const { manageSkill, ACTIONS: SKILL_ACTIONS } = require('./tools/skill-tool');
8
+ const { TASK_TOOLS } = require('./tools/task-tool');
9
+ const { validateArgs } = require('./validate');
10
+
11
+ class ToolRegistry {
12
+ constructor() {
13
+ this.tools = new Map();
14
+ this.registerDefaults();
15
+ }
16
+
17
+ registerDefaults() {
18
+ // 1. read_file
19
+ this.register({
20
+ name: 'read_file',
21
+ description: 'Read the contents of a file with line numbers, offset, and limit.',
22
+ parameters: {
23
+ type: 'object',
24
+ properties: {
25
+ path: { type: 'string', description: 'Relative or absolute file path to read' },
26
+ offset: { type: 'integer', description: 'Starting line number (1-based, default: 1)' },
27
+ limit: { type: 'integer', description: 'Number of lines to read (default: 100)' }
28
+ },
29
+ required: ['path']
30
+ },
31
+ handler: readFile
32
+ });
33
+
34
+ // 2. write_file
35
+ this.register({
36
+ name: 'write_file',
37
+ description: 'Create a new file or completely overwrite an existing file with the provided content.',
38
+ parameters: {
39
+ type: 'object',
40
+ properties: {
41
+ path: { type: 'string', description: 'File path to write to' },
42
+ content: { type: 'string', description: 'Full text content to write' }
43
+ },
44
+ required: ['path', 'content']
45
+ },
46
+ handler: writeFile,
47
+ sensitive: true
48
+ });
49
+
50
+ // 3. patch
51
+ this.register({
52
+ name: 'patch',
53
+ description: 'Surgically replace a unique block of text (old_string) with new_string in a file using exact or fuzzy whitespace matching.',
54
+ parameters: {
55
+ type: 'object',
56
+ properties: {
57
+ path: { type: 'string', description: 'File path to modify' },
58
+ old_string: { type: 'string', description: 'Exact text segment to find and replace' },
59
+ new_string: { type: 'string', description: 'Replacement text segment' },
60
+ replace_all: { type: 'boolean', description: 'Whether to replace all occurrences if multiple exist (default: false)' }
61
+ },
62
+ required: ['path', 'old_string', 'new_string']
63
+ },
64
+ handler: patchFile,
65
+ sensitive: true
66
+ });
67
+
68
+ // 4. search_files
69
+ this.register({
70
+ name: 'search_files',
71
+ description: 'Search for regex/text patterns within file contents or find file paths matching a pattern.',
72
+ parameters: {
73
+ type: 'object',
74
+ properties: {
75
+ pattern: { type: 'string', description: 'Regex or text query to search' },
76
+ path: { type: 'string', description: 'Root directory to start search from (default: .)' },
77
+ target: { type: 'string', enum: ['content', 'files'], description: 'Whether to search file contents or file paths (default: content)' },
78
+ file_glob: { type: 'string', description: 'Optional filename filter (e.g. *.js, *.py)' },
79
+ limit: { type: 'integer', description: 'Maximum matches to return (default: 50)' }
80
+ },
81
+ required: ['pattern']
82
+ },
83
+ handler: searchFiles
84
+ });
85
+
86
+ // 5. terminal
87
+ this.register({
88
+ name: 'terminal',
89
+ description: 'Execute a system command in the host shell (PowerShell on Windows, bash on Linux/macOS).',
90
+ parameters: {
91
+ type: 'object',
92
+ properties: {
93
+ command: { type: 'string', description: 'The exact command line string to run' },
94
+ timeout: { type: 'integer', description: 'Timeout in milliseconds (default: 45000)' }
95
+ },
96
+ required: ['command']
97
+ },
98
+ handler: runTerminal,
99
+ isSensitiveCheck: (args) => isCommandSensitive(args.command)
100
+ });
101
+
102
+ // 6. todo_list
103
+ this.register({
104
+ name: 'todo_list',
105
+ description: 'Maintain the visible plan for this turn. Prefer action "set" with the complete list (one item per step), then flip items to in_progress/completed as you work. The user sees this checklist live.',
106
+ parameters: {
107
+ type: 'object',
108
+ properties: {
109
+ action: { type: 'string', enum: ['set', 'add', 'update', 'complete', 'delete', 'list', 'clear'], description: 'set rewrites the whole plan; add/update/complete/delete act on one id' },
110
+ items: {
111
+ type: 'array',
112
+ description: 'Full plan for action "set": [{ "task": "...", "status": "pending|in_progress|completed" }]',
113
+ items: {
114
+ type: 'object',
115
+ properties: {
116
+ task: { type: 'string', description: 'Short imperative step' },
117
+ status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] }
118
+ },
119
+ required: ['task']
120
+ }
121
+ },
122
+ task: { type: 'string', description: 'Task description (for action add)' },
123
+ id: { type: 'integer', description: 'Task ID (for update/complete/delete)' },
124
+ status: { type: 'string', enum: ['pending', 'in_progress', 'completed'], description: 'New status (for action update)' }
125
+ },
126
+ required: ['action']
127
+ },
128
+ handler: manageTodo
129
+ });
130
+
131
+ // 7. memory
132
+ this.register({
133
+ name: 'memory',
134
+ description: 'Recall, store, list, or forget persistent knowledge across sessions.',
135
+ parameters: {
136
+ type: 'object',
137
+ properties: {
138
+ action: { type: 'string', enum: ['get', 'set', 'list', 'delete'], description: 'Memory action' },
139
+ key: { type: 'string', description: 'Key name to store or recall' },
140
+ value: { type: 'string', description: 'Information to store (for set action)' }
141
+ },
142
+ required: ['action']
143
+ },
144
+ handler: manageMemory
145
+ });
146
+
147
+ // 8. fetch_url — ground external claims in retrieved text
148
+ this.register({
149
+ name: 'fetch_url',
150
+ description: 'Fetch an http(s) URL and return the readable text (HTML stripped). Use to verify external facts instead of guessing.',
151
+ parameters: {
152
+ type: 'object',
153
+ properties: {
154
+ url: { type: 'string', description: 'Absolute http(s) URL to fetch' },
155
+ maxChars: { type: 'integer', description: 'Maximum characters of text to return (default 12000)' }
156
+ },
157
+ required: ['url']
158
+ },
159
+ handler: fetchUrl
160
+ });
161
+
162
+ // 8c. vault — secrets the agent can use without ever printing them
163
+ this.register({
164
+ name: 'vault',
165
+ description: 'Encrypted secret store. list: names and last-4 hints only · set: store a secret · get: read one back (disabled unless the operator allows it) · remove: delete. Prefer storing a key here over pasting it into a command line.',
166
+ parameters: {
167
+ type: 'object',
168
+ properties: {
169
+ action: { type: 'string', enum: ['list', 'set', 'get', 'remove'], description: 'list | set | get | remove' },
170
+ name: { type: 'string', description: 'Secret name, e.g. github.token' },
171
+ value: { type: 'string', description: 'Secret value (action set)' }
172
+ },
173
+ required: ['action']
174
+ },
175
+ handler: async (args) => {
176
+ const vault = require('./vault');
177
+ const action = String(args.action || '').toLowerCase();
178
+ if (action === 'list') return { entries: vault.list(), status: vault.status() };
179
+ if (action === 'set') return vault.set(args.name, args.value);
180
+ if (action === 'remove') return vault.remove(args.name);
181
+ if (action === 'get') {
182
+ // Reading a secret back into the model is an operator decision: a key in
183
+ // the transcript can be exfiltrated by any later prompt injection.
184
+ const allowed = process.env.LIBER_VAULT_AGENT_READ === '1';
185
+ if (!allowed) {
186
+ return { error: 'Reading secrets back is disabled. The operator can enable it with LIBER_VAULT_AGENT_READ=1 or by wiring the value into a connector that uses it server-side.', entries: vault.list() };
187
+ }
188
+ const value = vault.get(args.name);
189
+ return value === null
190
+ ? { error: "No secret named '" + args.name + "'." }
191
+ : { name: args.name, value };
192
+ }
193
+ return { error: "Unknown vault action '" + action + "'." };
194
+ }
195
+ });
196
+
197
+ // 8b. browser — a real Chromium for pages that need JS, clicks or typing
198
+ this.register({
199
+ name: 'browser',
200
+ description: 'Drive a real headless Chromium: open pages, click, type into forms, press keys, read text, take screenshots. Use it when a page needs JavaScript, a login, or interaction — fetch_url only reads static HTML.',
201
+ parameters: {
202
+ type: 'object',
203
+ properties: {
204
+ action: { type: 'string', enum: ['open', 'click', 'type', 'press', 'extract', 'screenshot', 'eval', 'status', 'close'], description: 'open: navigate to url · click: by selector or visible text · type: selector+text · press: key · extract: read text · screenshot: save png · close: shut the browser' },
205
+ url: { type: 'string', description: 'http(s) URL for action open' },
206
+ selector: { type: 'string', description: 'CSS selector or the visible text of the element' },
207
+ text: { type: 'string', description: 'Text to type (action type)' },
208
+ key: { type: 'string', description: 'enter | tab | escape | arrowup | arrowdown' },
209
+ expression: { type: 'string', description: 'JavaScript to evaluate (action eval)' },
210
+ path: { type: 'string', description: 'Where to save a screenshot (optional)' }
211
+ },
212
+ required: ['action']
213
+ },
214
+ handler: async (args) => {
215
+ const browserTool = require('./tools/browser-tool');
216
+ const result = await browserTool.runBrowser(args);
217
+ // Page text is web data: flag instruction-like content before the model sees it.
218
+ try {
219
+ const injection = require('./injection');
220
+ const probe = JSON.stringify(result || {});
221
+ if (injection.scan(probe)) return { ...result, untrusted_warning: injection.WARNING };
222
+ } catch { /* scan is best effort */ }
223
+ return result;
224
+ }
225
+ });
226
+
227
+ // 9. skill — progressive-disclosure procedure library
228
+ this.register({
229
+ name: 'skill',
230
+ description: 'List, search, view, create or update procedural skills. Load a matching skill BEFORE acting instead of improvising a method.',
231
+ parameters: {
232
+ type: 'object',
233
+ properties: {
234
+ action: { type: 'string', enum: SKILL_ACTIONS, description: 'list | view | search | create | update' },
235
+ name: { type: 'string', description: 'Skill name (view/create/update)' },
236
+ query: { type: 'string', description: 'Search text (search)' },
237
+ description: { type: 'string', description: 'One-line "Use when ..." description (create/update)' },
238
+ body: { type: 'string', description: 'Full markdown procedure (create/update)' },
239
+ triggers: { type: 'array', description: 'Keywords that auto-select this skill' },
240
+ always: { type: 'boolean', description: 'Inject the body every turn (use sparingly)' },
241
+ overwrite: { type: 'boolean', description: 'Allow replacing an existing skill' }
242
+ },
243
+ required: ['action']
244
+ },
245
+ handler: manageSkill,
246
+ isSensitiveCheck: (args) => ['create', 'update'].includes(String(args.action || '').toLowerCase())
247
+ });
248
+
249
+ // 10. task / tasks — subagent orchestration (executed by the engine)
250
+ for (const def of TASK_TOOLS) this.register(def);
251
+
252
+ // 11. web_search — keyless search; verify important facts with fetch_url
253
+ this.register({
254
+ name: 'web_search',
255
+ description: 'Search the web and return titles, URLs and snippets. Treat results as pointers; verify any important fact by fetching the primary source with fetch_url and citing the receipt.',
256
+ parameters: {
257
+ type: 'object',
258
+ properties: {
259
+ query: { type: 'string', description: 'Search query' },
260
+ max: { type: 'integer', description: 'Maximum results (default 8, max 10)' }
261
+ },
262
+ required: ['query']
263
+ },
264
+ handler: searchWeb
265
+ });
266
+ }
267
+
268
+ register(def) {
269
+ this.tools.set(def.name, def);
270
+ }
271
+
272
+ get(name) {
273
+ if (name === 'shell_execute' || name === 'exec') return this.tools.get('terminal');
274
+ return this.tools.get(name);
275
+ }
276
+
277
+ isSensitive(name, args = {}) {
278
+ const tool = this.get(name);
279
+ if (!tool) return false;
280
+ if (typeof tool.isSensitiveCheck === 'function') {
281
+ return tool.isSensitiveCheck(args);
282
+ }
283
+ return !!tool.sensitive;
284
+ }
285
+
286
+ /**
287
+ * Schema-lite validation. A tool must never execute on malformed or hallucinated arguments.
288
+ */
289
+ validate(name, args = {}) {
290
+ const tool = this.get(name);
291
+ if (!tool) {
292
+ return {
293
+ ok: false,
294
+ errors: [`Tool '${name}' is not registered. Available: ${Array.from(this.tools.keys()).join(', ')}.`],
295
+ problems: [{ field: 'tool', issue: 'unknown_tool' }],
296
+ schema: null
297
+ };
298
+ }
299
+ const result = validateArgs(tool.parameters, args);
300
+ return { ...result, schema: { required: tool.parameters?.required || [], properties: Object.keys(tool.parameters?.properties || {}) } };
301
+ }
302
+
303
+ async execute(name, args = {}, meta = {}) {
304
+ const tool = this.get(name);
305
+ if (!tool) {
306
+ return {
307
+ error: `Tool '${name}' is not registered. Available: ${Array.from(this.tools.keys()).join(', ')}.`,
308
+ validation_failed: true
309
+ };
310
+ }
311
+
312
+ const validation = this.validate(name, args);
313
+ if (!validation.ok) {
314
+ return {
315
+ error: `Invalid arguments for '${name}': ${validation.errors.join(' ')}`,
316
+ validation_failed: true,
317
+ problems: validation.problems,
318
+ schema: validation.schema
319
+ };
320
+ }
321
+
322
+ try {
323
+ return await tool.handler(args, meta);
324
+ } catch (err) {
325
+ return { error: `Tool '${name}' failed: ${err.message}` };
326
+ }
327
+ }
328
+
329
+ getOpenAITools() {
330
+ const list = [];
331
+ for (const [name, def] of this.tools.entries()) {
332
+ list.push({
333
+ type: 'function',
334
+ function: {
335
+ name,
336
+ description: def.description,
337
+ parameters: def.parameters
338
+ }
339
+ });
340
+ }
341
+ return list;
342
+ }
343
+
344
+ getToolDescription() {
345
+ const list = [];
346
+ for (const [name, def] of this.tools.entries()) {
347
+ const params = Object.entries(def.parameters.properties || {})
348
+ .map(([p, info]) => `${p}: ${info.type} (${info.description})`)
349
+ .join(', ');
350
+ list.push(`- ${name}(${params}): ${def.description}`);
351
+ }
352
+ return list.join('\n');
353
+ }
354
+ }
355
+
356
+ module.exports = new ToolRegistry();
@@ -0,0 +1,35 @@
1
+ // src/daemon/core/secrets.js — detect and redact credential-like text before
2
+ // anything durable (session, journal, traces) hits disk.
3
+ const PATTERNS = [
4
+ { type: 'openai_key', re: /\bsk-[A-Za-z0-9_-]{20,}\b/g },
5
+ { type: 'github_token', re: /\bgh[psuo]_[A-Za-z0-9]{30,}\b/g },
6
+ { type: 'github_pat', re: /\bgithub_pat_[A-Za-z0-9_]{40,}\b/g },
7
+ { type: 'aws_key', re: /\bAKIA[0-9A-Z]{16}\b/g },
8
+ { type: 'private_key', re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]{0,400}?-----END [A-Z0-9 ]*PRIVATE KEY-----/g },
9
+ { type: 'bearer', re: /\bBearer\s+[A-Za-z0-9._-]{24,}\b/g },
10
+ { type: 'assigned_secret', re: /\b(?:password|passwd|secret|token|api_key|apikey)\s*[:=]\s*[^\s"',;{}]{8,}\b/gi }
11
+ ];
12
+
13
+ function find(text) {
14
+ const source = String(text || '');
15
+ const hits = [];
16
+ for (const { type, re } of PATTERNS) {
17
+ re.lastIndex = 0;
18
+ let m;
19
+ while ((m = re.exec(source)) !== null) {
20
+ hits.push({ type, snippet: m[0].slice(0, 24) + '…' });
21
+ }
22
+ }
23
+ return hits;
24
+ }
25
+
26
+ function redact(text) {
27
+ let out = String(text || '');
28
+ for (const { type, re } of PATTERNS) {
29
+ re.lastIndex = 0;
30
+ out = out.replace(re, `[REDACTED:${type}]`);
31
+ }
32
+ return out;
33
+ }
34
+
35
+ module.exports = { find, redact, PATTERNS };
@@ -0,0 +1,264 @@
1
+ // src/daemon/core/skills.js — progressive-disclosure skill library.
2
+ // The index is cheap and always injected; bodies are loaded on demand by the model
3
+ // (skill tool) or auto-selected by trigger match. Project skills override global ones.
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const yaml = require('js-yaml');
7
+
8
+ const GLOBAL_DIR = path.resolve(__dirname, '..', '..', '..', 'skills');
9
+ const PROJECT_DIR = () => path.resolve(process.cwd(), '.liber', 'skills');
10
+ const NAME_RE = /^[a-z0-9][a-z0-9-]{1,63}$/;
11
+ const BODY_CAP = 9000;
12
+
13
+ let cache = null;
14
+
15
+ function parseSkillFile(file, source) {
16
+ let raw;
17
+ try {
18
+ raw = fs.readFileSync(file, 'utf8');
19
+ } catch {
20
+ return null;
21
+ }
22
+ const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
23
+ if (!m) return null;
24
+
25
+ let meta;
26
+ try {
27
+ meta = yaml.load(m[1]) || {};
28
+ } catch {
29
+ return null;
30
+ }
31
+ if (!meta || typeof meta !== 'object') return null;
32
+
33
+ const dir = path.dirname(file);
34
+ const name = String(meta.name || path.basename(dir));
35
+ if (!NAME_RE.test(name)) return null;
36
+
37
+ const triggers = Array.isArray(meta.triggers)
38
+ ? meta.triggers.map(t => String(t)).filter(Boolean).slice(0, 16)
39
+ : [];
40
+
41
+ return {
42
+ name,
43
+ description: String(meta.description || '').replace(/\s+/g, ' ').trim().slice(0, 400),
44
+ always: meta.always === true,
45
+ triggers,
46
+ body: m[2].trim(),
47
+ dir,
48
+ file,
49
+ source,
50
+ files: listAttachments(dir)
51
+ };
52
+ }
53
+
54
+ function listAttachments(dir) {
55
+ const out = [];
56
+ for (const sub of ['references', 'scripts', 'templates', 'assets']) {
57
+ const p = path.join(dir, sub);
58
+ if (!fs.existsSync(p)) continue;
59
+ for (const f of fs.readdirSync(p)) {
60
+ out.push(`${sub}/${f}`);
61
+ }
62
+ }
63
+ return out.sort();
64
+ }
65
+
66
+ function walk(dir, source, depth = 0, found = new Map()) {
67
+ if (depth > 2 || !fs.existsSync(dir)) return found;
68
+ let entries;
69
+ try {
70
+ entries = fs.readdirSync(dir, { withFileTypes: true });
71
+ } catch {
72
+ return found;
73
+ }
74
+ for (const entry of entries) {
75
+ const full = path.join(dir, entry.name);
76
+ if (entry.isDirectory()) {
77
+ walk(full, source, depth + 1, found);
78
+ } else if (entry.isFile() && entry.name === 'SKILL.md') {
79
+ const skill = parseSkillFile(full, source);
80
+ if (skill) found.set(skill.name, skill);
81
+ }
82
+ }
83
+ return found;
84
+ }
85
+
86
+ function scan(force = false) {
87
+ if (cache && !force) return cache;
88
+ const found = new Map();
89
+ walk(GLOBAL_DIR, 'global', 0, found);
90
+ // Project skills load second so they override same-named global skills.
91
+ walk(PROJECT_DIR(), 'project', 0, found);
92
+ cache = Array.from(found.values()).sort((a, b) => {
93
+ if (a.always !== b.always) return a.always ? -1 : 1;
94
+ return a.name.localeCompare(b.name);
95
+ });
96
+ return cache;
97
+ }
98
+
99
+ function reload() {
100
+ cache = null;
101
+ return scan(true);
102
+ }
103
+
104
+ function get(name) {
105
+ const target = String(name || '').toLowerCase();
106
+ return scan().find(s => s.name === target) || null;
107
+ }
108
+
109
+ function indexLines() {
110
+ return scan()
111
+ .map(s => `- ${s.name}${s.always ? ' (always)' : ''} — ${s.description}`)
112
+ .join('\n');
113
+ }
114
+
115
+ function intentMatches(skill, intentText) {
116
+ if (!intentText) return false;
117
+ const text = String(intentText);
118
+ return skill.triggers.some(t => {
119
+ try {
120
+ return new RegExp(t, 'i').test(text);
121
+ } catch {
122
+ return text.toLowerCase().includes(t.toLowerCase());
123
+ }
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Build the per-turn skill context: cheap index + always-on bodies + trigger-matched bodies.
129
+ */
130
+ function buildContext(intentText = '', budgetChars = 7000) {
131
+ const skills = scan();
132
+ const index = `=== SKILLS INDEX (load a body with [TOOL: skill({"action":"view","name":"..."})]) ===\n${indexLines()}\n`;
133
+
134
+ let text = index;
135
+ const used = [];
136
+
137
+ const addBody = (skill, label) => {
138
+ const block = `\n### ${skill.name} ${label}\n${skill.body}\n`;
139
+ if (text.length + block.length > budgetChars) return false;
140
+ text += block;
141
+ used.push(skill.name);
142
+ return true;
143
+ };
144
+
145
+ for (const s of skills.filter(x => x.always)) addBody(s, '(core procedure)');
146
+ for (const s of skills.filter(x => !x.always)) {
147
+ if (intentMatches(s, intentText)) addBody(s, '(auto-selected for this request)');
148
+ }
149
+
150
+ return { text, used, chars: text.length, total: skills.length };
151
+ }
152
+
153
+ function view(name, cap = BODY_CAP) {
154
+ const skill = get(name);
155
+ if (!skill) {
156
+ return {
157
+ error: `Skill '${name}' not found. Available: ${scan().map(s => s.name).join(', ')}.`
158
+ };
159
+ }
160
+ return {
161
+ name: skill.name,
162
+ description: skill.description,
163
+ always: skill.always,
164
+ triggers: skill.triggers,
165
+ source: skill.source,
166
+ files: skill.files,
167
+ body: skill.body.length > cap ? skill.body.slice(0, cap) + `\n... [TRUNCATED at ${cap} chars]` : skill.body
168
+ };
169
+ }
170
+
171
+ function search(query, limit = 5) {
172
+ const q = String(query || '').toLowerCase().trim();
173
+ if (!q) return { error: 'Missing search query.' };
174
+ const hits = [];
175
+ for (const s of scan()) {
176
+ const haystack = `${s.name} ${s.description} ${s.body}`.toLowerCase();
177
+ let score = 0;
178
+ if (s.name.includes(q)) score += 5;
179
+ if (s.description.toLowerCase().includes(q)) score += 3;
180
+ const occurrences = haystack.split(q).length - 1;
181
+ score += Math.min(occurrences, 5);
182
+ if (score > 0) {
183
+ const idx = s.body.toLowerCase().indexOf(q);
184
+ hits.push({
185
+ name: s.name,
186
+ description: s.description,
187
+ score,
188
+ snippet: idx >= 0 ? s.body.slice(Math.max(0, idx - 60), idx + 120).replace(/\s+/g, ' ') : ''
189
+ });
190
+ }
191
+ }
192
+ hits.sort((a, b) => b.score - a.score);
193
+ return { query, total: hits.length, matches: hits.slice(0, Math.min(limit, 10)) };
194
+ }
195
+
196
+ function validate({ name, description, body }) {
197
+ const errors = [];
198
+ if (!NAME_RE.test(String(name || ''))) {
199
+ errors.push('name must be lowercase letters, digits or hyphens (2–64 chars).');
200
+ }
201
+ const desc = String(description || '').trim();
202
+ if (desc.length < 20) errors.push('description must be at least 20 chars and start with "Use when ...".');
203
+ if (desc.length > 400) errors.push('description must be ≤ 400 chars.');
204
+ const text = String(body || '').trim();
205
+ if (text.length < 60) errors.push('body must be at least 60 chars.');
206
+ if (text.length > 20000) errors.push('body must be ≤ 20000 chars.');
207
+ return errors;
208
+ }
209
+
210
+ /**
211
+ * Create or update a skill in the project-level library (.liber/skills).
212
+ * Package-level skills are never modified at runtime.
213
+ */
214
+ function writeSkill({ name, description, body, triggers = [], always = false }, overwrite = false) {
215
+ const errors = validate({ name, description, body });
216
+ if (errors.length) return { error: errors.join(' '), validation_failed: true };
217
+
218
+ const dir = path.join(PROJECT_DIR(), String(name).toLowerCase());
219
+ const file = path.join(dir, 'SKILL.md');
220
+ if (fs.existsSync(file) && !overwrite) {
221
+ return { error: `Skill '${name}' already exists at ${file}. Use action 'update' to replace it.` };
222
+ }
223
+
224
+ const trig = Array.isArray(triggers)
225
+ ? triggers.map(t => String(t).trim()).filter(Boolean).slice(0, 16)
226
+ : [];
227
+
228
+ const frontmatter = yaml.dump(
229
+ {
230
+ name: String(name).toLowerCase(),
231
+ description: String(description).trim(),
232
+ always: always === true,
233
+ triggers: trig
234
+ },
235
+ { lineWidth: 120 }
236
+ );
237
+
238
+ const content = `---\n${frontmatter}---\n\n# ${String(name).toLowerCase()}\n\n${String(body).trim()}\n`;
239
+ fs.mkdirSync(dir, { recursive: true });
240
+ fs.writeFileSync(file, content, 'utf8');
241
+ reload();
242
+
243
+ return {
244
+ success: true,
245
+ name: String(name).toLowerCase(),
246
+ path: path.relative(process.cwd(), file) || file,
247
+ action: overwrite ? 'updated' : 'created',
248
+ bytes_written: Buffer.byteLength(content, 'utf8')
249
+ };
250
+ }
251
+
252
+ module.exports = {
253
+ GLOBAL_DIR,
254
+ PROJECT_DIR,
255
+ scan,
256
+ reload,
257
+ get,
258
+ view,
259
+ search,
260
+ buildContext,
261
+ writeSkill,
262
+ indexLines,
263
+ listAttachments
264
+ };