aegisai-harness 0.74.0 → 0.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  All notable changes to AegisAi Harness are documented here.
4
4
 
5
- ## [0.74.0] - 2026-11-24
5
+ ## [0.76.0] - 2026-11-25
6
6
 
7
7
  ### Fixed
8
8
  - Installation: Windows installer now preflights Node.js 22.13+ with actionable messages; launcher no longer hides npm failures, uses `--omit=dev`, and records a dependency marker. Inno uninstall removes stale `node_modules`/lockfiles; `install.ps1` preserves `data/` and handles GitHub source zips.
package/README.md CHANGED
@@ -10,7 +10,7 @@ A **feature-rich, local-only AI agent harness** — OpenCode-class runtime, but
10
10
  offline-first: no cloud dependencies, no telemetry. 66 milestones, ~200 modules,
11
11
  257 tests, CI green.
12
12
 
13
- > Status: v0.74.0 (see [ROADMAP.md](./ROADMAP.md)).
13
+ > Status: v0.76.0 (see [ROADMAP.md](./ROADMAP.md)).
14
14
  > **Successor to [aegisai-next](https://github.com/user6811992/aegisai-next)** — that project is deprecated; all features have been ported here.
15
15
  > **Live docs:** https://user6811992.github.io/aegisai-harness/
16
16
 
package/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # AegisAi Harness — agent-readable catalog
2
2
 
3
- A feature-rich, local-only AI agent harness. CLI-first, offline-first. v0.74.0.
3
+ A feature-rich, local-only AI agent harness. CLI-first, offline-first. v0.76.0.
4
4
 
5
5
  ## Capabilities
6
6
  - Multi-backend LLM adapter (Ollama + OpenAI-compatible + 18 providers)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aegisai-harness",
3
- "version": "0.74.0",
3
+ "version": "0.76.0",
4
4
  "description": "AegisAi Harness — feature-rich, local-only AI agent harness",
5
5
  "type": "commonjs",
6
6
  "main": "src/index.js",
@@ -4,13 +4,13 @@
4
4
  [Setup]
5
5
  AppId={{8F3D1B2A-6C4E-4B9A-9D21-AE615A010001}}
6
6
  AppName=AegisAi Harness
7
- AppVersion=0.74.0
7
+ AppVersion=0.76.0
8
8
  AppPublisher=AegisAi
9
9
  AppPublisherURL=https://github.com/user6811992/aegisai-harness
10
10
  DefaultDirName={autopf}\AegisAiHarness
11
11
  DefaultGroupName=AegisAi Harness
12
12
  OutputDir=..\..\dist
13
- OutputBaseFilename=AegisAi-Harness-0.74.0-Setup
13
+ OutputBaseFilename=AegisAi-Harness-0.76.0-Setup
14
14
  Compression=lzma2
15
15
  SolidCompression=yes
16
16
  PrivilegesRequired=lowest
package/public/app.js CHANGED
@@ -4,7 +4,37 @@ import { useState, useEffect, useRef, useCallback } from '/vendor/hooks.mjs';
4
4
  import htm from '/vendor/htm.mjs';
5
5
  const html = htm.bind(h);
6
6
 
7
- const API = (p) => fetch(p).then((r) => r.json());
7
+ // Auth token support: stored in sessionStorage, sent as Bearer on every API call.
8
+ function authToken() { try { return sessionStorage.getItem('aegisai_token') || localStorage.getItem('aegisai_token') || ''; } catch (e) { return ''; } }
9
+ function setAuthToken(t) { try { if (t) sessionStorage.setItem('aegisai_token', t); else sessionStorage.removeItem('aegisai_token'); } catch (e) {} }
10
+ function authHeaders(extra) {
11
+ const h = Object.assign({}, extra || {});
12
+ const t = authToken();
13
+ if (t) h.Authorization = 'Bearer ' + t;
14
+ return h;
15
+ }
16
+
17
+ // Central API helper: throws on non-2xx so callers cannot report false success.
18
+ async function API(p, opts) {
19
+ const o = Object.assign({}, opts || {});
20
+ o.headers = authHeaders(o.headers);
21
+ const r = await fetch(p, o);
22
+ let body = null;
23
+ try { body = await r.json(); } catch (e) { body = null; }
24
+ if (!r.ok) {
25
+ if (r.status === 401) window.dispatchEvent(new CustomEvent('aegisai-unauthorized'));
26
+ const msg = (body && body.error) || ('HTTP ' + r.status);
27
+ throw Object.assign(new Error(msg), { status: r.status, body });
28
+ }
29
+ return body;
30
+ }
31
+
32
+ // Fetch wrapper for streaming + non-JSON callers.
33
+ function apiFetch(p, opts) {
34
+ const o = Object.assign({}, opts || {});
35
+ o.headers = authHeaders(o.headers);
36
+ return fetch(p, o);
37
+ }
8
38
 
9
39
  let toastFn = null;
10
40
  function toast(msg, type = 'info') { if (toastFn) toastFn(msg, type); }
@@ -68,7 +98,9 @@ function OnboardingWizard({ onComplete }) {
68
98
  const body = { BACKEND_TYPE: backend };
69
99
  if (model) body.AEGISAI_MODEL = model;
70
100
  if (token) body.AEGISAI_TOKEN = token;
71
- await fetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
101
+ await apiFetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
102
+ // Keep the UI authenticated after enabling a token.
103
+ if (token) setAuthToken(token.trim());
72
104
  } catch (e) {
73
105
  console.error('config save failed:', e);
74
106
  }
@@ -149,11 +181,17 @@ function ConfigModal({ cfg, setCfg, onClose }) {
149
181
  useEffect(() => { API('/api/config').then(setLocal); }, []);
150
182
  async function save() {
151
183
  setSaving(true);
152
- await fetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(local) });
153
- setCfg(local);
184
+ try {
185
+ await apiFetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(local) }).then(async (r) => {
186
+ if (!r.ok) { let e = 'HTTP ' + r.status; try { const b = await r.json(); if (b && b.error) e = b.error; } catch (_) {} throw new Error(e); }
187
+ });
188
+ setCfg(local);
189
+ toast('Configuration saved', 'success');
190
+ onClose();
191
+ } catch (e) {
192
+ toast('Save failed: ' + e.message, 'error');
193
+ }
154
194
  setSaving(false);
155
- toast('Configuration saved', 'success');
156
- onClose();
157
195
  }
158
196
  const keys = ['BACKEND_TYPE', 'BACKEND_URL', 'AEGISAI_MODEL', 'REA_BIN', 'GHIDRA_MCP_URL', 'CRAFT_BIN', 'sttUrl', 'ttsUrl'];
159
197
  const [tab, setTab] = useState('config');
@@ -196,7 +234,7 @@ function ConfigModal({ cfg, setCfg, onClose }) {
196
234
  async function pullModel(name) {
197
235
  toast('Pulling ' + name + '...', 'info');
198
236
  try {
199
- const r = await fetch('/api/models/pull', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: name }) });
237
+ const r = await apiFetch('/api/models/pull', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: name }) });
200
238
  const d = await r.json();
201
239
  if (d.ok) toast('Pulled ' + name + ' successfully', 'success');
202
240
  else toast('Pull failed: ' + (d.error || 'unknown'), 'error');
@@ -345,6 +383,8 @@ function App() {
345
383
  const [toasts, setToasts] = useState([]);
346
384
  const [toolLog, setToolLog] = useState([]);
347
385
  const [dragOver, setDragOver] = useState(false);
386
+ const [needAuth, setNeedAuth] = useState(false);
387
+ const [tokenInput, setTokenInput] = useState('');
348
388
  const inputRef = useRef(null);
349
389
  const chatRef = useRef(null);
350
390
 
@@ -362,10 +402,16 @@ function App() {
362
402
  }, [theme]);
363
403
 
364
404
  useEffect(() => { updateCtx(); }, []);
405
+ useEffect(() => {
406
+ // Server rejected our request: prompt for a token instead of failing silently.
407
+ const onUnauth = () => setNeedAuth(true);
408
+ window.addEventListener('aegisai-unauthorized', onUnauth);
409
+ return () => window.removeEventListener('aegisai-unauthorized', onUnauth);
410
+ }, []);
365
411
  useEffect(() => {
366
412
  API('/api/version').then((v) => {
367
- if (v.version && v.version !== '0.73.0') toast('Update available: v' + v.version, 'info');
368
- }).catch(() => {});
413
+ if (v && v.updateAvailable) toast('Update available: v' + (v.latest || '') + ' (current ' + (v.current || '') + ')', 'info');
414
+ }).catch((e) => { if (e && e.status === 401) setNeedAuth(true); });
369
415
  }, []);
370
416
 
371
417
  useEffect(() => {
@@ -433,7 +479,8 @@ function App() {
433
479
  // Add empty assistant message for streaming
434
480
  setMessages((m) => [...m, { role: 'assistant', content: '' }]);
435
481
  try {
436
- const r = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: text, stream: true }) });
482
+ const r = await apiFetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: text, stream: true }) });
483
+ if (r.status === 401) { window.dispatchEvent(new CustomEvent('aegisai-unauthorized')); throw new Error('unauthorized'); }
437
484
  if (!r.ok) throw new Error('HTTP ' + r.status);
438
485
  const reader = r.body.getReader();
439
486
  const decoder = new TextDecoder();
@@ -458,12 +505,23 @@ function App() {
458
505
  });
459
506
  } else if (data.type === 'tool_call') {
460
507
  toast('Tool: ' + data.name, 'info');
508
+ } else if (data.type === 'error') {
509
+ throw new Error(data.message || 'stream error');
461
510
  } else if (data.type === 'done') {
462
511
  if (data.toolLog) setToolLog(data.toolLog);
512
+ // Fall back to the authoritative reply if no token frames arrived.
513
+ if (!fullReply && data.reply) {
514
+ fullReply = data.reply;
515
+ setMessages((m) => {
516
+ const updated = [...m];
517
+ updated[updated.length - 1] = { role: 'assistant', content: fullReply };
518
+ return updated;
519
+ });
520
+ }
463
521
  updateCtx();
464
522
  toast('Response received', 'success');
465
523
  }
466
- } catch (e) {}
524
+ } catch (e) { if (e && e.message && e.message !== 'Unexpected end of JSON input') throw e; }
467
525
  }
468
526
  }
469
527
  } catch (e) {
@@ -510,7 +568,7 @@ function App() {
510
568
 
511
569
  async function exportChat(format) {
512
570
  try {
513
- const r = await fetch('/api/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ format, title: 'Chat Export' }) });
571
+ const r = await apiFetch('/api/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ format, title: 'Chat Export' }) });
514
572
  const d = await r.json();
515
573
  if (d.ok) toast('Exported to ' + d.path, 'success');
516
574
  else toast('Export failed: ' + (d.error || 'unknown'), 'error');
@@ -546,7 +604,7 @@ function App() {
546
604
  setComparing(true);
547
605
  try {
548
606
  const models = compareModels.split(',').map((m) => m.trim()).filter(Boolean);
549
- const r = await fetch('/api/compare', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: comparePrompt, models }) });
607
+ const r = await apiFetch('/api/compare', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: comparePrompt, models }) });
550
608
  const d = await r.json();
551
609
  setCompareResult(d);
552
610
  toast('Comparison complete', 'success');
@@ -555,7 +613,24 @@ function App() {
555
613
  }
556
614
 
557
615
  if (view === 'onboarding') {
558
- return html`<${OnboardingWizard} onComplete=${() => setView('chat')} />`;
616
+ return html`
617
+ <div class="app" data-theme=${theme}>
618
+ <${ToastContainer} />
619
+ ${needAuth ? html`
620
+ <div class="modal-backdrop">
621
+ <div class="modal" onClick=${(e) => e.stopPropagation()}>
622
+ <h2>Authentication Required</h2>
623
+ <p>The server requires an access token. Enter it below.</p>
624
+ <input type="password" value=${tokenInput} onInput=${(e) => setTokenInput(e.target.value)} placeholder="Access token" style="width:100%" />
625
+ <div class="modal-actions">
626
+ <button class="btn-primary" onClick=${() => { setAuthToken(tokenInput.trim()); setNeedAuth(false); setTokenInput(''); toast('Token set', 'success'); updateCtx(); }}>Use Token</button>
627
+ </div>
628
+ </div>
629
+ </div>
630
+ ` : null}
631
+ <${OnboardingWizard} onComplete=${() => { setNeedAuth(false); setView('chat'); updateCtx(); }} />
632
+ </div>
633
+ `;
559
634
  }
560
635
 
561
636
  return html`
@@ -564,8 +639,19 @@ function App() {
564
639
  <${CommandPalette} open=${showPalette} onClose=${() => setShowPalette(false)} commands=${commands} />
565
640
  ${showConfig ? html`<${ConfigModal} cfg=${cfg} setCfg=${setCfg} onClose=${() => setShowConfig(false)} />` : null}
566
641
  ${showHelp ? html`<${HelpPanel} onClose=${() => setShowHelp(false)} />` : null}
567
- ${showShortcuts ? html`
568
- <div class="modal-backdrop" onClick=${() => setShowShortcuts(false)}>
642
+ ${needAuth ? html`
643
+ <div class="modal-backdrop">
644
+ <div class="modal" onClick=${(e) => e.stopPropagation()}>
645
+ <h2>Authentication Required</h2>
646
+ <p>The server requires an access token. Enter it below (stored in this browser session only).</p>
647
+ <input type="password" value=${tokenInput} onInput=${(e) => setTokenInput(e.target.value)} placeholder="Access token" style="width:100%" />
648
+ <div class="modal-actions">
649
+ <button class="btn-primary" onClick=${() => { setAuthToken(tokenInput.trim()); setNeedAuth(false); setTokenInput(''); toast('Token set', 'success'); updateCtx(); }}>Use Token</button>
650
+ </div>
651
+ </div>
652
+ </div>
653
+ ` : null}
654
+ ${showShortcuts ? html` <div class="modal-backdrop" onClick=${() => setShowShortcuts(false)}>
569
655
  <div class="modal" onClick=${(e) => e.stopPropagation()}>
570
656
  <h2>Keyboard Shortcuts</h2>
571
657
  <div class="shortcuts-list">
@@ -668,7 +754,13 @@ function App() {
668
754
  </div>
669
755
  </div>
670
756
  ` : null}
671
- <${SessionSidebar} open=${showSessions} onClose=${() => setShowSessions(false)} onSelect=${(s) => { toast('Loaded session: ' + (s.title || s.id), 'info'); }} />
757
+ <${SessionSidebar} open=${showSessions} onClose=${() => setShowSessions(false)} onSelect=${async (s) => {
758
+ try {
759
+ const d = await API('/api/sessions?id=' + encodeURIComponent(s.id));
760
+ setMessages((d.messages || []).map((m) => ({ role: m.role, content: m.content })));
761
+ toast('Loaded session: ' + (s.title || s.id), 'success');
762
+ } catch (e) { toast('Load failed: ' + e.message, 'error'); }
763
+ }} />
672
764
  <header class="topbar">
673
765
  <h1>AegisAi Harness</h1>
674
766
  <span class="ctx-meter">ctx ${ctx.tokens}/${ctx.limit}${ctx.compacted ? ' · compacted' : ''}</span>
package/public/sw.js CHANGED
@@ -1,44 +1,33 @@
1
- // Offline cache for the local web UI. Bump CACHE when bundled assets change.
2
1
  const CACHE = 'aegisai-harness-v2';
3
- const CORE = [
4
- '/', '/index.html', '/style.css', '/app.js', '/markdown.js', '/manifest.json',
5
- '/vendor/preact.mjs', '/vendor/hooks.mjs', '/vendor/htm.mjs', '/vendor/tailwind.js'
6
- ];
2
+ const PRECACHE = ['/', '/style.css', '/app.js', '/manifest.json', '/vendor/preact.mjs', '/vendor/hooks.mjs', '/vendor/htm.mjs', '/vendor/tailwind.js'];
7
3
 
8
- self.addEventListener('install', (event) => {
9
- event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(CORE)).then(() => self.skipWaiting()));
4
+ self.addEventListener('install', (e) => {
5
+ self.skipWaiting();
6
+ e.waitUntil(caches.open(CACHE).then((c) => c.addAll(PRECACHE)).catch(() => {}));
10
7
  });
11
8
 
12
- self.addEventListener('activate', (event) => {
13
- event.waitUntil(
14
- caches.keys()
15
- .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
9
+ self.addEventListener('activate', (e) => {
10
+ e.waitUntil(
11
+ caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
16
12
  .then(() => self.clients.claim())
17
13
  );
18
14
  });
19
15
 
20
- self.addEventListener('fetch', (event) => {
21
- const req = event.request;
16
+ self.addEventListener('fetch', (e) => {
17
+ const req = e.request;
22
18
  if (req.method !== 'GET') return;
23
- const url = new URL(req.url);
24
- if (url.origin !== self.location.origin) return; // never intercept backend/LLM calls
25
-
26
- if (req.mode === 'navigate') {
27
- event.respondWith(fetch(req).then((res) => {
28
- const copy = res.clone();
29
- caches.open(CACHE).then((c) => c.put('/index.html', copy));
30
- return res;
31
- }).catch(() => caches.match('/index.html')));
32
- return;
33
- }
34
-
35
- event.respondWith(
19
+ let url;
20
+ try { url = new URL(req.url); } catch (err) { return; }
21
+ if (url.origin !== self.location.origin) return;
22
+ // Never intercept API / protocol calls: always network, never cached.
23
+ if (url.pathname.startsWith('/api/') || url.pathname === '/mcp' || url.pathname.startsWith('/mcp/')) return;
24
+ e.respondWith(
36
25
  caches.match(req).then((hit) => hit || fetch(req).then((res) => {
37
- if (res.ok) {
26
+ if (res && res.ok && res.type === 'basic') {
38
27
  const copy = res.clone();
39
- caches.open(CACHE).then((c) => c.put(req, copy));
28
+ caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {});
40
29
  }
41
30
  return res;
42
- }))
31
+ }).catch(() => hit))
43
32
  );
44
33
  });
package/src/a2a.js CHANGED
@@ -8,7 +8,7 @@ function agentCard() {
8
8
  return {
9
9
  name: 'aegisai-harness',
10
10
  description: 'Local-only AI agent harness',
11
- version: '0.31.0',
11
+ version: require('./version').VERSION,
12
12
  capabilities: { streaming: false, pushNotifications: false, stateTransitionHistory: true },
13
13
  defaultInputModes: ['text'],
14
14
  defaultOutputModes: ['text'],
package/src/acp.js CHANGED
@@ -6,7 +6,7 @@ function createServer(opts) {
6
6
  opts = opts || {};
7
7
  const sessions = new Map();
8
8
  const methods = {
9
- initialize: async (params) => ({ protocolVersion: 1, capabilities: { prompt: true, cancel: true }, agentInfo: { name: 'aegisai-harness', version: '0.30.0' } }),
9
+ initialize: async (params) => ({ protocolVersion: 1, capabilities: { prompt: true, cancel: true }, agentInfo: { name: 'aegisai-harness', version: require('./version').VERSION } }),
10
10
  'session/new': async (params) => {
11
11
  const id = 'acp_' + Date.now();
12
12
  sessions.set(id, { cwd: (params && params.cwd) || process.cwd(), messages: [] });
@@ -4,11 +4,17 @@ const { bus } = require('./event_bus');
4
4
 
5
5
  const clients = new Set();
6
6
 
7
- function subscribe(res) {
7
+ // Subscribe an SSE response. Pass the request so disconnects are cleaned up
8
+ // automatically (otherwise every closed tab leaks a listener + socket).
9
+ function subscribe(res, req) {
8
10
  res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
9
11
  res.write(': connected\n\n');
10
12
  clients.add(res);
11
- return () => clients.delete(res);
13
+ const cleanup = () => { clients.delete(res); try { res.end(); } catch (e) {} };
14
+ res.on('close', cleanup);
15
+ res.on('error', cleanup);
16
+ if (req) { req.on('close', cleanup); req.on('aborted', cleanup); }
17
+ return cleanup;
12
18
  }
13
19
  function broadcast(event, data) {
14
20
  const payload = 'event: ' + event + '\ndata: ' + JSON.stringify(data || {}) + '\n\n';
package/src/index.js CHANGED
@@ -114,6 +114,7 @@ async function main() {
114
114
  tui.addMessage('assistant', (r.final && r.final.final) || '(no reply)');
115
115
  } catch (e) { tui.addMessage('assistant', 'Error: ' + (e.message || e)); }
116
116
  });
117
+ tui.on('exit', () => { try { process.exit(0); } catch (e) {} });
117
118
  return;
118
119
  }
119
120
 
@@ -156,13 +157,43 @@ async function main() {
156
157
  const rateWindow = parseInt(process.env.AEGISAI_RATE_WINDOW || '60', 10) * 1000;
157
158
  const rateHits = new Map();
158
159
  const sessions = new Map(); // session id -> messages array
160
+ const sessionToolLogs = new Map(); // session id -> last tool log (for /api/context)
161
+ const sessionUpdated = new Map(); // session id -> ISO timestamp
162
+ const warnMissing = (v) => String(v || 'default');
163
+
164
+ // Session persistence: in-memory cache + SQLite fallback so history survives restarts.
165
+ let dbMod = null;
166
+ function dbSafe() { if (!dbMod) { try { dbMod = require('./storage/db'); dbMod.get(); } catch (e) { dbMod = null; } } return dbMod; }
167
+ function rememberSession(sid, msgs) {
168
+ sessions.set(sid, msgs);
169
+ sessionUpdated.set(sid, new Date().toISOString());
170
+ try {
171
+ const firstUser = (msgs || []).find((m) => m.role === 'user');
172
+ const d = dbSafe();
173
+ if (d) d.saveSession({ id: sid, title: firstUser ? String(firstUser.content || '').slice(0, 60) : sid, messages: msgs });
174
+ } catch (e) {}
175
+ }
176
+ function getSessionMessages(sid) {
177
+ if (sessions.has(sid)) return sessions.get(sid);
178
+ try { const d = dbSafe(); const s = d && d.getSession(sid); if (s) { sessions.set(sid, s.messages || []); return s.messages || []; } } catch (e) {}
179
+ return [];
180
+ }
159
181
  const pendingActions = new Map();
160
182
 
161
183
  function readJson(req) {
184
+ const MAX_BODY = parseInt(process.env.AEGISAI_MAX_BODY_BYTES || '1048576', 10); // 1 MiB default
162
185
  return new Promise((resolve, reject) => {
163
186
  let body = '';
164
- req.on('data', (c) => { body += c; });
165
- req.on('end', () => { try { resolve(JSON.parse(body || '{}')); } catch (e) { reject(e); } });
187
+ let bytes = 0;
188
+ let aborted = false;
189
+ req.on('data', (c) => {
190
+ if (aborted) return;
191
+ bytes += c.length;
192
+ if (bytes > MAX_BODY) { aborted = true; reject(Object.assign(new Error('request body too large'), { status: 413 })); req.resume(); return; }
193
+ body += c;
194
+ });
195
+ req.on('error', (e) => { if (!aborted) { aborted = true; reject(e); } });
196
+ req.on('end', () => { if (aborted) return; try { resolve(JSON.parse(body || '{}')); } catch (e) { reject(Object.assign(e, { status: 400 })); } });
166
197
  });
167
198
  }
168
199
  function sendJson(res, status, obj) {
@@ -170,9 +201,17 @@ async function main() {
170
201
  res.end(JSON.stringify(obj));
171
202
  }
172
203
 
173
- const server = http.createServer(async (req, res) => {
174
- // CORS headers (needed for browser fetch with application/json content type)
175
- res.setHeader('Access-Control-Allow-Origin', '*');
204
+ const handleRequest = async (req, res) => {
205
+ // CORS: never wildcard. Reflect only same-host origins; reject cross-site.
206
+ const origin = req.headers.origin;
207
+ const hostHdr = req.headers.host || '';
208
+ if (origin) {
209
+ let originHost = '';
210
+ try { originHost = new URL(origin).host; } catch (e) { originHost = ''; }
211
+ if (originHost && originHost !== hostHdr) { sendJson(res, 403, { error: 'cross-origin request blocked' }); return; }
212
+ res.setHeader('Access-Control-Allow-Origin', origin);
213
+ res.setHeader('Vary', 'Origin');
214
+ }
176
215
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
177
216
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
178
217
  if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
@@ -180,10 +219,19 @@ async function main() {
180
219
  const expectedToken = currentToken();
181
220
  if (expectedToken) {
182
221
  const supplied = (req.headers['authorization'] || '').replace(/^Bearer\s+/i, '') || new URL(req.url, 'http://x').searchParams.get('token') || '';
183
- if (!tokenMatches(supplied, expectedToken)) { sendJson(res, 401, { error: 'unauthorized' }); return; }
222
+ if (!tokenMatches(supplied, expectedToken)) {
223
+ // A valid personal access token (PAT) may stand in for the global token.
224
+ let patOk = false;
225
+ try {
226
+ const pats = require('./access_tokens');
227
+ const v = pats.verify ? pats.verify(supplied) : null;
228
+ patOk = Boolean(v && (v.ok !== false));
229
+ } catch (e) { patOk = false; }
230
+ if (!patOk) { sendJson(res, 401, { error: 'unauthorized' }); return; }
231
+ }
184
232
  }
185
- // rate limit
186
- if (rateLimit > 0) {
233
+ // rate limit — API only; static assets must not consume the API budget
234
+ if (rateLimit > 0 && req.url.split('?')[0].startsWith('/api/')) {
187
235
  const ip = req.socket.remoteAddress || 'unknown';
188
236
  const now = Date.now();
189
237
  const arr = (rateHits.get(ip) || []).filter((t) => now - t < rateWindow);
@@ -195,30 +243,37 @@ async function main() {
195
243
  if (req.method === 'POST' && req.url.split('?')[0] === '/api/chat') {
196
244
  const parsed = await readJson(req);
197
245
  const sid = parsed.sessionId || 'default';
198
- const history = Array.isArray(parsed.history) ? parsed.history : (sessions.get(sid) || []);
246
+ const history = Array.isArray(parsed.history) ? parsed.history : getSessionMessages(sid);
199
247
  const stream = parsed.stream === true;
200
248
  const autoApprove = process.env.AEGISAI_WEB_AUTO_APPROVE === 'true';
201
249
  if (stream) {
202
- res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
250
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' });
203
251
  let fullReply = '';
204
- const result = await runAgent({
205
- model: parsed.model || process.env.AEGISAI_MODEL || 'llama3.2:3b',
206
- messages: history.concat([{ role: 'user', content: parsed.message || '' }]),
207
- projectRoot: process.cwd(),
208
- onEvent: (e) => {
209
- if (e.type === 'token') { fullReply += (e.content || ''); res.write('data: ' + JSON.stringify({ type: 'token', content: e.content || '' }) + '\\n\\n'); }
210
- else if (e.type === 'tool_call') { res.write('data: ' + JSON.stringify({ type: 'tool_call', name: e.name, args: e.args }) + '\\n\\n'); }
211
- else if (e.type === 'tool_result') { res.write('data: ' + JSON.stringify({ type: 'tool_result', preview: (e.preview || '').slice(0, 200) }) + '\\n\\n'); }
212
- else if (e.type === 'status') { res.write('data: ' + JSON.stringify({ type: 'status', message: e.message }) + '\\n\\n'); }
213
- },
214
- autoApprove,
215
- approvalHandler: async () => false,
216
- });
217
- const reply = (result.final && result.final.final) || fullReply;
218
- const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
219
- sessions.set(sid, updated);
220
- res.write('data: ' + JSON.stringify({ type: 'done', reply, toolLog: result.toolLog || [] }) + '\\n\\n');
221
- res.end();
252
+ const writeEvent = (obj) => { try { if (!res.writableEnded && !res.destroyed) res.write('data: ' + JSON.stringify(obj) + '\n\n'); } catch (e) {} };
253
+ try {
254
+ const result = await runAgent({
255
+ model: parsed.model || process.env.AEGISAI_MODEL || 'llama3.2:3b',
256
+ messages: history.concat([{ role: 'user', content: parsed.message || '' }]),
257
+ projectRoot: process.cwd(),
258
+ onEvent: (e) => {
259
+ if (e.type === 'token') { fullReply += (e.content || ''); writeEvent({ type: 'token', content: e.content || '' }); }
260
+ else if (e.type === 'tool_call') { writeEvent({ type: 'tool_call', name: e.name, args: e.args }); }
261
+ else if (e.type === 'tool_result') { writeEvent({ type: 'tool_result', preview: (e.preview || '').slice(0, 200) }); }
262
+ else if (e.type === 'status') { writeEvent({ type: 'status', message: e.message }); }
263
+ },
264
+ autoApprove,
265
+ approvalHandler: async () => false,
266
+ });
267
+ const reply = (result.final && result.final.final) || fullReply;
268
+ const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
269
+ rememberSession(sid, updated);
270
+ sessionToolLogs.set(sid, result.toolLog || []);
271
+ writeEvent({ type: 'done', reply, toolLog: result.toolLog || [] });
272
+ } catch (err) {
273
+ // Headers already sent: emit an SSE error frame instead of a JSON 500.
274
+ writeEvent({ type: 'error', message: String((err && err.message) || err) });
275
+ }
276
+ try { if (!res.writableEnded) res.end(); } catch (e) {}
222
277
  return;
223
278
  }
224
279
  const result = await runAgent({
@@ -232,7 +287,9 @@ async function main() {
232
287
  });
233
288
  const reply = (result.final && result.final.final) || '';
234
289
  const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
235
- sessions.set(sid, updated);
290
+ rememberSession(sid, updated);
291
+ sessionToolLogs.set(sid, result.toolLog || []);
292
+ sessionUpdated.set(sid, new Date().toISOString());
236
293
  sendJson(res, 200, { reply, toolLog: result.toolLog || [], pendingActions: pendingActions.get(sid) || [] });
237
294
  return;
238
295
  }
@@ -284,7 +341,7 @@ async function main() {
284
341
  if (req.method === 'POST' && req.url.split('?')[0] === '/api/export') {
285
342
  const parsed = await readJson(req);
286
343
  const sid = parsed.sessionId || 'default';
287
- const history = sessions.get(sid) || [];
344
+ const history = getSessionMessages(sid);
288
345
  const format = parsed.format || 'markdown';
289
346
  const meta = { title: parsed.title, model: process.env.AEGISAI_MODEL || 'llama3.2:3b', date: new Date().toISOString() };
290
347
  const result = require('./conversation_export').exportToFile(history.map((m) => ({ role: m.role, content: m.content })), meta, format, null);
@@ -303,7 +360,7 @@ async function main() {
303
360
  let results = [];
304
361
  try {
305
362
  // Search without filter first, then filter for gguf client-side
306
- const r = await fetch('https://huggingface.co/api/models?search=' + encodeURIComponent(q) + '&sort=downloads&direction=-1&limit=30');
363
+ const r = await fetch('https://huggingface.co/api/models?search=' + encodeURIComponent(q) + '&sort=downloads&direction=-1&limit=30', { signal: AbortSignal.timeout(15000) });
307
364
  if (r.ok) {
308
365
  const data = await r.json();
309
366
  const all = Array.isArray(data) ? data : [];
@@ -323,43 +380,6 @@ async function main() {
323
380
  sendJson(res, 200, { results, query: q });
324
381
  return;
325
382
  }
326
- if (req.method === 'GET' && req.url.split('?')[0] === '/api/models/scan') {
327
- const roots = new URL(req.url, 'http://x').searchParams.get('roots');
328
- const rootList = roots ? roots.split(',') : undefined;
329
- const backend = require('./backends').getType();
330
- const found = require('./model_discovery').scan(rootList, 500, backend);
331
- // Also list models from the active backend
332
- try {
333
- const r = await require('./backends').backendListModels();
334
- const backendModels = (r.models || []).map((m) => ({ path: backend + '://' + (m.name || m), name: m.name || m, sizeGB: m.size ? +(m.size / 1024 ** 3).toFixed(2) : 0, type: backend }));
335
- // Only add if not already in found
336
- const existingNames = new Set(found.map((f) => f.name));
337
- for (const bm of backendModels) {
338
- if (!existingNames.has(bm.name)) found.push(bm);
339
- }
340
- } catch (e) {}
341
- sendJson(res, 200, { models: found, backend });
342
- return;
343
- }
344
- if (req.method === 'GET' && req.url.split('?')[0] === '/api/models/hf-search') {
345
- const q = new URL(req.url, 'http://x').searchParams.get('q') || '';
346
- // Simple HuggingFace search via their API
347
- let results = [];
348
- try {
349
- const r = await fetch('https://huggingface.co/api/models?search=' + encodeURIComponent(q) + '&filter=gguf&sort=downloads&direction=-1&limit=20');
350
- if (r.ok) {
351
- const data = await r.json();
352
- results = (Array.isArray(data) ? data : []).map((m) => ({
353
- id: m.id || m.modelId,
354
- downloads: m.downloads || 0,
355
- likes: m.likes || 0,
356
- tags: m.tags || [],
357
- }));
358
- }
359
- } catch (e) {}
360
- sendJson(res, 200, { results });
361
- return;
362
- }
363
383
  if (req.method === 'POST' && req.url.split('?')[0] === '/api/models/pull') {
364
384
  const parsed = await readJson(req);
365
385
  let ok = false;
@@ -378,7 +398,7 @@ async function main() {
378
398
  sendJson(res, 200, { ok: true });
379
399
  return;
380
400
  }
381
- } catch (e) { sendJson(res, 500, { error: String(e.message || e) }); return; }
401
+ } catch (e) { sendJson(res, (e && e.status) || 500, { error: String(e.message || e) }); return; }
382
402
 
383
403
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/stream') {
384
404
  const u = new URL(req.url, 'http://x');
@@ -389,7 +409,8 @@ async function main() {
389
409
  const tokenizer = require('./tokenizer');
390
410
  const sid = new URL(req.url, 'http://x').searchParams.get('session') || 'default';
391
411
  const tokens = tokenizer.countMessages(sessions.get(sid) || []);
392
- sendJson(res, 200, { tokens, limit: 8192, ratio: +(tokens / 8192).toFixed(3), compacted: (lastToolLog || []).some((t) => t.name === '__compact__') });
412
+ const tl = sessionToolLogs.get(sid) || [];
413
+ sendJson(res, 200, { tokens, limit: 8192, ratio: +(tokens / 8192).toFixed(3), compacted: tl.some((t) => t.name === '__compact__') });
393
414
  return;
394
415
  }
395
416
  if (req.url.split('?')[0] === '/mcp') {
@@ -457,8 +478,39 @@ async function main() {
457
478
  sendJson(res, 200, { events: require('./event_bus').bus.events() });
458
479
  return;
459
480
  }
481
+ if (req.method === 'GET' && req.url.split('?')[0] === '/api/sessions') {
482
+ const u = new URL(req.url, 'http://x');
483
+ const wantId = u.searchParams.get('id');
484
+ if (wantId) {
485
+ const sid = warnMissing(wantId);
486
+ const msgs = getSessionMessages(sid);
487
+ sendJson(res, 200, { id: sid, messages: msgs });
488
+ return;
489
+ }
490
+ const byId = new Map();
491
+ // Persisted sessions first (survive restarts).
492
+ try {
493
+ const d = dbSafe();
494
+ for (const s of (d ? d.listSessions() : [])) {
495
+ byId.set(s.id, { id: s.id, title: s.title || s.id, messages: (s.messages || []).length, updated: s.updated || null });
496
+ }
497
+ } catch (e) {}
498
+ // Merge live in-memory sessions (fresher).
499
+ for (const [id, msgs] of sessions.entries()) {
500
+ const firstUser = (msgs || []).find((m) => m.role === 'user');
501
+ byId.set(id, {
502
+ id,
503
+ title: firstUser ? String(firstUser.content || '').slice(0, 60) : id,
504
+ messages: (msgs || []).length,
505
+ updated: sessionUpdated.get(id) || (byId.get(id) || {}).updated || null,
506
+ });
507
+ }
508
+ const list = Array.from(byId.values()).sort((a, b) => String(b.updated || '').localeCompare(String(a.updated || '')));
509
+ sendJson(res, 200, { sessions: list });
510
+ return;
511
+ }
460
512
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/events') {
461
- require('./event_stream').subscribe(res);
513
+ require('./event_stream').subscribe(res, req);
462
514
  return;
463
515
  }
464
516
  try {
@@ -509,6 +561,8 @@ async function main() {
509
561
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/version') {
510
562
  const v = require('./updater');
511
563
  let info = v.checkLocal();
564
+ if (!info || typeof info !== 'object') info = {};
565
+ info.version = require('./version').VERSION;
512
566
  try { info.node = process.version; } catch (e) {}
513
567
  sendJson(res, 200, info);
514
568
  return;
@@ -551,7 +605,7 @@ async function main() {
551
605
  }
552
606
  if (req.method === 'POST' && req.url.split('?')[0] === '/api/config') {
553
607
  const parsed = await readJson(req);
554
- if (parsed.projectRootAllowlist) process.env.AEGISAI_PROJECT_ROOT_ALLOWLIST = parsed.projectRootAllowlist;
608
+ if (parsed.projectRootAllowlist !== undefined) process.env.AEGISAI_PROJECT_ROOT_ALLOWLIST = parsed.projectRootAllowlist;
555
609
  if (parsed.sttUrl !== undefined) process.env.STT_URL = parsed.sttUrl;
556
610
  if (parsed.ttsUrl !== undefined) process.env.TTS_URL = parsed.ttsUrl;
557
611
  for (const k of ['BACKEND_TYPE', 'BACKEND_URL', 'AEGISAI_MODEL', 'AEGISAI_TOKEN', 'AEGISAI_WEB_AUTO_APPROVE', 'REA_BIN', 'GHIDRA_MCP_URL', 'CRAFT_BIN']) {
@@ -565,10 +619,12 @@ async function main() {
565
619
  const url = process.env.STT_URL;
566
620
  if (!url) { sendJson(res, 400, { error: 'STT_URL not configured' }); return; }
567
621
  try {
622
+ const MAX_AUDIO = parseInt(process.env.AEGISAI_MAX_AUDIO_BYTES || '26214400', 10); // 25 MiB
568
623
  const chunks = [];
569
- for await (const c of req) chunks.push(c);
624
+ let total = 0;
625
+ for await (const c of req) { total += c.length; if (total > MAX_AUDIO) { sendJson(res, 413, { error: 'audio too large' }); return; } chunks.push(c); }
570
626
  const body = Buffer.concat(chunks);
571
- const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': req.headers['content-type'] || 'audio/webm' }, body });
627
+ const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': req.headers['content-type'] || 'audio/webm' }, body, signal: AbortSignal.timeout(60000) });
572
628
  const data = await r.json();
573
629
  sendJson(res, 200, { text: data.text || '' });
574
630
  } catch (e) { sendJson(res, 500, { error: String(e.message || e) }); }
@@ -595,7 +651,17 @@ async function main() {
595
651
  res.writeHead(200, { 'Content-Type': ct });
596
652
  res.end(fs.readFileSync(filePath));
597
653
  } else { res.writeHead(404); res.end(); }
654
+ };
655
+ const server = http.createServer((req, res) => {
656
+ handleRequest(req, res).catch((e) => {
657
+ try {
658
+ if (!res.headersSent) sendJson(res, (e && e.status) || 500, { error: String((e && e.message) || e) });
659
+ else res.end();
660
+ } catch (_) { try { res.end(); } catch (__) {} }
661
+ });
598
662
  });
663
+ // Never let a stray rejection kill the web server.
664
+ process.on('unhandledRejection', (e) => { try { console.error('[unhandledRejection]', (e && e.stack) || e); } catch (_) {} });
599
665
  server.listen(port, host, () => console.log('Web UI at http://' + host + ':' + port));
600
666
  return;
601
667
  }
@@ -628,37 +694,91 @@ async function main() {
628
694
  if (proxyFlag) {
629
695
  const http = require('http');
630
696
  const port = parseInt(process.env.AEGISAI_PROXY_PORT || '4000', 10);
697
+ const host = process.env.HOST || '127.0.0.1';
698
+ const MAX_BODY = parseInt(process.env.AEGISAI_PROXY_MAX_BODY || String(10 * 1024 * 1024), 10);
699
+ const proxyToken = () => process.env.AEGISAI_TOKEN || process.env.LOCALAI_TOKEN || '';
700
+ const sendErr = (res, status, message, type) => {
701
+ try { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message, type: type || 'invalid_request_error' } })); } catch (e) {}
702
+ };
631
703
  const server = http.createServer(async (req, res) => {
632
- if (req.method === 'POST' && req.url.includes('/chat/completions')) {
704
+ const urlPath = req.url.split('?')[0];
705
+ // Auth when a token is configured.
706
+ const expected = proxyToken();
707
+ if (expected) {
708
+ const supplied = (req.headers['authorization'] || '').replace(/^Bearer\s+/i, '') || new URL(req.url, 'http://x').searchParams.get('token') || '';
709
+ if (!tokenMatches(supplied, expected)) { sendErr(res, 401, 'unauthorized', 'authentication_error'); return; }
710
+ }
711
+ if (req.method === 'GET' && (urlPath === '/v1/models' || urlPath === '/models')) {
712
+ let ids = [];
713
+ try { const r = await require('./backends').backendListModels(); ids = (r.models || []).map((m) => m.name || m); } catch (e) {}
714
+ if (!ids.length) ids = [process.env.AEGISAI_MODEL || 'llama3.2:3b'];
715
+ res.writeHead(200, { 'Content-Type': 'application/json' });
716
+ res.end(JSON.stringify({ object: 'list', data: ids.map((id) => ({ id, object: 'model', owned_by: 'aegisai' })) }));
717
+ return;
718
+ }
719
+ if (req.method === 'POST' && (urlPath === '/v1/chat/completions' || urlPath === '/chat/completions')) {
633
720
  let body = '';
634
- let aborted = false;
635
- req.on('aborted', () => { aborted = true; });
636
- req.on('close', () => { if (!req.complete) aborted = true; });
637
- req.on('data', (c) => { body += c; });
721
+ let bytes = 0;
722
+ let tooBig = false;
723
+ req.on('data', (c) => {
724
+ if (tooBig) return;
725
+ bytes += c.length;
726
+ if (bytes > MAX_BODY) { tooBig = true; sendErr(res, 413, 'request body too large'); return; }
727
+ body += c;
728
+ });
638
729
  req.on('end', async () => {
730
+ if (tooBig) return;
731
+ let parsed;
732
+ try { parsed = JSON.parse(body); } catch (e) { sendErr(res, 400, 'invalid JSON body'); return; }
733
+ const model = parsed.model || process.env.AEGISAI_MODEL || 'llama3.2:3b';
734
+ if (parsed.stream) {
735
+ let headersSent = false;
736
+ const send = (obj) => {
737
+ try {
738
+ if (!headersSent) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }); headersSent = true; }
739
+ if (!res.writableEnded) res.write('data: ' + JSON.stringify(obj) + '\n\n');
740
+ } catch (e) {}
741
+ };
742
+ try {
743
+ let text = '';
744
+ await runAgent({
745
+ model,
746
+ messages: parsed.messages || [],
747
+ projectRoot: process.cwd(),
748
+ onEvent: (e) => {
749
+ if (e.type === 'token' && e.content) {
750
+ text += e.content;
751
+ send({ id: 'chatcmpl-x', object: 'chat.completion.chunk', created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: { content: e.content }, finish_reason: null }] });
752
+ }
753
+ },
754
+ autoApprove: true,
755
+ });
756
+ send({ id: 'chatcmpl-x', object: 'chat.completion.chunk', created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] });
757
+ try { if (!res.writableEnded) { res.write('data: [DONE]\n\n'); res.end(); } } catch (e) {}
758
+ } catch (e) {
759
+ if (!headersSent) sendErr(res, 500, String(e.message || e), 'server_error');
760
+ else { try { res.write('data: [DONE]\n\n'); res.end(); } catch (_) {} }
761
+ }
762
+ return;
763
+ }
639
764
  try {
640
- const parsed = JSON.parse(body);
641
- if (aborted) return;
642
765
  const result = await runAgent({
643
- model: parsed.model || process.env.AEGISAI_MODEL || 'llama3.2:3b',
766
+ model,
644
767
  messages: parsed.messages || [],
645
768
  projectRoot: process.cwd(),
646
769
  onEvent: () => {},
647
770
  autoApprove: true,
648
771
  });
649
- const resp = { id: 'chatcmpl-' + Date.now(), object: 'chat.completion', created: Math.floor(Date.now() / 1000), model: parsed.model, choices: [{ index: 0, message: { role: 'assistant', content: (result.final && result.final.final) || '' }, finish_reason: 'stop' }] };
772
+ const resp = { id: 'chatcmpl-' + Date.now(), object: 'chat.completion', created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, message: { role: 'assistant', content: (result.final && result.final.final) || '' }, finish_reason: 'stop' }] };
650
773
  res.writeHead(200, { 'Content-Type': 'application/json' });
651
774
  res.end(JSON.stringify(resp));
652
- } catch (e) {
653
- res.writeHead(500, { 'Content-Type': 'application/json' });
654
- res.end(JSON.stringify({ error: String(e.message || e) }));
655
- }
775
+ } catch (e) { sendErr(res, 500, String(e.message || e), 'server_error'); }
656
776
  });
657
- } else {
658
- res.writeHead(404); res.end();
777
+ return;
659
778
  }
779
+ sendErr(res, 404, 'not found', 'invalid_request_error');
660
780
  });
661
- server.listen(port, () => console.log('Proxy listening on :' + port));
781
+ server.listen(port, host, () => console.log('Proxy listening on http://' + host + ':' + port));
662
782
  return;
663
783
  }
664
784
 
@@ -692,10 +812,36 @@ async function main() {
692
812
  };
693
813
  rl.prompt();
694
814
  rl.on('line', async (line) => {
815
+ try {
695
816
  const t = line.trim();
696
817
  if (!t) { rl.prompt(); return; }
697
818
  if (t === '/exit' || t === '/quit') { rl.close(); return; }
698
- if (t === '/help') { console.log('Commands: /exit, /model <name>, /root <path>, /sandbox on|off, /autoapprove on|off, /offline on|off, /agent <name>, /index, /replay <sessionId>, /health, /backup <file>, /restore <file>, /vault set|get|list|delete ..., /eval add|run|list, /traces'); rl.prompt(); return; }
819
+ if (t === '/help') {
820
+ const groups = [
821
+ ['Session', ['/exit', '/model <name>', '/root <path>', '/sandbox on|off', '/autoapprove on|off', '/offline on|off', '/agent <name>', '/plan <goal>']],
822
+ ['Index & replay', ['/index', '/replay <sessionId>', '/traces', '/search-sessions <q>', '/session-export <id>|<format>']],
823
+ ['Health & data', ['/health', '/backup <file>', '/restore <file>', '/vault set|get|list|delete ...', '/metrics', '/score', '/reliability']],
824
+ ['Eval & bench', ['/eval add|run|list', '/pass-at-k', '/bench <models...>', '/failure-clusters', '/lint', '/stress']],
825
+ ['Models', ['/providers', '/provider-list', '/model-scan', '/models', '/cheapest <prompt>', '/cost-route', '/routing-eval']],
826
+ ['Memory', ['/remember <text>', '/recall <q>', '/reflect', '/sremember', '/srecall', '/tremember', '/tasof', '/memory-graph', '/habits', '/geo-wake', '/mem-reindex']],
827
+ ['Memory (graph)', ['/graph-observe', '/graph-recall', '/graph-prompt', '/mem-md-search', '/memory-hierarchy']],
828
+ ['Governance', ['/charter', '/governance', '/constitution', '/constitution-propose', '/constitution-decide', '/policy', '/auto-rules', '/ahp-check', '/security-layers', '/identity-list']],
829
+ ['Audit & evidence', ['/ledger-verify', '/ledger-replay', '/ledger-rewind', '/merkle-root', '/evidence-bundle', '/contract-save', '/contract-check', '/contracts', '/honesty', '/waste', '/diagnose', '/evolve']],
830
+ ['Orchestration', ['/dag <json|file>', '/dag-runs', '/critique <text>', '/board', '/board-add', '/task-create', '/task-update', '/tasks', '/team-create', '/team-run', '/teams', '/swarm <plan>', '/schedule', '/sched-tick']],
831
+ ['Tools', ['/tools', '/tool-contract', '/tool-eval', '/tool-state', '/equipment', '/equipment-add', '/semantic-tools <q>', '/mcp-pins', '/mcp-registry', '/mcp-market']],
832
+ ['Security & RE', ['/vuln-scan <path>', '/security-kb', '/sarif <path>', '/pentest <target>', '/rea-status', '/ghidra-status', '/craft-status', '/re-search <q>', '/re-categories', '/re-online <q>']],
833
+ ['Browser & web', ['/browser-targets', '/browser-nav <url>', '/browser-snapshot', '/browser-eval <js>', '/extract <url>', '/search <q>', '/multi-search <q>', '/fetch <url>', '/squeeze <url>|<q>']],
834
+ ['Workspace', ['/git-status', '/git-diff', '/git-branch', '/git-log', '/git-stash', '/git-show', '/diff-review', '/review-start', '/project-create', '/projects', '/project-add-doc', '/ctxfs', '/files']],
835
+ ['Misc', ['/time', '/export <format>|<title>', '/compare <prompt>|<model1>|<model2>', '/ui-record', '/ui-replay', '/plugins-ui', '/dag-ui', '/trajectory-ui', '/backup', '/help']],
836
+ ];
837
+ console.log('\nAegisAi Harness — command reference\n');
838
+ for (const [g, cmds] of groups) {
839
+ console.log(g + ':');
840
+ console.log(' ' + cmds.join(', '));
841
+ }
842
+ console.log('\nType /<command> to run. Many commands accept "|" separated arguments.');
843
+ rl.prompt(); return;
844
+ }
699
845
  if (t.startsWith('/model ')) { model = t.slice(7).trim(); console.log('model =', model); rl.prompt(); return; }
700
846
  if (t.startsWith('/root ')) { root = t.slice(6).trim(); console.log('root =', root); rl.prompt(); return; }
701
847
  if (t.startsWith('/sandbox ')) { sandbox = t.slice(9).trim() === 'on'; console.log('sandbox =', sandbox); rl.prompt(); return; }
@@ -1083,6 +1229,10 @@ async function main() {
1083
1229
  }
1084
1230
  try { await runOne(t); } catch (e) { console.error('error:', e.message || e); }
1085
1231
  rl.prompt();
1232
+ } catch (err) {
1233
+ console.error('[command error]', (err && err.message) || err);
1234
+ try { rl.prompt(); } catch (_) {}
1235
+ }
1086
1236
  });
1087
1237
  rl.on('close', () => { db.close(); process.exit(0); });
1088
1238
  return;
@@ -80,7 +80,11 @@ function scan(roots, maxFiles, backend) {
80
80
  } else if (extensions.test(e.name)) {
81
81
  let size = 0;
82
82
  try { size = fs.statSync(p).size; } catch (err) {}
83
- found.push({ path: p, name: e.name, sizeGB: +(size / 1024 ** 3).toFixed(2), type: path.extname(e.name).slice(1).toLowerCase() });
83
+ const ext = path.extname(e.name).slice(1).toLowerCase();
84
+ // `.bin` is used by many non-model artefacts; require a model-sized file.
85
+ const MIN_BIN_BYTES = 50 * 1024 * 1024;
86
+ if (ext === 'bin' && size < MIN_BIN_BYTES) continue;
87
+ found.push({ path: p, name: e.name, sizeGB: +(size / 1024 ** 3).toFixed(2), type: ext });
84
88
  count += 1;
85
89
  }
86
90
  }
@@ -120,9 +124,3 @@ function huggingFacePull(repo, filename) {
120
124
  }
121
125
 
122
126
  module.exports = { ROOTS: [], getDefaultRoots, scan, huggingFacePull };
123
- function huggingFacePull(repo, filename) {
124
- const url = 'https://huggingface.co/' + repo + '/resolve/main/' + (filename || '');
125
- return { ok: true, url, note: 'streaming download not implemented; open URL or use huggingface-cli' };
126
- }
127
-
128
- // (duplicate removed)
package/src/projects.js CHANGED
@@ -5,27 +5,65 @@ const path = require('path');
5
5
  const { DATA_DIR } = require('./core/config');
6
6
 
7
7
  function dir() { return path.join(DATA_DIR, 'projects'); }
8
+
9
+ // Reject traversal/absolute paths for project names.
10
+ function safeName(name) {
11
+ if (typeof name !== 'string') throw Object.assign(new Error('project name must be a string'), { status: 400 });
12
+ const n = name.trim();
13
+ if (!n) throw Object.assign(new Error('project name is required'), { status: 400 });
14
+ if (n.includes('..') || n.includes('/') || n.includes('\\') || n.includes('\0') || path.isAbsolute(n)) {
15
+ throw Object.assign(new Error('invalid project name (no path separators or "..")'), { status: 400 });
16
+ }
17
+ return n;
18
+ }
19
+
20
+ // Reject anything that isn't a plain filename for documents.
21
+ function safeFilename(filename) {
22
+ if (typeof filename !== 'string') throw Object.assign(new Error('filename must be a string'), { status: 400 });
23
+ const f = path.basename(filename.trim());
24
+ if (!f || f === '.' || f === '..' || f.includes('\0')) {
25
+ throw Object.assign(new Error('invalid filename'), { status: 400 });
26
+ }
27
+ return f;
28
+ }
29
+
30
+ // Ensure the resolved target stays inside the projects base.
31
+ function resolveInside(base, target) {
32
+ const resolvedBase = path.resolve(base);
33
+ const resolved = path.resolve(resolvedBase, target);
34
+ const rel = path.relative(resolvedBase, resolved);
35
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
36
+ throw Object.assign(new Error('path escapes projects directory'), { status: 400 });
37
+ }
38
+ return resolved;
39
+ }
40
+
8
41
  function create(name, instructions) {
9
- const p = path.join(dir(), name);
42
+ const n = safeName(name);
43
+ const p = resolveInside(dir(), n);
10
44
  fs.mkdirSync(p, { recursive: true });
11
45
  fs.mkdirSync(path.join(p, 'docs'), { recursive: true });
12
- fs.writeFileSync(path.join(p, 'instructions.md'), instructions || '# ' + name + '\n');
13
- return { name, path: p };
46
+ fs.writeFileSync(path.join(p, 'instructions.md'), instructions || '# ' + n + '\n');
47
+ return { name: n, path: p };
14
48
  }
15
49
  function get(name) {
16
- const p = path.join(dir(), name);
50
+ const n = safeName(name);
51
+ const p = resolveInside(dir(), n);
17
52
  if (!fs.existsSync(p)) return null;
18
53
  let instructions = '';
19
54
  try { instructions = fs.readFileSync(path.join(p, 'instructions.md'), 'utf8'); } catch (e) {}
20
55
  let shelf = [];
21
56
  try { shelf = fs.readdirSync(path.join(p, 'docs')).filter((f) => f.endsWith('.md') || f.endsWith('.txt')); } catch (e) {}
22
- return { name, path: p, instructions, shelf };
57
+ return { name: n, path: p, instructions, shelf };
23
58
  }
24
59
  function addDoc(name, filename, content) {
25
- const p = path.join(dir(), name, 'docs', filename);
60
+ const n = safeName(name);
61
+ const f = safeFilename(filename);
62
+ const base = resolveInside(dir(), n);
63
+ const p = resolveInside(path.join(base, 'docs'), f);
26
64
  fs.mkdirSync(path.dirname(p), { recursive: true });
27
65
  fs.writeFileSync(p, content || '');
28
- return { name, file: filename };
66
+ return { name: n, file: f };
29
67
  }
30
68
  function list() {
31
69
  try { return fs.readdirSync(dir()).filter((d) => fs.statSync(path.join(dir(), d)).isDirectory()); } catch (e) { return []; }
@@ -36,7 +74,7 @@ function systemText(name) {
36
74
  const docs = p.shelf.map((f) => {
37
75
  try { return '### ' + f + '\n' + fs.readFileSync(path.join(p.path, 'docs', f), 'utf8').slice(0, 4000); } catch (e) { return ''; }
38
76
  }).filter(Boolean);
39
- return 'Project: ' + name + '\n\n' + p.instructions + (docs.length ? '\n\n## Document shelf\n\n' + docs.join('\n\n---\n\n') : '');
77
+ return 'Project: ' + p.name + '\n\n' + p.instructions + (docs.length ? '\n\n## Document shelf\n\n' + docs.join('\n\n---\n\n') : '');
40
78
  }
41
79
 
42
- module.exports = { create, get, addDoc, list, systemText };
80
+ module.exports = { create, get, addDoc, list, systemText, safeName, safeFilename };
package/src/storage/db.js CHANGED
@@ -167,7 +167,7 @@ function rowToSession(r) {
167
167
  try { messages = JSON.parse(r.messages || '[]'); } catch (e) { messages = []; }
168
168
  return { id: r.id, title: r.title, updated: r.updated, parent_id: r.parent_id, branch_from: r.branch_from, messages };
169
169
  }
170
- function listSessions() { return all('SELECT id, title, updated, parent_id, branch_from FROM sessions ORDER BY updated DESC').map(rowToSession); }
170
+ function listSessions() { return all('SELECT * FROM sessions ORDER BY updated DESC').map(rowToSession); }
171
171
  function getSession(id) { const row = one('SELECT * FROM sessions WHERE id = ?', [id]); return row ? rowToSession(row) : null; }
172
172
  function saveSession(s) {
173
173
  const id = s.id || ('sess_' + Date.now());
package/src/tui.js CHANGED
@@ -28,24 +28,37 @@ class Tui extends EventEmitter {
28
28
  }
29
29
  start() {
30
30
  this.running = true;
31
+ this._stopped = false;
31
32
  process.stdout.write(ANSI.hideCursor + ANSI.clear);
32
33
  this.render();
33
34
  this.rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true, prompt: '' });
34
35
  process.stdin.setRawMode && process.stdin.setRawMode(true);
35
- process.stdin.on('data', (d) => this.handleKey(d));
36
- process.on('SIGWINCH', () => this.render());
37
- process.on('SIGINT', () => this.stop());
36
+ this._onData = (d) => this.handleKey(d);
37
+ this._onResize = () => this.render();
38
+ this._onSigint = () => this.stop();
39
+ process.stdin.on('data', this._onData);
40
+ process.on('SIGWINCH', this._onResize);
41
+ process.on('SIGINT', this._onSigint);
38
42
  }
39
43
  stop() {
44
+ if (this._stopped) return;
45
+ this._stopped = true;
40
46
  this.running = false;
47
+ // Detach listeners so the process can exit after Ctrl+C.
48
+ try { if (this._onData) process.stdin.off('data', this._onData); } catch (e) {}
49
+ try { if (this._onResize) process.off('SIGWINCH', this._onResize); } catch (e) {}
50
+ try { if (this._onSigint) process.off('SIGINT', this._onSigint); } catch (e) {}
51
+ try { process.stdin.pause(); } catch (e) {}
41
52
  process.stdin.setRawMode && process.stdin.setRawMode(false);
42
53
  process.stdout.write(ANSI.showCursor + ANSI.clear + ANSI.reset);
43
- if (this.rl) this.rl.close();
54
+ if (this.rl) { try { this.rl.close(); } catch (e) {} this.rl = null; }
44
55
  this.emit('exit');
45
56
  }
46
57
  handleKey(d) {
47
58
  const s = d.toString();
59
+ if (!s) return;
48
60
  if (s === '\u0003') { this.stop(); return; } // Ctrl+C
61
+ // Split pasted/multi-byte chunks into lines and printable runs.
49
62
  if (s === '\r' || s === '\n') {
50
63
  const cmd = this.input.trim();
51
64
  this.input = '';
@@ -59,9 +72,26 @@ class Tui extends EventEmitter {
59
72
  this.render();
60
73
  return;
61
74
  }
62
- if (s.startsWith('\x1b[')) return; // ignore arrow keys for now
63
- if (s.length === 1 && s.charCodeAt(0) >= 32) {
64
- this.input += s;
75
+ if (s.startsWith('\x1b[') || s.startsWith('\x1bO')) return; // ignore escape sequences
76
+ // Handle pasted text containing newlines: submit each complete line.
77
+ if (s.includes('\n') || s.includes('\r')) {
78
+ const parts = s.split(/\r\n|\r|\n/);
79
+ for (let i = 0; i < parts.length; i++) {
80
+ if (parts[i]) this.input += parts[i].replace(/[^\x20-\x7e\t]/g, '');
81
+ if (i < parts.length - 1) {
82
+ const cmd = this.input.trim();
83
+ this.input = '';
84
+ this.emit('command', cmd);
85
+ if (cmd) this.addMessage('user', cmd);
86
+ }
87
+ }
88
+ this.render();
89
+ return;
90
+ }
91
+ // Accept the whole printable run (paste support), dropping control chars.
92
+ const printable = s.replace(/[^\x20-\x7e\t]/g, '');
93
+ if (printable) {
94
+ this.input += printable;
65
95
  this.render();
66
96
  }
67
97
  }
package/src/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // src/version.js — single runtime source for the version string.
2
2
  // Kept separate from package.json so bundled/npm-installed copies behave the same.
3
- const VERSION = '0.74.0';
3
+ const VERSION = '0.76.0';
4
4
  module.exports = { VERSION, version: VERSION };