@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,1343 @@
1
+ // src/daemon/liberd.js
2
+ const http = require('http');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const llmManager = require('./llm/manager');
6
+ const ConfigLoader = require('../utils/config-loader');
7
+ const liberEngine = require('./core/engine');
8
+ const memory = require('./core/memory');
9
+ const registry = require('./core/registry');
10
+ const circuitBreaker = require('./core/circuit-breaker');
11
+ const trace = require('./core/trace');
12
+ const auth = require('./core/auth');
13
+ const policy = require('./core/policy');
14
+ const journal = require('./core/journal');
15
+ const modelSwitch = require('./core/model-switch');
16
+ const configApply = require('./core/config-apply');
17
+ const workspace = require('./core/workspace');
18
+ const skills = require('./core/skills');
19
+ const providers = require('./core/providers');
20
+ const budget = require('./core/budget');
21
+ const memoryBank = require('./core/tools/memory-tool');
22
+ const automations = require('./core/automations');
23
+ const vault = require('./core/vault');
24
+ const voice = require('./core/voice');
25
+ const connectors = require('./core/connectors');
26
+ const { AgentQueue } = require('./core/lock');
27
+ const logger = require('../utils/logger');
28
+
29
+ class LiberDaemon {
30
+ constructor() {
31
+ this.agents = new Map();
32
+ this.port = 4567;
33
+ this.server = null;
34
+ this.hitlPending = null; // { resolve, agentId, command }
35
+ this.queue = new AgentQueue(); // one turn at a time per agent
36
+ }
37
+
38
+ resolveHitl(approved) {
39
+ if (this.hitlPending) {
40
+ this.hitlPending.resolve(approved);
41
+ this.hitlPending = null;
42
+ return true;
43
+ }
44
+ return false;
45
+ }
46
+
47
+ waitForHitl(agentId, command, timeoutMs = 60000) {
48
+ return new Promise((resolve) => {
49
+ this.hitlPending = { resolve, agentId, command };
50
+ setTimeout(() => {
51
+ if (this.hitlPending && this.hitlPending.command === command) {
52
+ this.hitlPending = null;
53
+ resolve(false); // timeout defaults to deny
54
+ }
55
+ }, timeoutMs);
56
+ });
57
+ }
58
+
59
+ async fetchAvailableModels(engine) {
60
+ if (!engine || !engine.endpoint || !engine.apiKey) return [];
61
+ try {
62
+ const url = `${engine.endpoint}/models`;
63
+ const res = await fetch(url, {
64
+ headers: { 'Authorization': `Bearer ${engine.apiKey}` }
65
+ });
66
+ if (!res.ok) return [];
67
+ const data = await res.json();
68
+ if (Array.isArray(data.data)) {
69
+ return data.data.map(m => m.id);
70
+ }
71
+ if (Array.isArray(data.models)) {
72
+ return data.models.map(m => m.name || m.id);
73
+ }
74
+ return [];
75
+ } catch {
76
+ return [];
77
+ }
78
+ }
79
+
80
+ persistConfigChanges(changes) {
81
+ try {
82
+ const cfgPath = path.resolve(process.cwd(), process.env.LIBER_CONFIG || 'liber.yaml');
83
+ if (fs.existsSync(cfgPath)) {
84
+ const raw = fs.readFileSync(cfgPath, 'utf8');
85
+ // engine.* lives under the agent: section in liber.yaml.
86
+ const yamlChanges = {};
87
+ for (const [key, value] of Object.entries(changes)) {
88
+ yamlChanges[key.startsWith('engine.') ? `agent.${key}` : key] = value;
89
+ }
90
+ const patched = configApply.patchYamlKeys(raw, yamlChanges);
91
+ if (patched !== raw) {
92
+ const tmp = `${cfgPath}.tmp`;
93
+ fs.writeFileSync(tmp, patched, 'utf8');
94
+ fs.renameSync(tmp, cfgPath);
95
+ }
96
+ }
97
+ } catch (e) {
98
+ logger.error('SYSTEM', 'CONFIG_PERSIST_FAILED', { error: e.message });
99
+ }
100
+ }
101
+
102
+ /**
103
+ * One timer for the whole daemon: every 30s, run whatever is due. A job that is
104
+ * already running is skipped, and markRun() records the run so the next tick
105
+ * cannot fire it twice.
106
+ */
107
+ startAutomations() {
108
+ if (this._autoTimer || process.env.LIBER_AUTOMATIONS === 'off') return;
109
+ this._autoRunning = this._autoRunning || new Set();
110
+ this._autoTimer = setInterval(() => { this.tickAutomations().catch(() => {}); }, 30_000);
111
+ if (this._autoTimer.unref) this._autoTimer.unref();
112
+ logger.info('SYSTEM', 'AUTOMATIONS_ARMED', { jobs: automations.list().length });
113
+ }
114
+
115
+ async tickAutomations() {
116
+ const agentId = Array.from(this.agents.keys())[0];
117
+ if (!agentId) return;
118
+ const agent = this.agents.get(agentId);
119
+ if (agent?.status === 'RUNNING' && this.queue?.busy?.()) { /* a manual turn owns the queue */ }
120
+ for (const job of automations.list()) {
121
+ if (!job.due) continue;
122
+ if (this._autoRunning.has(job.id)) continue;
123
+ this._autoRunning.add(job.id);
124
+ try {
125
+ logger.info('SYSTEM', 'AUTOMATION_FIRE', { id: job.id, name: job.name });
126
+ const result = await this.queue.run(agentId, () => liberEngine.runTurn({
127
+ agentId,
128
+ memoryKey: `${agentId}#auto:${job.id}`,
129
+ agentConfig: agent.config,
130
+ userMessage: job.prompt,
131
+ memory, llmManager,
132
+ onEvent: () => {},
133
+ maxLoops: this.maxLoops,
134
+ waitForHitl: async () => false
135
+ }));
136
+ automations.markRun(job.id, {
137
+ ok: result?.success !== false,
138
+ chars: String(result?.response || '').length,
139
+ excerpt: result?.response,
140
+ error: result?.success === false ? result.error : null
141
+ });
142
+ logger.info('SYSTEM', 'AUTOMATION_DONE', { id: job.id, ok: result?.success !== false });
143
+ } catch (err) {
144
+ automations.markRun(job.id, { ok: false, error: err.message });
145
+ logger.warn('SYSTEM', 'AUTOMATION_FAILED', { id: job.id, error: err.message });
146
+ } finally {
147
+ this._autoRunning.delete(job.id);
148
+ }
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Turn every declared HTTP connector into a tool. Called at boot and on
154
+ * /connectors/reload, so editing connectors.json does not need a restart.
155
+ */
156
+ installConnectors() {
157
+ try {
158
+ const registry = require('./core/registry');
159
+ const out = connectors.install(registry);
160
+ this._connectors = out.installed;
161
+ logger.info('SYSTEM', 'CONNECTORS_INSTALLED', { tools: out.installed, problems: out.problems.length });
162
+ return out;
163
+ } catch (e) {
164
+ logger.warn('SYSTEM', 'CONNECTORS_FAILED', { error: e.message });
165
+ return { installed: [], problems: [e.message] };
166
+ }
167
+ }
168
+
169
+ /** Facts a fresh session should not have to discover again. */
170
+ seedStandingFacts(config) {
171
+ try {
172
+ const facts = {
173
+ 'workspace.root': process.cwd(),
174
+ 'workspace.os': `${process.platform} ${process.arch}`,
175
+ 'workspace.user': (() => { try { return require('os').userInfo().username; } catch { return null; } })(),
176
+ 'engine.provider': config?.agent?.engine?.provider,
177
+ 'engine.model': config?.agent?.engine?.model
178
+ };
179
+ try {
180
+ const { execFileSync } = require('child_process');
181
+ const remote = execFileSync('git', ['remote', 'get-url', 'origin'], { cwd: process.cwd(), encoding: 'utf8', timeout: 3000, windowsHide: true }).trim();
182
+ if (remote) facts['workspace.remote'] = remote;
183
+ } catch { /* not a git repo: fine */ }
184
+ const added = memoryBank.memorySeed(facts);
185
+ if (added) logger.info('SYSTEM', 'MEMORY_SEEDED', { added });
186
+ } catch (err) {
187
+ logger.warn('SYSTEM', 'MEMORY_SEED_FAILED', { error: err.message });
188
+ }
189
+ }
190
+
191
+ async start(configPath = process.env.LIBER_CONFIG || 'liber.yaml') {
192
+ console.log(`[liberd] Starting Liber Production-Grade Daemon...`);
193
+ try {
194
+ const config = ConfigLoader.load(configPath);
195
+ llmManager.initialize(config.agent.engine);
196
+ policy.configure(config.policy || {});
197
+ this.token = auth.ensureToken();
198
+
199
+ this.maxLoops = config.limits?.circuit_breaker?.max_loops || 12;
200
+ if (config.memory?.persist !== false) {
201
+ memory.attach(config.memory?.path || '.liber/session.json', config.memory?.window_size);
202
+ }
203
+ this.traceEnabled = config.telemetry?.trace !== false;
204
+
205
+ const agentId = config.agent.name || 'default-agent';
206
+ this.agents.set(agentId, {
207
+ config: {
208
+ ...config.agent,
209
+ grounding: config.grounding || {},
210
+ skills: config.skills || {},
211
+ limits: config.limits || {},
212
+ memory: config.memory || {}
213
+ },
214
+ status: 'RUNNING',
215
+ startTime: Date.now(),
216
+ metrics: { tokens: 0, requests: 0 }
217
+ });
218
+
219
+ this.seedStandingFacts(config);
220
+ // Plaintext provider keys move into the encrypted vault on first boot.
221
+ try {
222
+ const mv = vault.migrateCredentials();
223
+ if (mv.moved?.length) logger.info('SYSTEM', 'VAULT_MIGRATED_KEYS', { count: mv.moved.length });
224
+ } catch (e) { logger.warn('SYSTEM', 'VAULT_MIGRATION_FAILED', { error: e.message }); }
225
+ this.startAutomations();
226
+ this.installConnectors();
227
+ // Adopt .liber/daemon.token as the local admin client on first boot.
228
+ try { auth.bootstrap(); } catch (e) { logger.warn('SYSTEM', 'AUTH_BOOTSTRAP_FAILED', { error: e.message }); }
229
+ this.server = http.createServer((req, res) => this.handleRequest(req, res));
230
+ // Bind to loopback by default: the daemon has no auth, so exposing it on the LAN
231
+ // would let any device spend the API key or call /shutdown. Override deliberately
232
+ // with LIBER_HOST only behind a trusted proxy.
233
+ const host = process.env.LIBER_HOST || '127.0.0.1';
234
+ // A workspace switch respawns the daemon; the old socket can outlive the old
235
+ // process for a moment, so retry the bind instead of crashing on EADDRINUSE.
236
+ let bindAttempt = 0;
237
+ const bind = () => {
238
+ this.server.listen(this.port, host, () => {
239
+ logger.info('SYSTEM', 'DAEMON_START', { port: this.port, host, cwd: process.cwd() });
240
+ });
241
+ };
242
+ this.server.on('error', (err) => {
243
+ if (err.code === 'EADDRINUSE' && bindAttempt < 20) {
244
+ bindAttempt++;
245
+ setTimeout(bind, 300);
246
+ return;
247
+ }
248
+ logger.error('SYSTEM', 'BIND_FAILED', { error: err.message });
249
+ process.exit(1);
250
+ });
251
+ bind();
252
+ } catch (err) {
253
+ logger.error('SYSTEM', 'BOOT_FAILED', { error: err.message });
254
+ process.exit(1);
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Public view of an agent. Never exposes credentials or raw config.
260
+ */
261
+ sanitizeAgent(id, data) {
262
+ const engine = data.config?.engine || {};
263
+ return {
264
+ id,
265
+ status: data.status,
266
+ startTime: data.startTime,
267
+ metrics: data.metrics,
268
+ name: data.config?.name || id,
269
+ version: data.config?.version || null,
270
+ model: engine.model || null,
271
+ provider: engine.provider || null,
272
+ grounding: data.config?.grounding?.enabled !== false
273
+ };
274
+ }
275
+
276
+ /**
277
+ * Apply one dotted config path to a live agent config, with the side effects
278
+ * each subsystem needs. Handles nested keys (limits.circuit_breaker.max_loops).
279
+ */
280
+ applyConfigPath(agent, dottedPath, value) {
281
+ const cfg = agent.config;
282
+ const [top, ...rest] = dottedPath.split('.');
283
+ const setDeep = (obj, keys, val) => {
284
+ let cur = obj;
285
+ for (let i = 0; i < keys.length - 1; i++) {
286
+ if (typeof cur[keys[i]] !== 'object' || cur[keys[i]] === null) cur[keys[i]] = {};
287
+ cur = cur[keys[i]];
288
+ }
289
+ cur[keys[keys.length - 1]] = val;
290
+ };
291
+
292
+ if (top === 'engine') setDeep(cfg, ['engine', ...rest], value);
293
+ else if (top === 'grounding') setDeep(cfg, ['grounding', ...rest], value);
294
+ else if (top === 'limits') {
295
+ setDeep(cfg, ['limits', ...rest], value);
296
+ if (rest[0] === 'circuit_breaker' && rest[1] === 'max_loops') this.maxLoops = value;
297
+ }
298
+ else if (top === 'memory') {
299
+ setDeep(cfg, ['memory', ...rest], value);
300
+ if (rest[0] === 'window_size') memory.resize(value);
301
+ }
302
+ else if (top === 'telemetry') {
303
+ setDeep(cfg, ['telemetry', ...rest], value);
304
+ if (rest[0] === 'trace') this.traceEnabled = !!value;
305
+ }
306
+ else if (top === 'policy') {
307
+ const pol = policy.current();
308
+ const terminal = { ...pol.terminal };
309
+ if (rest[0] === 'terminal') terminal[rest[1]] = value;
310
+ policy.configure({
311
+ write_roots: rest[0] === 'write_roots' ? value : pol.write_roots,
312
+ allow_outside_workspace: pol.allow_outside_workspace,
313
+ terminal
314
+ });
315
+ }
316
+ }
317
+
318
+ async handleRequest(req, res) {
319
+ const url = new URL(req.url, `http://${req.headers.host}`);
320
+ const endpoint = url.pathname;
321
+ res.setHeader('Content-Type', 'application/json');
322
+
323
+ // CORS for the desktop shell (Neutralino/WebView2 origin) and any local client.
324
+ // The daemon binds to loopback and every stateful endpoint still requires the
325
+ // bearer token, so a wildcard origin does not weaken access control.
326
+ res.setHeader('Access-Control-Allow-Origin', '*');
327
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
328
+ res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
329
+ if (req.method === 'OPTIONS') {
330
+ res.statusCode = 204;
331
+ res.end();
332
+ return;
333
+ }
334
+
335
+ // Unauthenticated liveness probe only — it exposes no state.
336
+ if (endpoint === '/healthz') {
337
+ res.end(JSON.stringify({ ok: true }));
338
+ return;
339
+ }
340
+
341
+ // Unauthenticated bootstrap info for local shells: the daemon's cwd and where
342
+ // its token FILE lives (the path only — the token itself is never served).
343
+ if (endpoint === '/whoami') {
344
+ let version = '0.0.0';
345
+ try { version = require('../../package.json').version || version; } catch { /* best effort */ }
346
+ res.end(JSON.stringify({
347
+ app: 'liber',
348
+ version,
349
+ cwd: process.cwd(),
350
+ token_path: path.join(process.cwd(), '.liber', 'daemon.token'),
351
+ platform: process.platform,
352
+ arch: process.arch,
353
+ cpus: (require('os').cpus() || []).length,
354
+ user: (() => { try { return require('os').userInfo().username; } catch { return null; } })()
355
+ }));
356
+ return;
357
+ }
358
+
359
+ // Every request is resolved to a client, then checked for scope and rate.
360
+ const requestStart = Date.now();
361
+ const client = auth.verify(auth.extract(req));
362
+ if (!client) {
363
+ res.statusCode = 401;
364
+ res.end(JSON.stringify({
365
+ success: false,
366
+ error: 'Unauthorized. Send Authorization: Bearer <token>. The desktop token lives in .liber/daemon.token; other clients get their own from /clients (scope admin).'
367
+ }));
368
+ logger.warn('SYSTEM', 'AUTH_FAILED', { endpoint, ip: req.socket.remoteAddress });
369
+ auth.audit({ client: null, ip: req.socket.remoteAddress, method: req.method, endpoint, decision: 'deny', reason: 'bad token' });
370
+ return;
371
+ }
372
+ const needed = auth.scopeFor(req.method, endpoint);
373
+ if (!auth.can(client, needed)) {
374
+ res.statusCode = 403;
375
+ res.end(JSON.stringify({
376
+ success: false,
377
+ error: `Client '${client.id}' lacks the '${needed}' scope for ${req.method} ${endpoint}.`,
378
+ scopes: client.scopes,
379
+ required: needed
380
+ }));
381
+ auth.audit({ client: client.id, method: req.method, endpoint, decision: 'deny', reason: 'scope ' + needed });
382
+ return;
383
+ }
384
+ const limited = auth.rateLimit(client);
385
+ if (!limited.allowed) {
386
+ res.statusCode = 429;
387
+ res.setHeader('retry-after', Math.ceil(limited.retryAfterMs / 1000));
388
+ res.end(JSON.stringify({
389
+ success: false,
390
+ error: `Rate limit reached for '${client.id}' (${limited.limit}/min). Retry in ${Math.ceil(limited.retryAfterMs / 1000)}s.`,
391
+ retry_after_ms: limited.retryAfterMs
392
+ }));
393
+ auth.audit({ client: client.id, method: req.method, endpoint, decision: 'deny', reason: 'rate limit' });
394
+ return;
395
+ }
396
+ auth.touch(client);
397
+ res.on('finish', () => auth.audit({
398
+ client: client.id,
399
+ method: req.method,
400
+ endpoint,
401
+ status: res.statusCode,
402
+ scope: needed,
403
+ ms: Date.now() - requestStart
404
+ }));
405
+
406
+ try {
407
+ if (endpoint === '/clients' || endpoint === '/clients/rotate' || endpoint === '/clients/audit') {
408
+ if (endpoint === '/clients' && req.method === 'GET') {
409
+ res.end(JSON.stringify({ success: true, clients: auth.list(), scopes: auth.SCOPES }));
410
+ return;
411
+ }
412
+ if (endpoint === '/clients' && req.method === 'POST') {
413
+ let b = ''; for await (const ch of req) b += ch;
414
+ const body = JSON.parse(b || '{}');
415
+ const out = auth.create(body.label, { scopes: body.scopes, perMin: body.perMin });
416
+ // The token is in this response and nowhere else, ever.
417
+ res.statusCode = out.ok ? 200 : 400;
418
+ res.end(JSON.stringify({ success: out.ok, ...out, clients: auth.list() }));
419
+ return;
420
+ }
421
+ if (endpoint === '/clients' && req.method === 'DELETE') {
422
+ const out = auth.revoke(String(url.searchParams.get('id') || ''));
423
+ res.statusCode = out.ok ? 200 : 400;
424
+ res.end(JSON.stringify({ success: out.ok, ...out, clients: auth.list() }));
425
+ return;
426
+ }
427
+ if (endpoint === '/clients/rotate') {
428
+ let b = ''; for await (const ch of req) b += ch;
429
+ const body = JSON.parse(b || '{}');
430
+ const out = auth.rotate(String(body.id || ''));
431
+ res.statusCode = out.ok ? 200 : 400;
432
+ res.end(JSON.stringify({ success: out.ok, ...out, clients: auth.list() }));
433
+ return;
434
+ }
435
+ if (endpoint === '/clients/audit') {
436
+ let lines = [];
437
+ try {
438
+ lines = require('fs').readFileSync(path.join(process.cwd(), '.liber', 'auth-audit.log'), 'utf8')
439
+ .trim().split('\n').filter(Boolean).slice(-Number(url.searchParams.get('tail') || 40))
440
+ .map(l => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
441
+ } catch { }
442
+ res.end(JSON.stringify({ success: true, entries: lines }));
443
+ return;
444
+ }
445
+ res.statusCode = 405;
446
+ res.end(JSON.stringify({ success: false, error: 'Method not allowed.' }));
447
+ return;
448
+ }
449
+ if (endpoint === '/ps') {
450
+ const status = Array.from(this.agents.entries()).map(([id, data]) => this.sanitizeAgent(id, data));
451
+ res.end(JSON.stringify({ success: true, data: status }));
452
+ }
453
+ else if (endpoint === '/shutdown') {
454
+ res.end(JSON.stringify({ success: true }));
455
+ setTimeout(() => { this.stop(); process.exit(0); }, 100);
456
+ }
457
+ else if (endpoint === '/session/clear') {
458
+ memory.clearAll();
459
+ res.end(JSON.stringify({ success: true, cleared: true }));
460
+ }
461
+ else if (endpoint === '/turns') {
462
+ if (req.method === 'DELETE') {
463
+ const id = url.searchParams.get('agentId');
464
+ const targets = id ? [id] : journal.list().map(t => t.agentId).filter(Boolean);
465
+ for (const t of targets) journal.clear(t);
466
+ res.end(JSON.stringify({ success: true, cleared: targets.length }));
467
+ return;
468
+ }
469
+ res.end(JSON.stringify({ success: true, turns: journal.list() }));
470
+ }
471
+ else if (endpoint === '/resume') {
472
+ let body = '';
473
+ for await (const chunk of req) body += chunk;
474
+ const { agentId } = JSON.parse(body || '{}');
475
+ const id = agentId || Array.from(this.agents.keys())[0];
476
+ if (!this.agents.has(id)) throw new Error(`Agent ${id} not found`);
477
+
478
+ const agent = this.agents.get(id);
479
+ const result = await this.queue.run(id, () => liberEngine.resume(id, {
480
+ agentConfig: agent.config,
481
+ memory,
482
+ llmManager,
483
+ onEvent: () => {},
484
+ maxLoops: this.maxLoops,
485
+ waitForHitl: (aid, toolName, args) => this.waitForHitl(aid, `${toolName}: ${JSON.stringify(args)}`)
486
+ }));
487
+
488
+ if (result && result.response && this.traceEnabled) {
489
+ trace.appendTurn({ agentId: id, userMessage: '(resumed turn)', result, model: agent.config.engine?.model });
490
+ }
491
+ res.end(JSON.stringify(result));
492
+ }
493
+ else if (endpoint === '/hitl/verdict') {
494
+ let body = '';
495
+ for await (const chunk of req) body += chunk;
496
+ const { verdict } = JSON.parse(body || '{}');
497
+ const handled = this.resolveHitl(verdict === 'approve' || verdict === true);
498
+ res.end(JSON.stringify({ success: true, handled }));
499
+ }
500
+ else if (endpoint === '/sessions/history') {
501
+ // The window keeps rendered HTML in memory only, so after a restart a
502
+ // session looked empty while its messages were still on disk. This
503
+ // endpoint is what makes a session reopenable.
504
+ const key = url.searchParams.get('key');
505
+ if (!key) {
506
+ res.statusCode = 400;
507
+ res.end(JSON.stringify({ success: false, error: 'Missing key.' }));
508
+ return;
509
+ }
510
+ const messages = (memory.get(key) || []).map(m => ({
511
+ role: m.role,
512
+ content: String(m.content || ''),
513
+ ts: m.ts || null
514
+ }));
515
+ const firstUser = messages.find(m => m.role === 'user' && !/^(OBSERVATION \[E|STOP —|You have at most|You returned an empty response|Your reply contained no \[FINAL|DENIED: approval|GROUNDING AUDIT|Your previous answer)/.test(m.content));
516
+ res.end(JSON.stringify({
517
+ success: true,
518
+ key,
519
+ title: firstUser ? firstUser.content.replace(/\s+/g, ' ').slice(0, 60) : null,
520
+ messages
521
+ }));
522
+ return;
523
+ }
524
+ else if (endpoint === '/sessions/search') {
525
+ const q = String(url.searchParams.get('q') || '').trim().toLowerCase();
526
+ if (!q) {
527
+ res.end(JSON.stringify({ success: true, q, hits: [] }));
528
+ return;
529
+ }
530
+ const hits = [];
531
+ for (const [key, messages] of memory.history?.entries() || []) {
532
+ for (const m of messages) {
533
+ const text = String(m.content || '');
534
+ const at = text.toLowerCase().indexOf(q);
535
+ if (at < 0) continue;
536
+ hits.push({
537
+ key,
538
+ role: m.role,
539
+ snippet: text.slice(Math.max(0, at - 40), at + 90).replace(/\s+/g, ' ').trim(),
540
+ at
541
+ });
542
+ if (hits.length >= 60) break;
543
+ }
544
+ if (hits.length >= 60) break;
545
+ }
546
+ res.end(JSON.stringify({ success: true, q, hits }));
547
+ return;
548
+ }
549
+ else if (endpoint === '/sessions') {
550
+ if (req.method === 'GET') {
551
+ const overview = {};
552
+ for (const [agentId, messages] of memory.history?.entries() || []) {
553
+ const assistant = messages.filter(m => m.role === 'assistant');
554
+ const noise = /^(OBSERVATION \[E|STOP —|You have at most|You returned an empty response|Your reply contained no \[FINAL|DENIED: approval|GROUNDING AUDIT|Your previous answer)/;
555
+ const firstUser = messages.find(m => m.role === 'user' && !noise.test(String(m.content || '')));
556
+ overview[agentId] = {
557
+ messages: messages.length,
558
+ title: firstUser ? String(firstUser.content).replace(/\s+/g, ' ').slice(0, 60) : null,
559
+ last: assistant.length ? String(assistant[assistant.length - 1].content || '').slice(0, 80) : null
560
+ };
561
+ }
562
+ const persisted = {};
563
+ try {
564
+ if (memory.persistPath && fs.existsSync(memory.persistPath)) {
565
+ persisted.size_bytes = fs.statSync(memory.persistPath).size;
566
+ persisted.file = memory.persistPath;
567
+ }
568
+ } catch { /* best effort */ }
569
+ res.end(JSON.stringify({ success: true, sessions: overview, persisted }));
570
+ return;
571
+ }
572
+ if (req.method === 'DELETE') {
573
+ // ?key=agent#session drops one session; without it the whole store goes.
574
+ const key = url.searchParams.get('key');
575
+ if (key) {
576
+ memory.clear(key);
577
+ res.end(JSON.stringify({ success: true, cleared: key }));
578
+ return;
579
+ }
580
+ memory.clearAll();
581
+ res.end(JSON.stringify({ success: true, cleared: true }));
582
+ return;
583
+ }
584
+ }
585
+ else if (endpoint === '/config/backup') {
586
+ try {
587
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
588
+ const outDir = path.join(process.cwd(), '.liber');
589
+
590
+ if (fs.existsSync(outDir)) {
591
+ for (const f of fs.readdirSync(outDir)) {
592
+ if (f.startsWith('liber.yaml.backup')) fs.unlinkSync(path.join(outDir, f));
593
+ }
594
+ }
595
+ fs.mkdirSync(outDir, { recursive: true });
596
+
597
+ const cfgPath = path.resolve(process.cwd(), process.env.LIBER_CONFIG || 'liber.yaml');
598
+ const target = path.join(outDir, `liber.yaml.backup-${stamp}`);
599
+ if (fs.existsSync(cfgPath)) {
600
+ fs.copyFileSync(cfgPath, target);
601
+ }
602
+ res.end(JSON.stringify({ success: true, backup: target }));
603
+ } catch (e) {
604
+ res.statusCode = 500;
605
+ res.end(JSON.stringify({ success: false, error: e.message }));
606
+ }
607
+ return;
608
+ }
609
+ else if (endpoint === '/providers') {
610
+ res.end(JSON.stringify({
611
+ success: true,
612
+ ...providers.status(),
613
+ imports: providers.imports(),
614
+ store: providers.storePath()
615
+ }));
616
+ }
617
+ else if (endpoint === '/providers/key') {
618
+ let body = '';
619
+ for await (const chunk of req) body += chunk;
620
+ const { id, key } = JSON.parse(body || '{}');
621
+ const r = providers.setKey(id, key);
622
+ if (!r.ok) { res.statusCode = 400; res.end(JSON.stringify({ success: false, error: r.error })); return; }
623
+ res.end(JSON.stringify({ success: true, id: r.id, hint: r.hint }));
624
+ }
625
+ else if (endpoint === '/providers/clear') {
626
+ let body = '';
627
+ for await (const chunk of req) body += chunk;
628
+ const { id } = JSON.parse(body || '{}');
629
+ const r = providers.clear(id);
630
+ res.end(JSON.stringify({ success: r.ok, error: r.error || null }));
631
+ }
632
+ else if (endpoint === '/providers/custom') {
633
+ let body = '';
634
+ for await (const chunk of req) body += chunk;
635
+ const r = providers.setCustom(JSON.parse(body || '{}'));
636
+ if (!r.ok) { res.statusCode = 400; res.end(JSON.stringify({ success: false, error: r.error })); return; }
637
+ res.end(JSON.stringify({ success: true, id: r.id }));
638
+ }
639
+ else if (endpoint === '/providers/test') {
640
+ let body = '';
641
+ for await (const chunk of req) body += chunk;
642
+ const { id, key } = JSON.parse(body || '{}');
643
+ res.end(JSON.stringify({ success: true, result: await providers.test(id, { key }) }));
644
+ }
645
+ else if (endpoint === '/providers/import') {
646
+ let body = '';
647
+ for await (const chunk of req) body += chunk;
648
+ const { id } = JSON.parse(body || '{}');
649
+ const r = providers.importFrom(id);
650
+ if (!r.ok) { res.statusCode = 400; res.end(JSON.stringify({ success: false, error: r.error })); return; }
651
+ res.end(JSON.stringify({ success: true, imported: r.id, via: r.via, hint: r.hint, expires_at: r.expires_at }));
652
+ }
653
+ else if (endpoint === '/providers/oauth/start') {
654
+ let body = '';
655
+ for await (const chunk of req) body += chunk;
656
+ const r = await providers.deviceStart(JSON.parse(body || '{}'));
657
+ if (!r.ok) { res.statusCode = 400; res.end(JSON.stringify({ success: false, error: r.error })); return; }
658
+ res.end(JSON.stringify({ success: true, ...r }));
659
+ }
660
+ else if (endpoint === '/providers/oauth/poll') {
661
+ let body = '';
662
+ for await (const chunk of req) body += chunk;
663
+ const r = await providers.devicePoll(JSON.parse(body || '{}'));
664
+ res.end(JSON.stringify({ success: !!r.ok, ...r }));
665
+ }
666
+ else if (endpoint === '/workspace') {
667
+ res.end(JSON.stringify({ success: true, workspace: workspace.summary(), activity: workspace.recent(20) }));
668
+ }
669
+ else if (endpoint === '/git') {
670
+ // Real repository state: local branches, the origin URL and how far the
671
+ // branch has drifted from its upstream. No cached guesses.
672
+ res.end(JSON.stringify({
673
+ success: true,
674
+ ...workspace.gitState(),
675
+ github_url: workspace.githubUrl()
676
+ }));
677
+ }
678
+ else if (endpoint === '/git/checkout') {
679
+ let body = '';
680
+ for await (const chunk of req) body += chunk;
681
+ const { branch: target } = JSON.parse(body || '{}');
682
+ const r = workspace.checkout(target);
683
+ res.statusCode = r.ok ? 200 : 400;
684
+ res.end(JSON.stringify({ success: r.ok, ...r }));
685
+ }
686
+ else if (endpoint === '/git/fetch') {
687
+ const r = workspace.fetchRemote();
688
+ res.statusCode = r.ok ? 200 : 400;
689
+ res.end(JSON.stringify({ success: r.ok, ...r }));
690
+ }
691
+ else if (endpoint === '/workspace/switch') {
692
+ let body = '';
693
+ for await (const chunk of req) body += chunk;
694
+ const requested = String(JSON.parse(body || '{}').path || '').trim();
695
+ if (!requested) {
696
+ res.statusCode = 400;
697
+ res.end(JSON.stringify({ success: false, error: 'Missing path.' }));
698
+ return;
699
+ }
700
+ const target = path.resolve(requested);
701
+ let stat = null;
702
+ try { stat = fs.statSync(target); } catch { /* reported below */ }
703
+ if (!stat || !stat.isDirectory()) {
704
+ res.statusCode = 400;
705
+ res.end(JSON.stringify({ success: false, error: `Not a directory: ${target}` }));
706
+ return;
707
+ }
708
+
709
+ // The daemon is rooted at its own cwd, so switching workspaces means
710
+ // restarting it there. The config file stays the one this daemon booted
711
+ // with (absolute path via LIBER_CONFIG) so the model and policy survive.
712
+ const configPath = path.resolve(process.cwd(), process.env.LIBER_CONFIG || 'liber.yaml');
713
+ const stateDir = path.join(target, '.liber');
714
+ let copiedKeys = false;
715
+ try {
716
+ fs.mkdirSync(stateDir, { recursive: true });
717
+ const src = path.resolve(process.cwd(), '.liber', 'credentials.json');
718
+ const dst = path.join(stateDir, 'credentials.json');
719
+ // Keys follow the app, not the folder: a new workspace with no store of
720
+ // its own inherits the configured providers instead of silently losing them.
721
+ if (fs.existsSync(src) && !fs.existsSync(dst)) {
722
+ fs.copyFileSync(src, dst);
723
+ try { fs.chmodSync(dst, 0o600); } catch { /* best effort on Windows */ }
724
+ copiedKeys = true;
725
+ }
726
+ } catch (err) {
727
+ logger.warn('SYSTEM', 'WORKSPACE_STATE_PREP_FAILED', { error: err.message });
728
+ }
729
+
730
+ const entry = path.resolve(__dirname, '..', '..', 'bin', 'liberd-entry');
731
+ res.end(JSON.stringify({ success: true, switching: true, cwd: target, keys_copied: copiedKeys, config: configPath }));
732
+
733
+ // Give the response a moment to flush before the process goes away.
734
+ setTimeout(() => {
735
+ const { spawn } = require('child_process');
736
+ const child = spawn(process.execPath, [entry], {
737
+ cwd: target,
738
+ detached: true,
739
+ stdio: 'ignore',
740
+ env: { ...process.env, LIBER_CONFIG: configPath }
741
+ });
742
+ child.unref();
743
+ logger.info('SYSTEM', 'WORKSPACE_SWITCH', { from: process.cwd(), to: target });
744
+ setTimeout(() => process.exit(0), 250);
745
+ }, 120);
746
+ }
747
+ else if (endpoint === '/skills') {
748
+ const scanned = skills.scan(true);
749
+ const list = Array.from(scanned.values ? scanned.values() : Object.values(scanned))
750
+ .map(s => ({
751
+ name: s.name,
752
+ description: String(s.description || '').slice(0, 200),
753
+ source: s.source || null,
754
+ always: !!s.always,
755
+ triggers: s.triggers || [],
756
+ bytes: s.size || (String(s.body || '').length || null)
757
+ }));
758
+ res.end(JSON.stringify({ success: true, skills: list, index: skills.indexLines() }));
759
+ }
760
+ else if (endpoint === '/compact') {
761
+ let body = '';
762
+ for await (const chunk of req) body += chunk;
763
+ const { agentId, keep = 6 } = JSON.parse(body || '{}');
764
+ const id = agentId || Array.from(this.agents.keys())[0];
765
+ const before = memory.get(id).length;
766
+ if (before <= keep + 2) {
767
+ res.end(JSON.stringify({
768
+ success: false,
769
+ error: `Nothing to compact (${before} messages, keep=${keep}).`,
770
+ before
771
+ }));
772
+ return;
773
+ }
774
+ const history = memory.get(id);
775
+ const old = history.slice(0, history.length - keep);
776
+ const tail = history.slice(-keep);
777
+ const transcript = old
778
+ .map(m => `${m.role.toUpperCase()}: ${String(m.content).slice(0, 1200)}`)
779
+ .join('\n');
780
+ let method = 'trim';
781
+ let summary = '';
782
+ try {
783
+ const out = await llmManager.generate([
784
+ {
785
+ role: 'system',
786
+ content: 'Summarize this conversation history so an agent can continue the work. Keep decisions, files touched, open questions, and any verified facts with their receipt ids. Be dense; no preamble.'
787
+ },
788
+ { role: 'user', content: transcript }
789
+ ], { temperature: 0.1, max_tokens: 700 });
790
+ summary = String(out?.content || '').trim();
791
+ if (summary) method = 'model';
792
+ } catch {
793
+ method = 'trim';
794
+ }
795
+ if (!summary) {
796
+ summary = `[COMPACTED] ${old.length} earlier messages dropped; the last ${keep} are below.`;
797
+ }
798
+ memory.clear(id);
799
+ memory.add(id, 'system', `[COMPACTED HISTORY]\n${summary}`);
800
+ for (const m of tail) memory.add(id, m.role, m.content);
801
+ res.end(JSON.stringify({
802
+ success: true,
803
+ method,
804
+ before,
805
+ after: memory.get(id).length,
806
+ summary_chars: summary.length
807
+ }));
808
+ }
809
+ else if (endpoint === '/revert') {
810
+ let body = '';
811
+ for await (const chunk of req) body += chunk;
812
+ const { agentId, turns = 1 } = JSON.parse(body || '{}');
813
+ const id = agentId || Array.from(this.agents.keys())[0];
814
+ const history = memory.get(id);
815
+ if (!history.length) {
816
+ res.end(JSON.stringify({ success: false, error: 'No history to revert.' }));
817
+ return;
818
+ }
819
+ let dropped = 0;
820
+ for (let i = 0; i < Math.max(1, Math.min(Number(turns) || 1, 10)); i++) {
821
+ while (history.length && history[history.length - 1].role === 'assistant') {
822
+ history.pop();
823
+ dropped++;
824
+ }
825
+ if (history.length && history[history.length - 1].role === 'user') {
826
+ history.pop();
827
+ dropped++;
828
+ }
829
+ }
830
+ memory.clear(id);
831
+ for (const m of history) memory.add(id, m.role, m.content);
832
+ res.end(JSON.stringify({ success: true, dropped, remaining: memory.get(id).length }));
833
+ }
834
+ else if (endpoint === '/sandbox') {
835
+ if (req.method === 'GET') {
836
+ const term = policy.terminalConfig();
837
+ const terminalTool = require('./core/tools/terminal-tool');
838
+ const dockerOk = terminalTool.containerAvailable(true);
839
+ let dockerVersion = null;
840
+ if (dockerOk) {
841
+ try {
842
+ dockerVersion = String(require('child_process').execFileSync('docker', ['version', '--format', '{{.Server.Version}}'], { timeout: 8000, windowsHide: true })).trim();
843
+ } catch { dockerVersion = null; }
844
+ }
845
+ let wsl = false;
846
+ try {
847
+ const out = require('child_process').execFileSync('wsl.exe', ['-l', '-q'], { timeout: 8000, windowsHide: true });
848
+ wsl = String(out).replace(/\0/g, '').trim().length > 0;
849
+ } catch { wsl = false; }
850
+ res.end(JSON.stringify({
851
+ success: true,
852
+ backend: term.backend,
853
+ sandbox: term.sandbox,
854
+ capabilities: {
855
+ 'constrained-language': process.platform === 'win32',
856
+ docker: dockerOk,
857
+ wsl,
858
+ 'windows-sandbox': false
859
+ },
860
+ docker: { available: dockerOk, server: dockerVersion, image: term.image, network: term.allow_network === true, memory: term.memory, pids: term.pids },
861
+ note: dockerOk
862
+ ? 'Commands run in a container with no network, a read-only root and only the workspace mounted.'
863
+ : 'Docker is not reachable, so commands fall back to PowerShell Constrained Language Mode (not a container).'
864
+ }));
865
+ return;
866
+ }
867
+ res.statusCode = 405;
868
+ res.end(JSON.stringify({ success: false, error: 'Method not allowed.' }));
869
+ return;
870
+ }
871
+ else if (endpoint === '/connectors' || endpoint === '/connectors/reload') {
872
+ if (endpoint === '/connectors/reload') {
873
+ const out = this.installConnectors();
874
+ res.end(JSON.stringify({ success: true, ...out, connectors: connectors.load().connectors.map(c => ({ id: c.id, label: c.label, actions: c.actions.map(a => a.name) })) }));
875
+ return;
876
+ }
877
+ const parsed = connectors.load();
878
+ res.end(JSON.stringify({
879
+ success: true,
880
+ file: connectors.FILE(),
881
+ connectors: parsed.connectors.map(c => ({ id: c.id, label: c.label, baseUrl: c.baseUrl, actions: c.actions.map(a => ({ name: a.name, method: a.method, path: a.path, description: a.description })) })),
882
+ problems: parsed.problems
883
+ }));
884
+ return;
885
+ }
886
+ else if (endpoint === '/voice' || endpoint === '/voice/speak') {
887
+ if (endpoint === '/voice' && req.method === 'GET') {
888
+ const voices = await voice.voices();
889
+ res.end(JSON.stringify({ success: true, available: voice.available(), voices, audioDir: voice.AUDIO_DIR() }));
890
+ return;
891
+ }
892
+ if (endpoint === '/voice/speak' && req.method === 'POST') {
893
+ let b = ''; for await (const ch of req) b += ch;
894
+ const body = JSON.parse(b || '{}');
895
+ const out = await voice.speak(body.text, { voice: body.voice, rate: body.rate, play: body.play !== false });
896
+ logger.info('SYSTEM', 'VOICE_SPEAK', { ok: out.ok, bytes: out.bytes || 0 });
897
+ res.statusCode = out.ok ? 200 : 400;
898
+ res.end(JSON.stringify({ success: out.ok, ...out }));
899
+ return;
900
+ }
901
+ res.statusCode = 405;
902
+ res.end(JSON.stringify({ success: false, error: 'Method not allowed.' }));
903
+ return;
904
+ }
905
+ else if (endpoint === '/vault' || endpoint === '/vault/migrate') {
906
+ const readBody = async () => { let b = ''; for await (const ch of req) b += ch; return JSON.parse(b || '{}'); };
907
+ if (endpoint === '/vault' && req.method === 'GET') {
908
+ res.end(JSON.stringify({ success: true, entries: vault.list(), status: vault.status() }));
909
+ return;
910
+ }
911
+ if (endpoint === '/vault' && req.method === 'POST') {
912
+ const body = await readBody();
913
+ // A value goes in and never comes back out through this route.
914
+ const out = vault.set(body.name, body.value, body.meta || {});
915
+ res.statusCode = out.ok ? 200 : 400;
916
+ res.end(JSON.stringify({ success: out.ok, ...out, entries: vault.list() }));
917
+ return;
918
+ }
919
+ if (endpoint === '/vault' && req.method === 'DELETE') {
920
+ const out = vault.remove(String(url.searchParams.get('name') || ''));
921
+ res.statusCode = out.ok ? 200 : 404;
922
+ res.end(JSON.stringify({ success: out.ok, ...out, entries: vault.list() }));
923
+ return;
924
+ }
925
+ if (endpoint === '/vault/migrate') {
926
+ const out = vault.migrateCredentials();
927
+ logger.info('SYSTEM', 'VAULT_MIGRATION', { moved: out.moved });
928
+ res.end(JSON.stringify({ success: out.ok, ...out, entries: vault.list() }));
929
+ return;
930
+ }
931
+ res.statusCode = 405;
932
+ res.end(JSON.stringify({ success: false, error: 'Method not allowed.' }));
933
+ return;
934
+ }
935
+ else if (endpoint === '/automations' || endpoint === '/automations/update' || endpoint === '/automations/run') {
936
+ const readBody = async () => { let b = ''; for await (const ch of req) b += ch; return JSON.parse(b || '{}'); };
937
+ if (endpoint === '/automations' && req.method === 'GET') {
938
+ res.end(JSON.stringify({ success: true, jobs: automations.list() }));
939
+ return;
940
+ }
941
+ if (endpoint === '/automations' && req.method === 'POST') {
942
+ const created = automations.create(await readBody());
943
+ res.statusCode = created.ok ? 200 : 400;
944
+ res.end(JSON.stringify({ success: created.ok, ...created, jobs: automations.list() }));
945
+ return;
946
+ }
947
+ if (endpoint === '/automations/update') {
948
+ const body = await readBody();
949
+ const out = automations.update(String(body.id || ''), body.patch || body);
950
+ res.statusCode = out.ok ? 200 : 400;
951
+ res.end(JSON.stringify({ success: out.ok, ...out, jobs: automations.list() }));
952
+ return;
953
+ }
954
+ if (endpoint === '/automations/run') {
955
+ const body = await readBody();
956
+ const id = String(body.id || url.searchParams.get('id') || '');
957
+ const job = automations.list().find(j => j.id === id);
958
+ if (!job) { res.statusCode = 404; res.end(JSON.stringify({ success: false, error: 'No such automation.' })); return; }
959
+ const agentId = Array.from(this.agents.keys())[0];
960
+ const agent = this.agents.get(agentId);
961
+ try {
962
+ const result = await this.queue.run(agentId, () => liberEngine.runTurn({
963
+ agentId,
964
+ memoryKey: `${agentId}#auto:${job.id}`,
965
+ agentConfig: agent.config,
966
+ userMessage: job.prompt,
967
+ memory, llmManager,
968
+ onEvent: () => {},
969
+ maxLoops: this.maxLoops,
970
+ waitForHitl: async () => false
971
+ }));
972
+ automations.markRun(job.id, {
973
+ ok: result?.success !== false,
974
+ chars: String(result?.response || '').length,
975
+ excerpt: result?.response,
976
+ error: result?.success === false ? result.error : null
977
+ });
978
+ res.end(JSON.stringify({ success: true, response: String(result?.response || '').slice(0, 400), jobs: automations.list() }));
979
+ } catch (err) {
980
+ automations.markRun(job.id, { ok: false, error: err.message });
981
+ res.statusCode = 500;
982
+ res.end(JSON.stringify({ success: false, error: err.message, jobs: automations.list() }));
983
+ }
984
+ return;
985
+ }
986
+ if (endpoint === '/automations' && req.method === 'DELETE') {
987
+ const id = url.searchParams.get('id');
988
+ const out = automations.remove(String(id || ''));
989
+ res.statusCode = out.ok ? 200 : 404;
990
+ res.end(JSON.stringify({ success: out.ok, ...out, jobs: automations.list() }));
991
+ return;
992
+ }
993
+ res.statusCode = 405;
994
+ res.end(JSON.stringify({ success: false, error: 'Method not allowed.' }));
995
+ return;
996
+ }
997
+ else if (endpoint === '/memory') {
998
+ // The same store the agent's memory tool writes to, exposed so the
999
+ // window can show what a new session will already know.
1000
+ if (req.method === 'GET') {
1001
+ res.end(JSON.stringify({
1002
+ success: true,
1003
+ entries: memoryBank.memoryEntries(),
1004
+ block: memoryBank.memoryBlock(1400),
1005
+ chars: memoryBank.memoryBlock(1400).length
1006
+ }));
1007
+ return;
1008
+ }
1009
+ if (req.method === 'DELETE') {
1010
+ const key = url.searchParams.get('key');
1011
+ if (!key) {
1012
+ res.statusCode = 400;
1013
+ res.end(JSON.stringify({ success: false, error: 'Missing key.' }));
1014
+ return;
1015
+ }
1016
+ const out = memoryBank.manageMemory({ action: 'delete', key });
1017
+ res.end(JSON.stringify({ success: true, deleted: key, ...out }));
1018
+ return;
1019
+ }
1020
+ let body = '';
1021
+ for await (const chunk of req) body += chunk;
1022
+ const parsed = JSON.parse(body || '{}');
1023
+ const key = String(parsed.key || '').trim();
1024
+ if (!key) {
1025
+ res.statusCode = 400;
1026
+ res.end(JSON.stringify({ success: false, error: 'Missing key.' }));
1027
+ return;
1028
+ }
1029
+ const written = memoryBank.manageMemory({ action: 'set', key, value: parsed.value ?? '' });
1030
+ res.end(JSON.stringify({ success: true, ...written, entries: memoryBank.memoryEntries() }));
1031
+ return;
1032
+ }
1033
+ else if (endpoint === '/budget') {
1034
+ const first = Array.from(this.agents.values())[0];
1035
+ const limits = first?.config?.limits || {};
1036
+ const engine = first?.config?.engine || {};
1037
+ if (req.method === 'POST') {
1038
+ // Reset today's counter so a blocked day can be resumed without
1039
+ // editing JSON on disk.
1040
+ let body = '';
1041
+ for await (const chunk of req) body += chunk;
1042
+ const action = String(JSON.parse(body || '{}').action || 'reset');
1043
+ if (action === 'reset') budget.reset();
1044
+ res.end(JSON.stringify({ success: true, action, budget: budget.summary(limits, engine) }));
1045
+ return;
1046
+ }
1047
+ res.end(JSON.stringify({ success: true, budget: budget.summary(limits, engine) }));
1048
+ return;
1049
+ }
1050
+ else if (endpoint === '/budget/limit') {
1051
+ let body = '';
1052
+ for await (const chunk of req) body += chunk;
1053
+ const parsed = JSON.parse(body || '{}');
1054
+ const tokens = Number(parsed.tokens);
1055
+ if (!Number.isFinite(tokens) || tokens < 0) {
1056
+ res.statusCode = 400;
1057
+ res.end(JSON.stringify({ success: false, error: 'tokens must be a number >= 0 (0 = no limit).' }));
1058
+ return;
1059
+ }
1060
+ const { changes, error } = configApply.validateConfigUpdate({ 'limits.max_tokens_per_day': tokens });
1061
+ if (error) {
1062
+ res.statusCode = 400;
1063
+ res.end(JSON.stringify({ success: false, error }));
1064
+ return;
1065
+ }
1066
+ for (const [, agent] of this.agents.entries()) {
1067
+ for (const [p, value] of Object.entries(changes)) this.applyConfigPath(agent, p, value);
1068
+ }
1069
+ this.persistConfigChanges(changes);
1070
+ const first = Array.from(this.agents.values())[0];
1071
+ res.end(JSON.stringify({
1072
+ success: true,
1073
+ limit_tokens: tokens,
1074
+ budget: budget.summary(first?.config?.limits || {}, first?.config?.engine || {})
1075
+ }));
1076
+ return;
1077
+ }
1078
+ else if (endpoint === '/config/export') {
1079
+ try {
1080
+ const cfgPath = path.resolve(process.cwd(), process.env.LIBER_CONFIG || 'liber.yaml');
1081
+ const raw = fs.existsSync(cfgPath) ? fs.readFileSync(cfgPath, 'utf8') : '';
1082
+ const secrets = require('./core/secrets');
1083
+ res.end(JSON.stringify({ success: true, path: cfgPath, yaml: secrets.redact(raw) }));
1084
+ } catch (e) {
1085
+ res.statusCode = 500;
1086
+ res.end(JSON.stringify({ success: false, error: e.message }));
1087
+ }
1088
+ return;
1089
+ }
1090
+ else if (endpoint === '/config/reset') {
1091
+ const defs = configApply.defaults();
1092
+ const { changes, error } = configApply.validateConfigUpdate(defs);
1093
+ if (error) {
1094
+ res.statusCode = 500;
1095
+ res.end(JSON.stringify({ success: false, error }));
1096
+ return;
1097
+ }
1098
+ for (const [, agent] of this.agents.entries()) {
1099
+ for (const [p, value] of Object.entries(changes)) {
1100
+ this.applyConfigPath(agent, p, value);
1101
+ }
1102
+ if (Object.keys(changes).some(k => k.startsWith('engine.'))) {
1103
+ const cfg = agent.config;
1104
+ const key = ConfigLoader.resolveApiKey(cfg.engine.provider, cfg.engine.endpoint);
1105
+ if (key) cfg.engine.apiKey = key;
1106
+ llmManager.initialize(cfg.engine);
1107
+ }
1108
+ }
1109
+ this.persistConfigChanges(changes);
1110
+ const firstReset = Array.from(this.agents.values())[0];
1111
+ res.end(JSON.stringify({
1112
+ success: true,
1113
+ reset: Object.keys(changes),
1114
+ applied: configApply.sanitizeConfig(firstReset?.config, this.traceEnabled, process.cwd())
1115
+ }));
1116
+ return;
1117
+ }
1118
+ else if (endpoint === '/config') {
1119
+ if (req.method === 'GET') {
1120
+ const first = Array.from(this.agents.values())[0];
1121
+ res.end(JSON.stringify({
1122
+ success: true,
1123
+ config: configApply.sanitizeConfig(first?.config, this.traceEnabled, process.cwd())
1124
+ }));
1125
+ return;
1126
+ }
1127
+
1128
+ // POST: whitelisted live updates, applied to every agent and persisted.
1129
+ let body = '';
1130
+ for await (const chunk of req) body += chunk;
1131
+ let payload;
1132
+ try {
1133
+ payload = JSON.parse(body || '{}');
1134
+ } catch {
1135
+ res.statusCode = 400;
1136
+ res.end(JSON.stringify({ success: false, error: 'Invalid JSON body.' }));
1137
+ return;
1138
+ }
1139
+ const { changes, error } = configApply.validateConfigUpdate(payload);
1140
+ if (error) {
1141
+ res.statusCode = 400;
1142
+ res.end(JSON.stringify({ success: false, error }));
1143
+ return;
1144
+ }
1145
+
1146
+ const engineTouched = Object.keys(changes).some(k => k.startsWith('engine.'));
1147
+ for (const [id, agent] of this.agents.entries()) {
1148
+ for (const [p, value] of Object.entries(changes)) {
1149
+ this.applyConfigPath(agent, p, value);
1150
+ }
1151
+ if (engineTouched) {
1152
+ const cfg = agent.config;
1153
+ const key = ConfigLoader.resolveApiKey(cfg.engine.provider, cfg.engine.endpoint);
1154
+ if (key) cfg.engine.apiKey = key;
1155
+ llmManager.initialize(cfg.engine);
1156
+ }
1157
+ }
1158
+
1159
+ this.persistConfigChanges(changes);
1160
+
1161
+ const first = Array.from(this.agents.values())[0];
1162
+ res.end(JSON.stringify({
1163
+ success: true,
1164
+ applied: configApply.sanitizeConfig(first?.config, this.traceEnabled, process.cwd())
1165
+ }));
1166
+ }
1167
+ else if (endpoint === '/models') {
1168
+ const firstAgent = Array.from(this.agents.values())[0];
1169
+ const engine = firstAgent?.config?.engine || {};
1170
+ const models = await this.fetchAvailableModels(engine);
1171
+ res.end(JSON.stringify({ success: true, active: engine.model, models }));
1172
+ }
1173
+ else if (endpoint === '/model/switch') {
1174
+ let body = '';
1175
+ for await (const chunk of req) body += chunk;
1176
+ const spec = modelSwitch.validateSwitch(JSON.parse(body || '{}'));
1177
+ if (spec.error) {
1178
+ res.statusCode = 400;
1179
+ res.end(JSON.stringify({ success: false, error: spec.error }));
1180
+ return;
1181
+ }
1182
+
1183
+ const changed = {};
1184
+ for (const [id, agent] of this.agents.entries()) {
1185
+ const engine = agent.config.engine;
1186
+ if (spec.provider && engine.provider !== spec.provider) {
1187
+ engine.provider = spec.provider;
1188
+ }
1189
+ engine.model = spec.model;
1190
+ if (spec.endpoint) engine.endpoint = spec.endpoint;
1191
+ // Endpoint-aware key: Groq/DeepSeek/Mistral/... each need their own key.
1192
+ const key = ConfigLoader.resolveApiKey(engine.provider, engine.endpoint);
1193
+ if (key) engine.apiKey = key;
1194
+ llmManager.initialize(engine);
1195
+ changed[id] = { ...modelSwitch.sanitizeEngine(engine), key_resolved: !!key };
1196
+ }
1197
+
1198
+ this.persistConfigChanges({ 'engine.provider': spec.provider, 'engine.model': spec.model, 'engine.endpoint': spec.endpoint });
1199
+
1200
+ const first = Array.from(this.agents.values())[0];
1201
+ res.end(JSON.stringify({
1202
+ success: true,
1203
+ active: first ? modelSwitch.sanitizeEngine(first.config.engine) : { model: spec.model, provider: spec.provider, endpoint: spec.endpoint },
1204
+ changed
1205
+ }));
1206
+ }
1207
+ else if (endpoint === '/chat/stream' || endpoint === '/resume/stream') {
1208
+ res.setHeader('Content-Type', 'text/event-stream');
1209
+ res.setHeader('Cache-Control', 'no-cache');
1210
+ res.setHeader('Connection', 'keep-alive');
1211
+ res.setHeader('Access-Control-Allow-Origin', '*');
1212
+
1213
+ const sendEvent = (event, data) => {
1214
+ // Feed the desktop Overview rail with the tool steps this daemon
1215
+ // actually executed (observations only — no invented entries).
1216
+ if (event === 'observation') {
1217
+ workspace.record({
1218
+ tool: data.tool,
1219
+ ok: data.ok,
1220
+ evidence: data.evidence,
1221
+ detail: data.command || data.output,
1222
+ exit_code: data.exit_code
1223
+ });
1224
+ }
1225
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
1226
+ };
1227
+
1228
+ let body = '';
1229
+ for await (const chunk of req) body += chunk;
1230
+ const parsed = JSON.parse(body || '{}');
1231
+ let agentId = parsed.agentId || Array.from(this.agents.keys())[0];
1232
+ const { sessionId, message } = parsed;
1233
+
1234
+ // The window can hang up mid-turn (stop button, closed app). Stop spending
1235
+ // tokens between iterations instead of finishing a reply nobody will see.
1236
+ let clientGone = false;
1237
+ res.on('close', () => { if (!res.writableEnded) clientGone = true; });
1238
+ const shouldStop = () => clientGone;
1239
+
1240
+ if (!this.agents.has(agentId)) {
1241
+ sendEvent('error', { error: `Agent ${agentId} not found` });
1242
+ res.end();
1243
+ return;
1244
+ }
1245
+
1246
+ const agent = this.agents.get(agentId);
1247
+
1248
+ if (endpoint === '/resume/stream') {
1249
+ try {
1250
+ const result = await this.queue.run(agentId, () => liberEngine.resume(agentId, {
1251
+ agentConfig: agent.config,
1252
+ memory,
1253
+ llmManager,
1254
+ onEvent: sendEvent,
1255
+ maxLoops: this.maxLoops,
1256
+ shouldStop,
1257
+ waitForHitl: (aid, toolName, args) => this.waitForHitl(aid, `${toolName}: ${JSON.stringify(args)}`)
1258
+ }));
1259
+ if (result && result.success === false) sendEvent('error', { error: result.error });
1260
+ else if (this.traceEnabled && result && result.response) {
1261
+ trace.appendTurn({ agentId, userMessage: '(resumed turn)', result, model: agent.config.engine?.model });
1262
+ }
1263
+ } catch (err) {
1264
+ sendEvent('error', { error: err.message });
1265
+ }
1266
+ res.end();
1267
+ return;
1268
+ }
1269
+
1270
+ // A session is its own history key; omitting sessionId keeps the old behaviour.
1271
+ const memoryKey = sessionId ? `${agentId}#${sessionId}` : agentId;
1272
+ try {
1273
+ const result = await this.queue.run(agentId, () => liberEngine.runTurn({
1274
+ agentId,
1275
+ memoryKey,
1276
+ agentConfig: agent.config,
1277
+ userMessage: message,
1278
+ memory,
1279
+ llmManager,
1280
+ onEvent: sendEvent,
1281
+ waitForHitl: (aid, toolName, args) => this.waitForHitl(aid, `${toolName}: ${JSON.stringify(args)}`),
1282
+ maxLoops: this.maxLoops,
1283
+ shouldStop
1284
+ }));
1285
+ if (this.traceEnabled) {
1286
+ trace.appendTurn({ agentId, userMessage: message, result, model: agent.config.engine?.model });
1287
+ }
1288
+ } catch (err) {
1289
+ sendEvent('error', { error: err.message });
1290
+ }
1291
+ res.end();
1292
+ }
1293
+ else if (endpoint === '/chat') {
1294
+ let body = '';
1295
+ for await (const chunk of req) body += chunk;
1296
+ const { agentId, sessionId, message } = JSON.parse(body || '{}');
1297
+
1298
+ if (!this.agents.has(agentId)) throw new Error(`Agent ${agentId} not found`);
1299
+ const agent = this.agents.get(agentId);
1300
+ const memoryKey = sessionId ? `${agentId}#${sessionId}` : agentId;
1301
+
1302
+ const result = await this.queue.run(agentId, () => liberEngine.runTurn({
1303
+ agentId,
1304
+ memoryKey,
1305
+ agentConfig: agent.config,
1306
+ userMessage: message,
1307
+ memory,
1308
+ llmManager,
1309
+ // This endpoint answers with one JSON body, so there is no channel to
1310
+ // ask a human: it fails closed. A command that needs approval is
1311
+ // refused and the reply reports the denial. Use /chat/stream when the
1312
+ // client can show a prompt and POST /hitl/verdict.
1313
+ waitForHitl: () => Promise.resolve(false),
1314
+ maxLoops: this.maxLoops
1315
+ }));
1316
+
1317
+ if (this.traceEnabled) {
1318
+ trace.appendTurn({ agentId, userMessage: message, result, model: agent.config.engine?.model });
1319
+ }
1320
+
1321
+ res.end(JSON.stringify(result));
1322
+ }
1323
+ else {
1324
+ res.statusCode = 404;
1325
+ res.end(JSON.stringify({ success: false, error: 'Endpoint not found' }));
1326
+ }
1327
+ } catch (err) {
1328
+ logger.error('SYSTEM', 'REQUEST_FAILED', { error: err.message });
1329
+ res.statusCode = 500;
1330
+ res.end(JSON.stringify({ success: false, error: err.message }));
1331
+ }
1332
+ }
1333
+
1334
+ stop() {
1335
+ if (this.server) this.server.close();
1336
+ // a headless browser must not outlive the daemon that started it
1337
+ try { require('./core/tools/browser-tool').close(); } catch { /* not launched */ }
1338
+ if (this._autoTimer) { clearInterval(this._autoTimer); this._autoTimer = null; }
1339
+ }
1340
+ }
1341
+
1342
+ module.exports = new LiberDaemon();
1343
+