aegisai-harness 0.73.0 → 0.75.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.73.0] - 2026-11-24
5
+ ## [0.75.0] - 2026-11-24
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.73.0 (see [ROADMAP.md](./ROADMAP.md)).
13
+ > Status: v0.75.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.73.0.
3
+ A feature-rich, local-only AI agent harness. CLI-first, offline-first. v0.75.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.73.0",
3
+ "version": "0.75.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.73.0
7
+ AppVersion=0.75.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.73.0-Setup
13
+ OutputBaseFilename=AegisAi-Harness-0.75.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');
@@ -340,10 +378,13 @@ function App() {
340
378
  const [showSessions, setShowSessions] = useState(false);
341
379
  const [cfg, setCfg] = useState({});
342
380
  const [theme, setTheme] = useState(localStorage.getItem('theme') || 'dark');
381
+ const THEMES = ['dark', 'light', 'high-contrast', 'solarized'];
343
382
  const [view, setView] = useState(localStorage.getItem('onboarded') ? 'chat' : 'onboarding');
344
383
  const [toasts, setToasts] = useState([]);
345
384
  const [toolLog, setToolLog] = useState([]);
346
385
  const [dragOver, setDragOver] = useState(false);
386
+ const [needAuth, setNeedAuth] = useState(false);
387
+ const [tokenInput, setTokenInput] = useState('');
347
388
  const inputRef = useRef(null);
348
389
  const chatRef = useRef(null);
349
390
 
@@ -361,6 +402,17 @@ function App() {
361
402
  }, [theme]);
362
403
 
363
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
+ }, []);
411
+ useEffect(() => {
412
+ API('/api/version').then((v) => {
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); });
415
+ }, []);
364
416
 
365
417
  useEffect(() => {
366
418
  const handler = (e) => {
@@ -427,7 +479,7 @@ function App() {
427
479
  // Add empty assistant message for streaming
428
480
  setMessages((m) => [...m, { role: 'assistant', content: '' }]);
429
481
  try {
430
- 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 }) });
431
483
  if (!r.ok) throw new Error('HTTP ' + r.status);
432
484
  const reader = r.body.getReader();
433
485
  const decoder = new TextDecoder();
@@ -487,6 +539,15 @@ function App() {
487
539
  { icon: '⚖️', label: 'Compare Models', keywords: 'compare models', run: () => setShowCompare(true) },
488
540
  ];
489
541
 
542
+ const [showFiles, setShowFiles] = useState(false);
543
+ const [showSearch, setShowSearch] = useState(false);
544
+ const [showShortcuts, setShowShortcuts] = useState(false);
545
+ const [searchQuery, setSearchQuery] = useState('');
546
+ const [searchResults, setSearchResults] = useState([]);
547
+ const [fileDir, setFileDir] = useState('');
548
+ const [fileEntries, setFileEntries] = useState([]);
549
+ const [fileContent, setFileContent] = useState('');
550
+ const [selectedFile, setSelectedFile] = useState('');
490
551
  const [showCompare, setShowCompare] = useState(false);
491
552
  const [compareModels, setCompareModels] = useState('');
492
553
  const [comparePrompt, setComparePrompt] = useState('');
@@ -495,19 +556,43 @@ function App() {
495
556
 
496
557
  async function exportChat(format) {
497
558
  try {
498
- const r = await fetch('/api/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ format, title: 'Chat Export' }) });
559
+ const r = await apiFetch('/api/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ format, title: 'Chat Export' }) });
499
560
  const d = await r.json();
500
561
  if (d.ok) toast('Exported to ' + d.path, 'success');
501
562
  else toast('Export failed: ' + (d.error || 'unknown'), 'error');
502
563
  } catch (e) { toast('Export failed: ' + e.message, 'error'); }
503
564
  }
504
565
 
566
+ async function loadFiles(dir) {
567
+ try {
568
+ const d = await API('/api/files?dir=' + encodeURIComponent(dir || ''));
569
+ setFileDir(d.dir || dir);
570
+ setFileEntries(d.entries || []);
571
+ } catch (e) { toast('Failed to load files: ' + e.message, 'error'); }
572
+ }
573
+
574
+ async function searchConversations() {
575
+ if (!searchQuery.trim()) return;
576
+ try {
577
+ const d = await API('/api/search-sessions?q=' + encodeURIComponent(searchQuery));
578
+ setSearchResults(d.results || []);
579
+ } catch (e) { toast('Search failed: ' + e.message, 'error'); }
580
+ }
581
+
582
+ async function openFile(filePath) {
583
+ try {
584
+ const d = await API('/api/file?path=' + encodeURIComponent(filePath));
585
+ setSelectedFile(filePath);
586
+ setFileContent(d.content || '');
587
+ } catch (e) { toast('Failed to read file: ' + e.message, 'error'); }
588
+ }
589
+
505
590
  async function runCompare() {
506
591
  if (!comparePrompt.trim() || !compareModels.trim()) { toast('Enter a prompt and models', 'error'); return; }
507
592
  setComparing(true);
508
593
  try {
509
594
  const models = compareModels.split(',').map((m) => m.trim()).filter(Boolean);
510
- const r = await fetch('/api/compare', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: comparePrompt, models }) });
595
+ const r = await apiFetch('/api/compare', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: comparePrompt, models }) });
511
596
  const d = await r.json();
512
597
  setCompareResult(d);
513
598
  toast('Comparison complete', 'success');
@@ -525,6 +610,93 @@ function App() {
525
610
  <${CommandPalette} open=${showPalette} onClose=${() => setShowPalette(false)} commands=${commands} />
526
611
  ${showConfig ? html`<${ConfigModal} cfg=${cfg} setCfg=${setCfg} onClose=${() => setShowConfig(false)} />` : null}
527
612
  ${showHelp ? html`<${HelpPanel} onClose=${() => setShowHelp(false)} />` : null}
613
+ ${needAuth ? html`
614
+ <div class="modal-backdrop">
615
+ <div class="modal" onClick=${(e) => e.stopPropagation()}>
616
+ <h2>Authentication Required</h2>
617
+ <p>The server requires an access token. Enter it below (stored in this browser session only).</p>
618
+ <input type="password" value=${tokenInput} onInput=${(e) => setTokenInput(e.target.value)} placeholder="Access token" style="width:100%" />
619
+ <div class="modal-actions">
620
+ <button class="btn-primary" onClick=${() => { setAuthToken(tokenInput.trim()); setNeedAuth(false); setTokenInput(''); toast('Token set', 'success'); updateCtx(); }}>Use Token</button>
621
+ </div>
622
+ </div>
623
+ </div>
624
+ ` : null}
625
+ ${showShortcuts ? html` <div class="modal-backdrop" onClick=${() => setShowShortcuts(false)}>
626
+ <div class="modal" onClick=${(e) => e.stopPropagation()}>
627
+ <h2>Keyboard Shortcuts</h2>
628
+ <div class="shortcuts-list">
629
+ <div class="shortcut-item"><kbd>Ctrl+K</kbd> <span>Command palette</span></div>
630
+ <div class="shortcut-item"><kbd>Ctrl+N</kbd> <span>New chat</span></div>
631
+ <div class="shortcut-item"><kbd>Ctrl+B</kbd> <span>Toggle sessions</span></div>
632
+ <div class="shortcut-item"><kbd>Ctrl+,</kbd> <span>Settings</span></div>
633
+ <div class="shortcut-item"><kbd>Ctrl+/</kbd> <span>Help</span></div>
634
+ <div class="shortcut-item"><kbd>Ctrl+Shift+F</kbd> <span>Search conversations</span></div>
635
+ <div class="shortcut-item"><kbd>Ctrl+Shift+E</kbd> <span>Export chat</span></div>
636
+ <div class="shortcut-item"><kbd>Ctrl+Shift+C</kbd> <span>Compare models</span></div>
637
+ <div class="shortcut-item"><kbd>Ctrl+Shift+T</kbd> <span>Cycle theme</span></div>
638
+ <div class="shortcut-item"><kbd>Esc</kbd> <span>Close modals</span></div>
639
+ <div class="shortcut-item"><kbd>Enter</kbd> <span>Send message</span></div>
640
+ <div class="shortcut-item"><kbd>Shift+Enter</kbd> <span>New line in input</span></div>
641
+ </div>
642
+ <div class="modal-actions">
643
+ <button onClick=${() => setShowShortcuts(false)}>Close</button>
644
+ </div>
645
+ </div>
646
+ </div>
647
+ ` : null}
648
+ ${showSearch ? html`
649
+ <div class="modal-backdrop" onClick=${() => setShowSearch(false)}>
650
+ <div class="modal" style="max-width: 600px" onClick=${(e) => e.stopPropagation()}>
651
+ <h2>Search Conversations</h2>
652
+ <div class="search-bar">
653
+ <input value=${searchQuery} onInput=${(e) => setSearchQuery(e.target.value)} placeholder="Search messages..." style="flex:1" onKeyDown=${(e) => { if (e.key === 'Enter') searchConversations(); }} />
654
+ <button class="btn-primary" onClick=${searchConversations}>Search</button>
655
+ </div>
656
+ ${searchResults.length > 0 ? html`
657
+ <div class="search-results">
658
+ ${searchResults.map((r) => html`
659
+ <div class="search-result-item">
660
+ <span class="search-role">${r.role}</span>
661
+ <span class="search-snippet">${r.snippet}</span>
662
+ </div>
663
+ `)}
664
+ </div>
665
+ ` : searchQuery ? html`<p class="hint">No results found.</p>` : null}
666
+ <div class="modal-actions">
667
+ <button onClick=${() => setShowSearch(false)}>Close</button>
668
+ </div>
669
+ </div>
670
+ </div>
671
+ ` : null}
672
+ ${showFiles ? html`
673
+ <div class="modal-backdrop" onClick=${() => setShowFiles(false)}>
674
+ <div class="modal" style="max-width: 800px; max-height: 80vh" onClick=${(e) => e.stopPropagation()}>
675
+ <h2>File Browser</h2>
676
+ <p class="hint">${fileDir}</p>
677
+ <div class="file-browser">
678
+ <div class="file-list">
679
+ ${fileEntries.map((e) => html`
680
+ <div class=${'file-item' + (e.type === 'dir' ? ' dir' : '')} onClick=${() => e.type === 'dir' ? loadFiles(e.path) : openFile(e.path)}>
681
+ <span class="file-icon">${e.type === 'dir' ? '📁' : '📄'}</span>
682
+ <span class="file-name">${e.name}</span>
683
+ ${e.type === 'file' ? html`<span class="file-size">${e.size > 1024 ? (e.size / 1024).toFixed(1) + ' KB' : e.size + ' B'}</span>` : null}
684
+ </div>
685
+ `)}
686
+ </div>
687
+ ${selectedFile ? html`
688
+ <div class="file-preview">
689
+ <h3>${selectedFile.split(/[\\/]/).pop()}</h3>
690
+ <pre class="file-content">${fileContent.slice(0, 5000)}</pre>
691
+ </div>
692
+ ` : null}
693
+ </div>
694
+ <div class="modal-actions">
695
+ <button onClick=${() => setShowFiles(false)}>Close</button>
696
+ </div>
697
+ </div>
698
+ </div>
699
+ ` : null}
528
700
  ${showCompare ? html`
529
701
  <div class="modal-backdrop" onClick=${() => setShowCompare(false)}>
530
702
  <div class="modal" style="max-width: 800px" onClick=${(e) => e.stopPropagation()}>
@@ -553,14 +725,22 @@ function App() {
553
725
  </div>
554
726
  </div>
555
727
  ` : null}
556
- <${SessionSidebar} open=${showSessions} onClose=${() => setShowSessions(false)} onSelect=${(s) => { toast('Loaded session: ' + (s.title || s.id), 'info'); }} />
728
+ <${SessionSidebar} open=${showSessions} onClose=${() => setShowSessions(false)} onSelect=${async (s) => {
729
+ try {
730
+ const d = await API('/api/sessions?id=' + encodeURIComponent(s.id));
731
+ setMessages((d.messages || []).map((m) => ({ role: m.role, content: m.content })));
732
+ toast('Loaded session: ' + (s.title || s.id), 'success');
733
+ } catch (e) { toast('Load failed: ' + e.message, 'error'); }
734
+ }} />
557
735
  <header class="topbar">
558
736
  <h1>AegisAi Harness</h1>
559
737
  <span class="ctx-meter">ctx ${ctx.tokens}/${ctx.limit}${ctx.compacted ? ' · compacted' : ''}</span>
560
738
  <button onClick=${() => setShowSessions(true)} title="Sessions (Ctrl+B)">📂</button>
561
- <button onClick=${() => setTheme(theme === 'dark' ? 'light' : 'dark')} title="Toggle theme">${theme === 'dark' ? '☀️' : '🌙'}</button>
739
+ <button onClick=${() => { const idx = THEMES.indexOf(theme); const next = THEMES[(idx + 1) % THEMES.length]; setTheme(next); localStorage.setItem('theme', next); toast('Theme: ' + next, 'info'); }} title="Cycle theme (${theme})">${theme === 'dark' ? '☀️' : theme === 'light' ? '🌙' : theme === 'high-contrast' ? '🔲' : '🌅'}</button>
562
740
  <button onClick=${() => setShowConfig(true)} title="Settings (Ctrl+,)">⚙️</button>
563
741
  <button onClick=${() => setShowPalette(true)} title="Command palette (Ctrl+K)">⌘</button>
742
+ <button onClick=${() => setShowFiles(true) || loadFiles('')} title="File browser">📁</button>
743
+ <button onClick=${() => setShowSearch(true)} title="Search conversations">🔍</button>
564
744
  <button onClick=${() => exportChat('markdown')} title="Export chat as Markdown">📤</button>
565
745
  <button onClick=${() => setShowCompare(true)} title="Compare models">⚖️</button>
566
746
  <button onClick=${() => setShowHelp(true)} title="Help (Ctrl+/)">?</button>
package/public/style.css CHANGED
@@ -4,6 +4,12 @@
4
4
  [data-theme="light"] {
5
5
  --bg: #ffffff; --fg: #24292f; --accent: #0969da; --border: #d0d7de; --panel: #f6f8fa; --input: #ffffff; --danger: #cf222e; --success: #1a7f37; --warning: #9a6700;
6
6
  }
7
+ [data-theme="high-contrast"] {
8
+ --bg: #000000; --fg: #ffffff; --accent: #ffff00; --border: #ffffff; --panel: #0a0a0a; --input: #000000; --danger: #ff0000; --success: #00ff00; --warning: #ffff00;
9
+ }
10
+ [data-theme="solarized"] {
11
+ --bg: #002b36; --fg: #839496; --accent: #268bd2; --border: #586e75; --panel: #073642; --input: #002b36; --danger: #dc322f; --success: #859900; --warning: #b58900;
12
+ }
7
13
  * { box-sizing: border-box; }
8
14
  body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--bg); color: var(--fg); }
9
15
  .app { display: flex; flex-direction: column; height: 100vh; }
@@ -250,6 +256,23 @@ kbd { background: var(--panel); border: 1px solid var(--border); border-radius:
250
256
  .scan-results, .hf-results { margin: 8px 0; max-height: 200px; overflow-y: auto; }
251
257
  .scan-item, .hf-item { display: flex; align-items: center; gap: 8px; padding: 6px; border-bottom: 1px solid var(--border); font-size: 12px; }
252
258
  .hf-item .model-name { flex: 1; }
259
+ /* Shortcuts */
260
+ .shortcuts-list { margin: 8px 0; }
261
+ .shortcut-item { display: flex; align-items: center; gap: 12px; padding: 6px 0; border-bottom: 1px solid var(--border); }
262
+ .shortcut-item kbd { background: var(--panel); border: 1px solid var(--border); border-radius: 4px; padding: 2px 8px; font-size: 12px; font-family: monospace; min-width: 100px; text-align: center; }
263
+ .shortcut-item span { font-size: 13px; }
264
+ /* File browser */
265
+ .file-browser { display: flex; gap: 12px; margin: 8px 0; }
266
+ .file-list { flex: 1; max-height: 300px; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px; padding: 4px; }
267
+ .file-item { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 4px; cursor: pointer; font-size: 13px; }
268
+ .file-item:hover { background: var(--border); }
269
+ .file-item.dir { font-weight: 500; }
270
+ .file-icon { width: 20px; text-align: center; }
271
+ .file-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
272
+ .file-size { font-size: 11px; color: var(--muted); }
273
+ .file-preview { flex: 1; border: 1px solid var(--border); border-radius: 6px; padding: 8px; max-height: 300px; overflow-y: auto; }
274
+ .file-preview h3 { margin: 0 0 8px; font-size: 13px; }
275
+ .file-content { font-size: 12px; line-height: 1.4; white-space: pre-wrap; word-break: break-all; margin: 0; }
253
276
  /* Compare */
254
277
  .compare-results { margin-top: 16px; max-height: 400px; overflow-y: auto; }
255
278
  .compare-card { background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 12px; margin-bottom: 8px; }
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
@@ -156,13 +156,25 @@ async function main() {
156
156
  const rateWindow = parseInt(process.env.AEGISAI_RATE_WINDOW || '60', 10) * 1000;
157
157
  const rateHits = new Map();
158
158
  const sessions = new Map(); // session id -> messages array
159
+ const sessionToolLogs = new Map(); // session id -> last tool log (for /api/context)
160
+ const sessionUpdated = new Map(); // session id -> ISO timestamp
161
+ const warnMissing = (v) => String(v || 'default');
159
162
  const pendingActions = new Map();
160
163
 
161
164
  function readJson(req) {
165
+ const MAX_BODY = parseInt(process.env.AEGISAI_MAX_BODY_BYTES || '1048576', 10); // 1 MiB default
162
166
  return new Promise((resolve, reject) => {
163
167
  let body = '';
164
- req.on('data', (c) => { body += c; });
165
- req.on('end', () => { try { resolve(JSON.parse(body || '{}')); } catch (e) { reject(e); } });
168
+ let bytes = 0;
169
+ let aborted = false;
170
+ req.on('data', (c) => {
171
+ if (aborted) return;
172
+ bytes += c.length;
173
+ if (bytes > MAX_BODY) { aborted = true; reject(Object.assign(new Error('request body too large'), { status: 413 })); req.resume(); return; }
174
+ body += c;
175
+ });
176
+ req.on('error', (e) => { if (!aborted) { aborted = true; reject(e); } });
177
+ req.on('end', () => { if (aborted) return; try { resolve(JSON.parse(body || '{}')); } catch (e) { reject(Object.assign(e, { status: 400 })); } });
166
178
  });
167
179
  }
168
180
  function sendJson(res, status, obj) {
@@ -170,7 +182,7 @@ async function main() {
170
182
  res.end(JSON.stringify(obj));
171
183
  }
172
184
 
173
- const server = http.createServer(async (req, res) => {
185
+ const handleRequest = async (req, res) => {
174
186
  // CORS headers (needed for browser fetch with application/json content type)
175
187
  res.setHeader('Access-Control-Allow-Origin', '*');
176
188
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
@@ -180,10 +192,19 @@ async function main() {
180
192
  const expectedToken = currentToken();
181
193
  if (expectedToken) {
182
194
  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; }
195
+ if (!tokenMatches(supplied, expectedToken)) {
196
+ // A valid personal access token (PAT) may stand in for the global token.
197
+ let patOk = false;
198
+ try {
199
+ const pats = require('./access_tokens');
200
+ const v = pats.verify ? pats.verify(supplied) : null;
201
+ patOk = Boolean(v && (v.ok !== false));
202
+ } catch (e) { patOk = false; }
203
+ if (!patOk) { sendJson(res, 401, { error: 'unauthorized' }); return; }
204
+ }
184
205
  }
185
- // rate limit
186
- if (rateLimit > 0) {
206
+ // rate limit — API only; static assets must not consume the API budget
207
+ if (rateLimit > 0 && req.url.split('?')[0].startsWith('/api/')) {
187
208
  const ip = req.socket.remoteAddress || 'unknown';
188
209
  const now = Date.now();
189
210
  const arr = (rateHits.get(ip) || []).filter((t) => now - t < rateWindow);
@@ -206,10 +227,10 @@ async function main() {
206
227
  messages: history.concat([{ role: 'user', content: parsed.message || '' }]),
207
228
  projectRoot: process.cwd(),
208
229
  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'); }
230
+ if (e.type === 'token') { fullReply += (e.content || ''); res.write('data: ' + JSON.stringify({ type: 'token', content: e.content || '' }) + '\n\n'); }
231
+ else if (e.type === 'tool_call') { res.write('data: ' + JSON.stringify({ type: 'tool_call', name: e.name, args: e.args }) + '\n\n'); }
232
+ else if (e.type === 'tool_result') { res.write('data: ' + JSON.stringify({ type: 'tool_result', preview: (e.preview || '').slice(0, 200) }) + '\n\n'); }
233
+ else if (e.type === 'status') { res.write('data: ' + JSON.stringify({ type: 'status', message: e.message }) + '\n\n'); }
213
234
  },
214
235
  autoApprove,
215
236
  approvalHandler: async () => false,
@@ -217,7 +238,9 @@ async function main() {
217
238
  const reply = (result.final && result.final.final) || fullReply;
218
239
  const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
219
240
  sessions.set(sid, updated);
220
- res.write('data: ' + JSON.stringify({ type: 'done', reply, toolLog: result.toolLog || [] }) + '\\n\\n');
241
+ sessionToolLogs.set(sid, result.toolLog || []);
242
+ sessionUpdated.set(sid, new Date().toISOString());
243
+ res.write('data: ' + JSON.stringify({ type: 'done', reply, toolLog: result.toolLog || [] }) + '\n\n');
221
244
  res.end();
222
245
  return;
223
246
  }
@@ -233,6 +256,8 @@ async function main() {
233
256
  const reply = (result.final && result.final.final) || '';
234
257
  const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
235
258
  sessions.set(sid, updated);
259
+ sessionToolLogs.set(sid, result.toolLog || []);
260
+ sessionUpdated.set(sid, new Date().toISOString());
236
261
  sendJson(res, 200, { reply, toolLog: result.toolLog || [], pendingActions: pendingActions.get(sid) || [] });
237
262
  return;
238
263
  }
@@ -303,7 +328,7 @@ async function main() {
303
328
  let results = [];
304
329
  try {
305
330
  // 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');
331
+ const r = await fetch('https://huggingface.co/api/models?search=' + encodeURIComponent(q) + '&sort=downloads&direction=-1&limit=30', { signal: AbortSignal.timeout(15000) });
307
332
  if (r.ok) {
308
333
  const data = await r.json();
309
334
  const all = Array.isArray(data) ? data : [];
@@ -323,43 +348,6 @@ async function main() {
323
348
  sendJson(res, 200, { results, query: q });
324
349
  return;
325
350
  }
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
351
  if (req.method === 'POST' && req.url.split('?')[0] === '/api/models/pull') {
364
352
  const parsed = await readJson(req);
365
353
  let ok = false;
@@ -378,7 +366,7 @@ async function main() {
378
366
  sendJson(res, 200, { ok: true });
379
367
  return;
380
368
  }
381
- } catch (e) { sendJson(res, 500, { error: String(e.message || e) }); return; }
369
+ } catch (e) { sendJson(res, (e && e.status) || 500, { error: String(e.message || e) }); return; }
382
370
 
383
371
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/stream') {
384
372
  const u = new URL(req.url, 'http://x');
@@ -389,13 +377,55 @@ async function main() {
389
377
  const tokenizer = require('./tokenizer');
390
378
  const sid = new URL(req.url, 'http://x').searchParams.get('session') || 'default';
391
379
  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__') });
380
+ const tl = sessionToolLogs.get(sid) || [];
381
+ sendJson(res, 200, { tokens, limit: 8192, ratio: +(tokens / 8192).toFixed(3), compacted: tl.some((t) => t.name === '__compact__') });
393
382
  return;
394
383
  }
395
384
  if (req.url.split('?')[0] === '/mcp') {
396
385
  require('./mcp_server').createHandler()(req, res);
397
386
  return;
398
387
  }
388
+ if (req.method === 'GET' && req.url.split('?')[0] === '/api/search-sessions') {
389
+ const q = (new URL(req.url, 'http://x').searchParams.get('q') || '').toLowerCase();
390
+ const results = [];
391
+ for (const [sid, msgs] of sessions.entries()) {
392
+ for (const m of msgs) {
393
+ if ((m.content || '').toLowerCase().includes(q)) {
394
+ results.push({ sessionId: sid, role: m.role, snippet: (m.content || '').slice(0, 100), match: true });
395
+ break;
396
+ }
397
+ }
398
+ }
399
+ sendJson(res, 200, { results, query: q });
400
+ return;
401
+ }
402
+ if (req.method === 'GET' && req.url.split('?')[0] === '/api/files') {
403
+ const dir = new URL(req.url, 'http://x').searchParams.get('dir') || process.cwd();
404
+ let entries = [];
405
+ try {
406
+ const fs = require('fs');
407
+ const path = require('path');
408
+ const items = fs.readdirSync(dir, { withFileTypes: true });
409
+ entries = items.map((e) => ({
410
+ name: e.name,
411
+ type: e.isDirectory() ? 'dir' : 'file',
412
+ size: e.isFile() ? (fs.statSync(path.join(dir, e.name)).size) : 0,
413
+ path: path.join(dir, e.name),
414
+ })).sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : (a.type === 'dir' ? -1 : 1)));
415
+ } catch (e) {}
416
+ sendJson(res, 200, { dir, entries });
417
+ return;
418
+ }
419
+ if (req.method === 'GET' && req.url.split('?')[0] === '/api/file') {
420
+ const filePath = new URL(req.url, 'http://x').searchParams.get('path');
421
+ if (!filePath) { sendJson(res, 400, { error: 'path required' }); return; }
422
+ try {
423
+ const fs = require('fs');
424
+ const content = fs.readFileSync(filePath, 'utf8');
425
+ sendJson(res, 200, { content, path: filePath });
426
+ } catch (e) { sendJson(res, 500, { error: String(e.message || e) }); }
427
+ return;
428
+ }
399
429
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/projects') {
400
430
  const list = require('./projects').list();
401
431
  const details = list.map((n) => require('./projects').get(n));
@@ -416,8 +446,31 @@ async function main() {
416
446
  sendJson(res, 200, { events: require('./event_bus').bus.events() });
417
447
  return;
418
448
  }
449
+ if (req.method === 'GET' && req.url.split('?')[0] === '/api/sessions') {
450
+ const u = new URL(req.url, 'http://x');
451
+ const wantId = u.searchParams.get('id');
452
+ if (wantId) {
453
+ const sid = warnMissing(wantId);
454
+ const msgs = sessions.get(sid) || [];
455
+ sendJson(res, 200, { id: sid, messages: msgs });
456
+ return;
457
+ }
458
+ const list = [];
459
+ for (const [id, msgs] of sessions.entries()) {
460
+ const firstUser = (msgs || []).find((m) => m.role === 'user');
461
+ list.push({
462
+ id,
463
+ title: firstUser ? String(firstUser.content || '').slice(0, 60) : id,
464
+ messages: (msgs || []).length,
465
+ updated: sessionUpdated.get(id) || null,
466
+ });
467
+ }
468
+ list.sort((a, b) => String(b.updated || '').localeCompare(String(a.updated || '')));
469
+ sendJson(res, 200, { sessions: list });
470
+ return;
471
+ }
419
472
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/events') {
420
- require('./event_stream').subscribe(res);
473
+ require('./event_stream').subscribe(res, req);
421
474
  return;
422
475
  }
423
476
  try {
@@ -468,6 +521,8 @@ async function main() {
468
521
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/version') {
469
522
  const v = require('./updater');
470
523
  let info = v.checkLocal();
524
+ if (!info || typeof info !== 'object') info = {};
525
+ info.version = require('./version').VERSION;
471
526
  try { info.node = process.version; } catch (e) {}
472
527
  sendJson(res, 200, info);
473
528
  return;
@@ -524,10 +579,12 @@ async function main() {
524
579
  const url = process.env.STT_URL;
525
580
  if (!url) { sendJson(res, 400, { error: 'STT_URL not configured' }); return; }
526
581
  try {
582
+ const MAX_AUDIO = parseInt(process.env.AEGISAI_MAX_AUDIO_BYTES || '26214400', 10); // 25 MiB
527
583
  const chunks = [];
528
- for await (const c of req) chunks.push(c);
584
+ let total = 0;
585
+ for await (const c of req) { total += c.length; if (total > MAX_AUDIO) { sendJson(res, 413, { error: 'audio too large' }); return; } chunks.push(c); }
529
586
  const body = Buffer.concat(chunks);
530
- const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': req.headers['content-type'] || 'audio/webm' }, body });
587
+ const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': req.headers['content-type'] || 'audio/webm' }, body, signal: AbortSignal.timeout(60000) });
531
588
  const data = await r.json();
532
589
  sendJson(res, 200, { text: data.text || '' });
533
590
  } catch (e) { sendJson(res, 500, { error: String(e.message || e) }); }
@@ -554,7 +611,17 @@ async function main() {
554
611
  res.writeHead(200, { 'Content-Type': ct });
555
612
  res.end(fs.readFileSync(filePath));
556
613
  } else { res.writeHead(404); res.end(); }
614
+ };
615
+ const server = http.createServer((req, res) => {
616
+ handleRequest(req, res).catch((e) => {
617
+ try {
618
+ if (!res.headersSent) sendJson(res, (e && e.status) || 500, { error: String((e && e.message) || e) });
619
+ else res.end();
620
+ } catch (_) { try { res.end(); } catch (__) {} }
621
+ });
557
622
  });
623
+ // Never let a stray rejection kill the web server.
624
+ process.on('unhandledRejection', (e) => { try { console.error('[unhandledRejection]', (e && e.stack) || e); } catch (_) {} });
558
625
  server.listen(port, host, () => console.log('Web UI at http://' + host + ':' + port));
559
626
  return;
560
627
  }
@@ -651,10 +718,36 @@ async function main() {
651
718
  };
652
719
  rl.prompt();
653
720
  rl.on('line', async (line) => {
721
+ try {
654
722
  const t = line.trim();
655
723
  if (!t) { rl.prompt(); return; }
656
724
  if (t === '/exit' || t === '/quit') { rl.close(); return; }
657
- 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; }
725
+ if (t === '/help') {
726
+ const groups = [
727
+ ['Session', ['/exit', '/model <name>', '/root <path>', '/sandbox on|off', '/autoapprove on|off', '/offline on|off', '/agent <name>', '/plan <goal>']],
728
+ ['Index & replay', ['/index', '/replay <sessionId>', '/traces', '/search-sessions <q>', '/session-export <id>|<format>']],
729
+ ['Health & data', ['/health', '/backup <file>', '/restore <file>', '/vault set|get|list|delete ...', '/metrics', '/score', '/reliability']],
730
+ ['Eval & bench', ['/eval add|run|list', '/pass-at-k', '/bench <models...>', '/failure-clusters', '/lint', '/stress']],
731
+ ['Models', ['/providers', '/provider-list', '/model-scan', '/models', '/cheapest <prompt>', '/cost-route', '/routing-eval']],
732
+ ['Memory', ['/remember <text>', '/recall <q>', '/reflect', '/sremember', '/srecall', '/tremember', '/tasof', '/memory-graph', '/habits', '/geo-wake', '/mem-reindex']],
733
+ ['Memory (graph)', ['/graph-observe', '/graph-recall', '/graph-prompt', '/mem-md-search', '/memory-hierarchy']],
734
+ ['Governance', ['/charter', '/governance', '/constitution', '/constitution-propose', '/constitution-decide', '/policy', '/auto-rules', '/ahp-check', '/security-layers', '/identity-list']],
735
+ ['Audit & evidence', ['/ledger-verify', '/ledger-replay', '/ledger-rewind', '/merkle-root', '/evidence-bundle', '/contract-save', '/contract-check', '/contracts', '/honesty', '/waste', '/diagnose', '/evolve']],
736
+ ['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']],
737
+ ['Tools', ['/tools', '/tool-contract', '/tool-eval', '/tool-state', '/equipment', '/equipment-add', '/semantic-tools <q>', '/mcp-pins', '/mcp-registry', '/mcp-market']],
738
+ ['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>']],
739
+ ['Browser & web', ['/browser-targets', '/browser-nav <url>', '/browser-snapshot', '/browser-eval <js>', '/extract <url>', '/search <q>', '/multi-search <q>', '/fetch <url>', '/squeeze <url>|<q>']],
740
+ ['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']],
741
+ ['Misc', ['/time', '/export <format>|<title>', '/compare <prompt>|<model1>|<model2>', '/ui-record', '/ui-replay', '/plugins-ui', '/dag-ui', '/trajectory-ui', '/backup', '/help']],
742
+ ];
743
+ console.log('\nAegisAi Harness — command reference\n');
744
+ for (const [g, cmds] of groups) {
745
+ console.log(g + ':');
746
+ console.log(' ' + cmds.join(', '));
747
+ }
748
+ console.log('\nType /<command> to run. Many commands accept "|" separated arguments.');
749
+ rl.prompt(); return;
750
+ }
658
751
  if (t.startsWith('/model ')) { model = t.slice(7).trim(); console.log('model =', model); rl.prompt(); return; }
659
752
  if (t.startsWith('/root ')) { root = t.slice(6).trim(); console.log('root =', root); rl.prompt(); return; }
660
753
  if (t.startsWith('/sandbox ')) { sandbox = t.slice(9).trim() === 'on'; console.log('sandbox =', sandbox); rl.prompt(); return; }
@@ -1042,6 +1135,10 @@ async function main() {
1042
1135
  }
1043
1136
  try { await runOne(t); } catch (e) { console.error('error:', e.message || e); }
1044
1137
  rl.prompt();
1138
+ } catch (err) {
1139
+ console.error('[command error]', (err && err.message) || err);
1140
+ try { rl.prompt(); } catch (_) {}
1141
+ }
1045
1142
  });
1046
1143
  rl.on('close', () => { db.close(); process.exit(0); });
1047
1144
  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/tui.js CHANGED
@@ -45,7 +45,9 @@ class Tui extends EventEmitter {
45
45
  }
46
46
  handleKey(d) {
47
47
  const s = d.toString();
48
+ if (!s) return;
48
49
  if (s === '\u0003') { this.stop(); return; } // Ctrl+C
50
+ // Split pasted/multi-byte chunks into lines and printable runs.
49
51
  if (s === '\r' || s === '\n') {
50
52
  const cmd = this.input.trim();
51
53
  this.input = '';
@@ -59,9 +61,26 @@ class Tui extends EventEmitter {
59
61
  this.render();
60
62
  return;
61
63
  }
62
- if (s.startsWith('\x1b[')) return; // ignore arrow keys for now
63
- if (s.length === 1 && s.charCodeAt(0) >= 32) {
64
- this.input += s;
64
+ if (s.startsWith('\x1b[') || s.startsWith('\x1bO')) return; // ignore escape sequences
65
+ // Handle pasted text containing newlines: submit each complete line.
66
+ if (s.includes('\n') || s.includes('\r')) {
67
+ const parts = s.split(/\r\n|\r|\n/);
68
+ for (let i = 0; i < parts.length; i++) {
69
+ if (parts[i]) this.input += parts[i].replace(/[^\x20-\x7e\t]/g, '');
70
+ if (i < parts.length - 1) {
71
+ const cmd = this.input.trim();
72
+ this.input = '';
73
+ this.emit('command', cmd);
74
+ if (cmd) this.addMessage('user', cmd);
75
+ }
76
+ }
77
+ this.render();
78
+ return;
79
+ }
80
+ // Accept the whole printable run (paste support), dropping control chars.
81
+ const printable = s.replace(/[^\x20-\x7e\t]/g, '');
82
+ if (printable) {
83
+ this.input += printable;
65
84
  this.render();
66
85
  }
67
86
  }
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.73.0';
3
+ const VERSION = '0.75.0';
4
4
  module.exports = { VERSION, version: VERSION };