aegisai-harness 0.75.0 → 0.77.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.75.0] - 2026-11-24
5
+ ## [0.77.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.75.0 (see [ROADMAP.md](./ROADMAP.md)).
13
+ > Status: v0.77.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.75.0.
3
+ A feature-rich, local-only AI agent harness. CLI-first, offline-first. v0.77.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.75.0",
3
+ "version": "0.77.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.75.0
7
+ AppVersion=0.77.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.75.0-Setup
13
+ OutputBaseFilename=AegisAi-Harness-0.77.0-Setup
14
14
  Compression=lzma2
15
15
  SolidCompression=yes
16
16
  PrivilegesRequired=lowest
package/public/app.js CHANGED
@@ -325,12 +325,28 @@ function ConfigModal({ cfg, setCfg, onClose }) {
325
325
  function SessionSidebar({ open, onClose, onSelect }) {
326
326
  const [sessions, setSessions] = useState([]);
327
327
  const [q, setQ] = useState('');
328
- useEffect(() => {
329
- if (open) {
330
- API('/api/sessions').then((d) => setSessions(d.sessions || [])).catch(() => {});
331
- }
332
- }, [open]);
333
- const filtered = sessions.filter((s) => !q || (s.title || s.id || '').toLowerCase().includes(q.toLowerCase()));
328
+ const [tagFilter, setTagFilter] = useState('');
329
+ const [tagDraft, setTagDraft] = useState({});
330
+ const load = () => API('/api/sessions').then((d) => setSessions(d.sessions || [])).catch(() => {});
331
+ useEffect(() => { if (open) load(); }, [open]);
332
+ const allTags = Array.from(new Set(sessions.flatMap((s) => s.tags || []))).sort();
333
+ const filtered = sessions.filter((s) => {
334
+ const text = ((s.title || '') + ' ' + (s.id || '')).toLowerCase();
335
+ const matchesQ = !q || text.includes(q.toLowerCase());
336
+ const matchesTag = !tagFilter || (s.tags || []).includes(tagFilter);
337
+ return matchesQ && matchesTag;
338
+ });
339
+ async function saveTags(s) {
340
+ const raw = tagDraft[s.id];
341
+ if (raw == null) return;
342
+ const tags = raw.split(',').map((t) => t.trim()).filter(Boolean);
343
+ try {
344
+ await API('/api/sessions/tags', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: s.id, tags }) });
345
+ toast('Tags saved', 'success');
346
+ setTagDraft((d) => { const n = Object.assign({}, d); delete n[s.id]; return n; });
347
+ load();
348
+ } catch (e) { toast('Tag save failed: ' + e.message, 'error'); }
349
+ }
334
350
  if (!open) return null;
335
351
  return html`
336
352
  <div class="sidebar">
@@ -339,11 +355,27 @@ function SessionSidebar({ open, onClose, onSelect }) {
339
355
  <button class="sidebar-close" onClick=${onClose}>×</button>
340
356
  </div>
341
357
  <input class="sidebar-search" value=${q} onInput=${(e) => setQ(e.target.value)} placeholder="Search sessions..." />
358
+ ${allTags.length ? html`
359
+ <div class="tag-filter">
360
+ <span class=${'tag-pill' + (tagFilter === '' ? ' active' : '')} onClick=${() => setTagFilter('')}>all</span>
361
+ ${allTags.map((t) => html`<span class=${'tag-pill' + (tagFilter === t ? ' active' : '')} onClick=${() => setTagFilter(tagFilter === t ? '' : t)}>${t}</span>`)}
362
+ </div>
363
+ ` : null}
342
364
  <div class="sidebar-list">
343
365
  ${filtered.map((s) => html`
344
- <div class="session-item" onClick=${() => { onSelect(s); onClose(); }}>
345
- <div class="session-title">${s.title || s.id}</div>
366
+ <div class="session-item">
367
+ <div class="session-title" onClick=${() => { onSelect(s); onClose(); }}>${s.title || s.id}</div>
346
368
  <div class="session-meta">${s.updated || ''}</div>
369
+ <div class="session-tags">
370
+ ${(s.tags || []).map((t) => html`<span class="tag-pill small">${t}</span>`)}
371
+ <input
372
+ class="tag-input"
373
+ placeholder="+ tags (comma sep)"
374
+ value=${tagDraft[s.id] != null ? tagDraft[s.id] : (s.tags || []).join(', ')}
375
+ onInput=${(e) => setTagDraft((d) => Object.assign({}, d, { [s.id]: e.target.value }))}
376
+ onKeyDown=${(e) => { if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); saveTags(s); } }}
377
+ />
378
+ </div>
347
379
  </div>
348
380
  `)}
349
381
  ${filtered.length === 0 ? html`<div class="sidebar-empty">No sessions found</div>` : null}
@@ -352,6 +384,30 @@ function SessionSidebar({ open, onClose, onSelect }) {
352
384
  `;
353
385
  }
354
386
 
387
+ // Word-level diff render: additions highlighted, deletions struck through.
388
+ function DiffText({ a, b }) {
389
+ const tok = (s) => String(s || '').split(/(\s+)/).filter((t) => t !== '');
390
+ const A = tok(a).slice(0, 3000);
391
+ const B = tok(b).slice(0, 3000);
392
+ const n = A.length, m = B.length;
393
+ const dp = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
394
+ for (let i = n - 1; i >= 0; i--) {
395
+ for (let j = m - 1; j >= 0; j--) {
396
+ dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
397
+ }
398
+ }
399
+ const out = [];
400
+ let i = 0, j = 0, key = 0;
401
+ while (i < n && j < m) {
402
+ if (A[i] === B[j]) { out.push(html`<span key=${key++}>${A[i]}</span>`); i++; j++; }
403
+ else if (dp[i + 1][j] >= dp[i][j + 1]) { out.push(html`<del key=${key++}>${A[i]}</del>`); i++; }
404
+ else { out.push(html`<ins key=${key++}>${B[j]}</ins>`); j++; }
405
+ }
406
+ while (i < n) out.push(html`<del key=${key++}>${A[i++]}</del>`);
407
+ while (j < m) out.push(html`<ins key=${key++}>${B[j++]}</ins>`);
408
+ return html`<pre class="compare-pre diff">${out}</pre>`;
409
+ }
410
+
355
411
  function ToolTimeline({ tools }) {
356
412
  if (!tools || tools.length === 0) return null;
357
413
  return html`
@@ -383,6 +439,9 @@ function App() {
383
439
  const [toasts, setToasts] = useState([]);
384
440
  const [toolLog, setToolLog] = useState([]);
385
441
  const [dragOver, setDragOver] = useState(false);
442
+ const [attachments, setAttachments] = useState([]);
443
+ const [attachPreview, setAttachPreview] = useState(null);
444
+ const [fileEditor, setFileEditor] = useState(null);
386
445
  const [needAuth, setNeedAuth] = useState(false);
387
446
  const [tokenInput, setTokenInput] = useState('');
388
447
  const inputRef = useRef(null);
@@ -437,12 +496,13 @@ function App() {
437
496
  setDragOver(false);
438
497
  const files = e.dataTransfer.files;
439
498
  if (files.length) {
440
- toast('Attached ' + files.length + ' file(s)', 'info');
441
- // Read file contents and append to input
442
499
  Array.from(files).forEach((f) => {
443
500
  const reader = new FileReader();
444
501
  reader.onload = (ev) => {
445
- setInput((prev) => prev + '\n[File: ' + f.name + ']\n' + ev.target.result.slice(0, 2000) + '\n');
502
+ const content = String(ev.target.result || '').slice(0, 2000);
503
+ const id = 'att_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
504
+ setAttachments((prev) => [...prev, { id, name: f.name, size: f.size, content }]);
505
+ toast('Attached ' + f.name, 'info');
446
506
  };
447
507
  reader.readAsText(f);
448
508
  });
@@ -470,16 +530,23 @@ function App() {
470
530
  }
471
531
 
472
532
  async function send() {
473
- if (!input.trim() || loading) return;
474
- const text = input;
533
+ if ((!input.trim() && attachments.length === 0) || loading) return;
534
+ let text = input;
535
+ if (attachments.length) {
536
+ const parts = attachments.map((a) => '[File: ' + a.name + ']\n' + a.content);
537
+ text = (text ? text + '\n\n' : '') + parts.join('\n\n');
538
+ }
539
+ const displayText = input || (attachments.length ? '(attached ' + attachments.map((a) => a.name).join(', ') + ')' : '');
475
540
  setInput('');
476
- setMessages((m) => [...m, { role: 'user', content: text }]);
541
+ setAttachments([]);
542
+ setMessages((m) => [...m, { role: 'user', content: displayText }]);
477
543
  setLoading(true);
478
544
  setToolLog([]);
479
545
  // Add empty assistant message for streaming
480
546
  setMessages((m) => [...m, { role: 'assistant', content: '' }]);
481
547
  try {
482
548
  const r = await apiFetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: text, stream: true }) });
549
+ if (r.status === 401) { window.dispatchEvent(new CustomEvent('aegisai-unauthorized')); throw new Error('unauthorized'); }
483
550
  if (!r.ok) throw new Error('HTTP ' + r.status);
484
551
  const reader = r.body.getReader();
485
552
  const decoder = new TextDecoder();
@@ -504,12 +571,23 @@ function App() {
504
571
  });
505
572
  } else if (data.type === 'tool_call') {
506
573
  toast('Tool: ' + data.name, 'info');
574
+ } else if (data.type === 'error') {
575
+ throw new Error(data.message || 'stream error');
507
576
  } else if (data.type === 'done') {
508
577
  if (data.toolLog) setToolLog(data.toolLog);
578
+ // Fall back to the authoritative reply if no token frames arrived.
579
+ if (!fullReply && data.reply) {
580
+ fullReply = data.reply;
581
+ setMessages((m) => {
582
+ const updated = [...m];
583
+ updated[updated.length - 1] = { role: 'assistant', content: fullReply };
584
+ return updated;
585
+ });
586
+ }
509
587
  updateCtx();
510
588
  toast('Response received', 'success');
511
589
  }
512
- } catch (e) {}
590
+ } catch (e) { if (e && e.message && e.message !== 'Unexpected end of JSON input') throw e; }
513
591
  }
514
592
  }
515
593
  } catch (e) {
@@ -553,6 +631,7 @@ function App() {
553
631
  const [comparePrompt, setComparePrompt] = useState('');
554
632
  const [compareResult, setCompareResult] = useState(null);
555
633
  const [comparing, setComparing] = useState(false);
634
+ const [compareDiff, setCompareDiff] = useState(false);
556
635
 
557
636
  async function exportChat(format) {
558
637
  try {
@@ -587,6 +666,24 @@ function App() {
587
666
  } catch (e) { toast('Failed to read file: ' + e.message, 'error'); }
588
667
  }
589
668
 
669
+ async function openInEditor(filePath) {
670
+ try {
671
+ const d = await API('/api/file?path=' + encodeURIComponent(filePath));
672
+ setFileEditor({ path: filePath, content: d.content || '', dirty: false });
673
+ setShowFiles(false);
674
+ toast('Opened in editor', 'info');
675
+ } catch (e) { toast('Open failed: ' + e.message, 'error'); }
676
+ }
677
+
678
+ async function saveEditor() {
679
+ if (!fileEditor) return;
680
+ try {
681
+ await API('/api/file', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: fileEditor.path, content: fileEditor.content }) });
682
+ setFileEditor(Object.assign({}, fileEditor, { dirty: false }));
683
+ toast('Saved ' + fileEditor.path.split(/[\\/]/).pop(), 'success');
684
+ } catch (e) { toast('Save failed: ' + e.message, 'error'); }
685
+ }
686
+
590
687
  async function runCompare() {
591
688
  if (!comparePrompt.trim() || !compareModels.trim()) { toast('Enter a prompt and models', 'error'); return; }
592
689
  setComparing(true);
@@ -601,7 +698,24 @@ function App() {
601
698
  }
602
699
 
603
700
  if (view === 'onboarding') {
604
- return html`<${OnboardingWizard} onComplete=${() => setView('chat')} />`;
701
+ return html`
702
+ <div class="app" data-theme=${theme}>
703
+ <${ToastContainer} />
704
+ ${needAuth ? html`
705
+ <div class="modal-backdrop">
706
+ <div class="modal" onClick=${(e) => e.stopPropagation()}>
707
+ <h2>Authentication Required</h2>
708
+ <p>The server requires an access token. Enter it below.</p>
709
+ <input type="password" value=${tokenInput} onInput=${(e) => setTokenInput(e.target.value)} placeholder="Access token" style="width:100%" />
710
+ <div class="modal-actions">
711
+ <button class="btn-primary" onClick=${() => { setAuthToken(tokenInput.trim()); setNeedAuth(false); setTokenInput(''); toast('Token set', 'success'); updateCtx(); }}>Use Token</button>
712
+ </div>
713
+ </div>
714
+ </div>
715
+ ` : null}
716
+ <${OnboardingWizard} onComplete=${() => { setNeedAuth(false); setView('chat'); updateCtx(); }} />
717
+ </div>
718
+ `;
605
719
  }
606
720
 
607
721
  return html`
@@ -686,7 +800,10 @@ function App() {
686
800
  </div>
687
801
  ${selectedFile ? html`
688
802
  <div class="file-preview">
689
- <h3>${selectedFile.split(/[\\/]/).pop()}</h3>
803
+ <div class="file-preview-head">
804
+ <h3>${selectedFile.split(/[\\/]/).pop()}</h3>
805
+ <button class="btn-sm" onClick=${() => openInEditor(selectedFile)}>Open in editor</button>
806
+ </div>
690
807
  <pre class="file-content">${fileContent.slice(0, 5000)}</pre>
691
808
  </div>
692
809
  ` : null}
@@ -712,14 +829,29 @@ function App() {
712
829
  <button onClick=${() => setShowCompare(false)}>Close</button>
713
830
  </div>
714
831
  ${compareResult ? html`
715
- <div class="compare-results">
716
- ${compareResult.comparison.results.map((r) => html`
717
- <div class="compare-card">
718
- <h3>${r.model} ${r.ok ? '✓' : '✗'} ${r.duration}ms</h3>
719
- <div class="compare-reply">${r.ok ? r.reply.slice(0, 500) : r.error}</div>
832
+ <div class="compare-summary">
833
+ ${compareResult.analysis ? html`<span class="hint">Agreement: ${(compareResult.analysis.agreement == null ? 'n/a' : (compareResult.analysis.agreement * 100).toFixed(1) + '%')}</span>` : null}
834
+ <span class="hint">Fastest: ${compareResult.comparison.fastest || 'n/a'}</span>
835
+ <span class="hint">Shortest: ${compareResult.comparison.shortest || 'n/a'}</span>
836
+ <span class="hint">Longest: ${compareResult.comparison.longest || 'n/a'}</span>
837
+ </div>
838
+ <div class=${'compare-grid' + (compareDiff ? ' with-diff' : '')}>
839
+ ${compareResult.comparison.results.map((r, i) => html`
840
+ <div class="compare-col">
841
+ <div class="compare-head">
842
+ <strong>${r.model}</strong>
843
+ <span class="compare-badge ${r.ok ? 'ok' : 'err'}">${r.ok ? r.duration + 'ms' : 'error'}</span>
844
+ </div>
845
+ <div class="compare-body">
846
+ ${r.ok ? (compareDiff && i > 0
847
+ ? html`<${DiffText} a=${compareResult.comparison.results[0].reply} b=${r.reply} />`
848
+ : html`<pre class="compare-pre">${r.reply.slice(0, 2000)}</pre>`) : html`<pre class="compare-pre err">${r.error}</pre>`}
849
+ </div>
720
850
  </div>
721
851
  `)}
722
- <p class="hint">Fastest: ${compareResult.comparison.fastest} | Shortest: ${compareResult.comparison.shortest} | Longest: ${compareResult.comparison.longest}</p>
852
+ </div>
853
+ <div class="modal-actions">
854
+ <button class="btn-secondary" onClick=${() => setCompareDiff((v) => !v)}>${compareDiff ? 'Hide diff' : 'Show diff vs first'}</button>
723
855
  </div>
724
856
  ` : null}
725
857
  </div>
@@ -745,7 +877,7 @@ function App() {
745
877
  <button onClick=${() => setShowCompare(true)} title="Compare models">⚖️</button>
746
878
  <button onClick=${() => setShowHelp(true)} title="Help (Ctrl+/)">?</button>
747
879
  </header>
748
- <div class="main-layout">
880
+ <div class=${'main-layout' + (fileEditor ? ' split' : '')}>
749
881
  <main class="chat ${dragOver ? 'drag-over' : ''}">
750
882
  ${dragOver ? html`<div class="drag-overlay">Drop files here to attach</div>` : null}
751
883
  ${messages.length === 0 ? html`
@@ -767,11 +899,48 @@ function App() {
767
899
  ${loading ? html`<div class="msg assistant"><div class="bubble loading">Thinking<span class="dots">...</span></div></div>` : null}
768
900
  ${toolLog.length > 0 ? html`<${ToolTimeline} tools=${toolLog} />` : null}
769
901
  </main>
902
+ ${fileEditor ? html`
903
+ <aside class="editor-pane">
904
+ <div class="editor-head">
905
+ <span class="editor-path" title=${fileEditor.path}>${fileEditor.path.split(/[\\/]/).pop()}</span>
906
+ <span class="editor-dirty">${fileEditor.dirty ? '●' : ''}</span>
907
+ <button class="btn-sm" onClick=${() => saveEditor()} disabled=${!fileEditor.dirty}>Save</button>
908
+ <button class="btn-sm" onClick=${() => setFileEditor(null)}>Close</button>
909
+ </div>
910
+ <textarea
911
+ class="editor-area"
912
+ value=${fileEditor.content}
913
+ onInput=${(e) => setFileEditor(Object.assign({}, fileEditor, { content: e.target.value, dirty: true }))}
914
+ spellcheck="false"
915
+ ></textarea>
916
+ </aside>
917
+ ` : null}
770
918
  </div>
771
919
  <footer class="composer">
920
+ ${attachments.length ? html`
921
+ <div class="attach-chips">
922
+ ${attachments.map((a) => html`
923
+ <div class="attach-chip" key=${a.id}>
924
+ <span class="attach-icon">📄</span>
925
+ <span class="attach-name" onClick=${() => setAttachPreview(a)} title="Preview">${a.name}</span>
926
+ <span class="attach-size">${(a.size / 1024).toFixed(1)} KB</span>
927
+ <button class="attach-remove" onClick=${() => setAttachments((prev) => prev.filter((x) => x.id !== a.id))} title="Remove">×</button>
928
+ </div>
929
+ `)}
930
+ </div>
931
+ ` : null}
772
932
  <textarea ref=${inputRef} value=${input} onInput=${(e) => setInput(e.target.value)} onKeyDown=${(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }} placeholder="Type a message... (Shift+Enter for new line, drag files to attach)" rows="2"></textarea>
773
- <button onClick=${send} disabled=${loading || !input.trim()}>Send</button>
933
+ <button onClick=${send} disabled=${loading || (!input.trim() && attachments.length === 0)}>Send</button>
774
934
  </footer>
935
+ ${attachPreview ? html`
936
+ <div class="modal-backdrop" onClick=${() => setAttachPreview(null)}>
937
+ <div class="modal" style="max-width: 720px" onClick=${(e) => e.stopPropagation()}>
938
+ <h2>${attachPreview.name}</h2>
939
+ <pre class="file-content">${attachPreview.content}</pre>
940
+ <div class="modal-actions"><button onClick=${() => setAttachPreview(null)}>Close</button></div>
941
+ </div>
942
+ </div>
943
+ ` : null}
775
944
  </div>
776
945
  `;
777
946
  }
package/public/style.css CHANGED
@@ -273,6 +273,45 @@ kbd { background: var(--panel); border: 1px solid var(--border); border-radius:
273
273
  .file-preview { flex: 1; border: 1px solid var(--border); border-radius: 6px; padding: 8px; max-height: 300px; overflow-y: auto; }
274
274
  .file-preview h3 { margin: 0 0 8px; font-size: 13px; }
275
275
  .file-content { font-size: 12px; line-height: 1.4; white-space: pre-wrap; word-break: break-all; margin: 0; }
276
+ /* Compare (side-by-side + diff) */
277
+ .compare-summary { display: flex; gap: 12px; flex-wrap: wrap; margin: 8px 0; }
278
+ .compare-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; margin-top: 8px; }
279
+ .compare-col { border: 1px solid var(--border); border-radius: 8px; background: var(--bg); overflow: hidden; display: flex; flex-direction: column; }
280
+ .compare-head { display: flex; justify-content: space-between; align-items: center; padding: 6px 8px; background: var(--panel); border-bottom: 1px solid var(--border); font-size: 12px; }
281
+ .compare-badge { font-size: 11px; padding: 1px 6px; border-radius: 10px; }
282
+ .compare-badge.ok { background: color-mix(in srgb, var(--success) 20%, transparent); color: var(--success); }
283
+ .compare-badge.err { background: color-mix(in srgb, var(--danger) 20%, transparent); color: var(--danger); }
284
+ .compare-body { max-height: 260px; overflow: auto; }
285
+ .compare-pre { margin: 0; padding: 8px; font-size: 12px; line-height: 1.45; white-space: pre-wrap; word-break: break-word; }
286
+ .compare-pre.err { color: var(--danger); }
287
+ .compare-pre.diff ins { background: color-mix(in srgb, var(--success) 30%, transparent); text-decoration: none; }
288
+ .compare-pre.diff del { background: color-mix(in srgb, var(--danger) 25%, transparent); text-decoration: line-through; opacity: 0.8; }
289
+
290
+ /* Attachment chips */
291
+ .attach-chips { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 6px; }
292
+ .attach-chip { display: flex; align-items: center; gap: 6px; border: 1px solid var(--border); background: var(--panel); border-radius: 14px; padding: 3px 8px; font-size: 12px; }
293
+ .attach-name { cursor: pointer; text-decoration: underline dotted; }
294
+ .attach-name:hover { color: var(--accent); }
295
+ .attach-size { color: var(--muted, #8b949e); font-size: 11px; }
296
+ .attach-remove { border: none; background: none; color: var(--fg); cursor: pointer; font-size: 14px; line-height: 1; padding: 0 2px; }
297
+ .attach-remove:hover { color: var(--danger); }
298
+
299
+ /* Session tags */
300
+ .tag-filter { display: flex; gap: 4px; flex-wrap: wrap; padding: 4px 8px; }
301
+ .tag-pill { font-size: 11px; padding: 2px 8px; border-radius: 10px; border: 1px solid var(--border); cursor: pointer; user-select: none; }
302
+ .tag-pill.small { font-size: 10px; padding: 0 6px; cursor: default; }
303
+ .tag-pill.active { background: var(--accent); color: #fff; border-color: var(--accent); }
304
+ .session-tags { display: flex; gap: 4px; flex-wrap: wrap; align-items: center; margin-top: 4px; }
305
+ .tag-input { flex: 1; min-width: 90px; font-size: 11px; padding: 2px 6px; border: 1px dashed var(--border); border-radius: 6px; background: var(--input); color: var(--fg); }
306
+
307
+ /* Split view editor */
308
+ .main-layout.split { display: grid; grid-template-columns: 1fr minmax(320px, 45%); }
309
+ .editor-pane { display: flex; flex-direction: column; border-left: 1px solid var(--border); background: var(--bg); min-height: 0; }
310
+ .editor-head { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-bottom: 1px solid var(--border); background: var(--panel); font-size: 12px; }
311
+ .editor-path { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: monospace; }
312
+ .editor-dirty { color: var(--warning); }
313
+ .editor-area { flex: 1; width: 100%; resize: none; border: none; outline: none; padding: 10px; background: var(--bg); color: var(--fg); font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; line-height: 1.5; }
314
+ .file-preview-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
276
315
  /* Compare */
277
316
  .compare-results { margin-top: 16px; max-height: 400px; overflow-y: auto; }
278
317
  .compare-card { background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 12px; margin-bottom: 8px; }
@@ -43,25 +43,37 @@ function toText(messages, meta) {
43
43
  return lines.join('\n');
44
44
  }
45
45
 
46
- // Simple PDF-like text output (not a real PDF, but a text file with .pdf extension for compatibility)
47
- // For real PDF, would need a library. This produces a readable text document.
46
+ // Real PDF via the zero-dependency writer.
48
47
  function toPDF(messages, meta) {
49
- // Produce a simple text-based document that can be opened in any text editor
50
- // In a real implementation, this would use a PDF library like pdfkit
51
- const text = toText(messages, meta);
52
- return { content: text, mimeType: 'text/plain', extension: '.txt', note: 'PDF generation requires pdfkit; returning text format' };
48
+ meta = meta || {};
49
+ const blocks = [];
50
+ blocks.push({ text: meta.title || 'Conversation Export', size: 20, bold: true, gap: 6 });
51
+ if (meta.model) blocks.push({ text: 'Model: ' + meta.model, size: 9, gray: 0.45 });
52
+ if (meta.date) blocks.push({ text: 'Date: ' + meta.date, size: 9, gray: 0.45 });
53
+ blocks.push({ text: '', gap: 8 });
54
+ for (const m of messages || []) {
55
+ const role = (m.role || 'unknown').charAt(0).toUpperCase() + (m.role || 'unknown').slice(1);
56
+ blocks.push({ text: role, size: 12, bold: true, gap: 10 });
57
+ const body = String(m.content || '');
58
+ for (const para of body.split(/\r?\n/)) {
59
+ blocks.push({ text: para, size: 10.5 });
60
+ }
61
+ blocks.push({ text: '', gap: 4 });
62
+ }
63
+ return require('./pdf_writer').buildPdf(blocks, meta);
53
64
  }
54
65
 
55
66
  function exportToFile(messages, meta, format, outputPath) {
56
67
  format = (format || 'markdown').toLowerCase();
57
- let content, ext;
68
+ let content, ext, encoding = 'utf8';
58
69
  if (format === 'json') { content = toJSON(messages, meta); ext = '.json'; }
59
70
  else if (format === 'text' || format === 'txt') { content = toText(messages, meta); ext = '.txt'; }
60
- else if (format === 'pdf') { const r = toPDF(messages, meta); content = r.content; ext = r.extension; }
71
+ else if (format === 'pdf') { content = toPDF(messages, meta); ext = '.pdf'; encoding = 'latin1'; }
61
72
  else { content = toMarkdown(messages, meta); ext = '.md'; }
62
73
  const filePath = outputPath || path.join(process.cwd(), 'conversation-export' + ext);
63
- fs.writeFileSync(filePath, content, 'utf8');
64
- return { ok: true, path: filePath, format, bytes: Buffer.byteLength(content) };
74
+ fs.writeFileSync(filePath, content, encoding === 'latin1' ? null : 'utf8');
75
+ const bytes = Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content);
76
+ return { ok: true, path: filePath, format: ext === '.pdf' ? 'pdf' : format, bytes };
65
77
  }
66
78
 
67
79
  module.exports = { toMarkdown, toJSON, toText, toPDF, exportToFile };
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
 
@@ -159,6 +160,24 @@ async function main() {
159
160
  const sessionToolLogs = new Map(); // session id -> last tool log (for /api/context)
160
161
  const sessionUpdated = new Map(); // session id -> ISO timestamp
161
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
+ }
162
181
  const pendingActions = new Map();
163
182
 
164
183
  function readJson(req) {
@@ -183,8 +202,16 @@ async function main() {
183
202
  }
184
203
 
185
204
  const handleRequest = async (req, res) => {
186
- // CORS headers (needed for browser fetch with application/json content type)
187
- res.setHeader('Access-Control-Allow-Origin', '*');
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
+ }
188
215
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
189
216
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
190
217
  if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
@@ -216,32 +243,37 @@ async function main() {
216
243
  if (req.method === 'POST' && req.url.split('?')[0] === '/api/chat') {
217
244
  const parsed = await readJson(req);
218
245
  const sid = parsed.sessionId || 'default';
219
- const history = Array.isArray(parsed.history) ? parsed.history : (sessions.get(sid) || []);
246
+ const history = Array.isArray(parsed.history) ? parsed.history : getSessionMessages(sid);
220
247
  const stream = parsed.stream === true;
221
248
  const autoApprove = process.env.AEGISAI_WEB_AUTO_APPROVE === 'true';
222
249
  if (stream) {
223
- 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' });
224
251
  let fullReply = '';
225
- const result = await runAgent({
226
- model: parsed.model || process.env.AEGISAI_MODEL || 'llama3.2:3b',
227
- messages: history.concat([{ role: 'user', content: parsed.message || '' }]),
228
- projectRoot: process.cwd(),
229
- onEvent: (e) => {
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'); }
234
- },
235
- autoApprove,
236
- approvalHandler: async () => false,
237
- });
238
- const reply = (result.final && result.final.final) || fullReply;
239
- const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
240
- sessions.set(sid, updated);
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');
244
- 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) {}
245
277
  return;
246
278
  }
247
279
  const result = await runAgent({
@@ -255,7 +287,7 @@ async function main() {
255
287
  });
256
288
  const reply = (result.final && result.final.final) || '';
257
289
  const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
258
- sessions.set(sid, updated);
290
+ rememberSession(sid, updated);
259
291
  sessionToolLogs.set(sid, result.toolLog || []);
260
292
  sessionUpdated.set(sid, new Date().toISOString());
261
293
  sendJson(res, 200, { reply, toolLog: result.toolLog || [], pendingActions: pendingActions.get(sid) || [] });
@@ -309,7 +341,7 @@ async function main() {
309
341
  if (req.method === 'POST' && req.url.split('?')[0] === '/api/export') {
310
342
  const parsed = await readJson(req);
311
343
  const sid = parsed.sessionId || 'default';
312
- const history = sessions.get(sid) || [];
344
+ const history = getSessionMessages(sid);
313
345
  const format = parsed.format || 'markdown';
314
346
  const meta = { title: parsed.title, model: process.env.AEGISAI_MODEL || 'llama3.2:3b', date: new Date().toISOString() };
315
347
  const result = require('./conversation_export').exportToFile(history.map((m) => ({ role: m.role, content: m.content })), meta, format, null);
@@ -320,7 +352,30 @@ async function main() {
320
352
  const parsed = await readJson(req);
321
353
  const models = parsed.models || [process.env.AEGISAI_MODEL || 'llama3.2:3b'];
322
354
  const result = await require('./model_compare').compare(parsed.prompt || '', models, { projectRoot: process.cwd() });
323
- sendJson(res, 200, { comparison: result, formatted: require('./model_compare').formatComparison(result) });
355
+ const analysis = require('./model_compare').analyze(result);
356
+ sendJson(res, 200, { comparison: result, formatted: require('./model_compare').formatComparison(result), analysis });
357
+ return;
358
+ }
359
+ if (req.method === 'POST' && req.url.split('?')[0] === '/api/diff') {
360
+ const parsed = await readJson(req);
361
+ const d = require('./text_diff');
362
+ sendJson(res, 200, { diff: d.diffWords(parsed.a || '', parsed.b || ''), similarity: +d.similarity(parsed.a || '', parsed.b || '').toFixed(3) });
363
+ return;
364
+ }
365
+ if (req.method === 'POST' && req.url.split('?')[0] === '/api/file') {
366
+ const parsed = await readJson(req);
367
+ const target = parsed.path;
368
+ if (!target) { sendJson(res, 400, { error: 'path required' }); return; }
369
+ const allowed = (process.env.AEGISAI_PROJECT_ROOT_ALLOWLIST || '').split(',').map((s) => s.trim()).filter(Boolean);
370
+ const path = require('path');
371
+ const resolved = path.resolve(target);
372
+ if (allowed.length && !allowed.some((root) => { const rel = path.relative(path.resolve(root), resolved); return !rel.startsWith('..') && !path.isAbsolute(rel); })) {
373
+ sendJson(res, 403, { error: 'path outside allowed roots' }); return;
374
+ }
375
+ try {
376
+ require('fs').writeFileSync(resolved, String(parsed.content == null ? '' : parsed.content), 'utf8');
377
+ sendJson(res, 200, { ok: true, path: resolved, bytes: Buffer.byteLength(String(parsed.content || '')) });
378
+ } catch (e) { sendJson(res, 500, { error: String(e.message || e) }); }
324
379
  return;
325
380
  }
326
381
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/models/hf-search') {
@@ -451,24 +506,42 @@ async function main() {
451
506
  const wantId = u.searchParams.get('id');
452
507
  if (wantId) {
453
508
  const sid = warnMissing(wantId);
454
- const msgs = sessions.get(sid) || [];
509
+ const msgs = getSessionMessages(sid);
455
510
  sendJson(res, 200, { id: sid, messages: msgs });
456
511
  return;
457
512
  }
458
- const list = [];
513
+ const byId = new Map();
514
+ // Persisted sessions first (survive restarts).
515
+ try {
516
+ const d = dbSafe();
517
+ for (const s of (d ? d.listSessions() : [])) {
518
+ byId.set(s.id, { id: s.id, title: s.title || s.id, messages: (s.messages || []).length, updated: s.updated || null, tags: s.tags || [] });
519
+ }
520
+ } catch (e) {}
521
+ // Merge live in-memory sessions (fresher).
459
522
  for (const [id, msgs] of sessions.entries()) {
460
523
  const firstUser = (msgs || []).find((m) => m.role === 'user');
461
- list.push({
524
+ byId.set(id, {
462
525
  id,
463
526
  title: firstUser ? String(firstUser.content || '').slice(0, 60) : id,
464
527
  messages: (msgs || []).length,
465
- updated: sessionUpdated.get(id) || null,
528
+ updated: sessionUpdated.get(id) || (byId.get(id) || {}).updated || null,
529
+ tags: (byId.get(id) || {}).tags || [],
466
530
  });
467
531
  }
468
- list.sort((a, b) => String(b.updated || '').localeCompare(String(a.updated || '')));
532
+ const list = Array.from(byId.values()).sort((a, b) => String(b.updated || '').localeCompare(String(a.updated || '')));
469
533
  sendJson(res, 200, { sessions: list });
470
534
  return;
471
535
  }
536
+ if (req.method === 'POST' && req.url.split('?')[0] === '/api/sessions/tags') {
537
+ const parsed = await readJson(req);
538
+ const sid = warnMissing(parsed.id);
539
+ const tags = Array.isArray(parsed.tags) ? parsed.tags.map((t) => String(t).trim()).filter(Boolean) : [];
540
+ const d = dbSafe();
541
+ const r = d ? d.setSessionTags(sid, tags) : { ok: false, error: 'db unavailable' };
542
+ sendJson(res, r.ok ? 200 : 500, r);
543
+ return;
544
+ }
472
545
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/events') {
473
546
  require('./event_stream').subscribe(res, req);
474
547
  return;
@@ -565,7 +638,7 @@ async function main() {
565
638
  }
566
639
  if (req.method === 'POST' && req.url.split('?')[0] === '/api/config') {
567
640
  const parsed = await readJson(req);
568
- if (parsed.projectRootAllowlist) process.env.AEGISAI_PROJECT_ROOT_ALLOWLIST = parsed.projectRootAllowlist;
641
+ if (parsed.projectRootAllowlist !== undefined) process.env.AEGISAI_PROJECT_ROOT_ALLOWLIST = parsed.projectRootAllowlist;
569
642
  if (parsed.sttUrl !== undefined) process.env.STT_URL = parsed.sttUrl;
570
643
  if (parsed.ttsUrl !== undefined) process.env.TTS_URL = parsed.ttsUrl;
571
644
  for (const k of ['BACKEND_TYPE', 'BACKEND_URL', 'AEGISAI_MODEL', 'AEGISAI_TOKEN', 'AEGISAI_WEB_AUTO_APPROVE', 'REA_BIN', 'GHIDRA_MCP_URL', 'CRAFT_BIN']) {
@@ -654,37 +727,91 @@ async function main() {
654
727
  if (proxyFlag) {
655
728
  const http = require('http');
656
729
  const port = parseInt(process.env.AEGISAI_PROXY_PORT || '4000', 10);
730
+ const host = process.env.HOST || '127.0.0.1';
731
+ const MAX_BODY = parseInt(process.env.AEGISAI_PROXY_MAX_BODY || String(10 * 1024 * 1024), 10);
732
+ const proxyToken = () => process.env.AEGISAI_TOKEN || process.env.LOCALAI_TOKEN || '';
733
+ const sendErr = (res, status, message, type) => {
734
+ try { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message, type: type || 'invalid_request_error' } })); } catch (e) {}
735
+ };
657
736
  const server = http.createServer(async (req, res) => {
658
- if (req.method === 'POST' && req.url.includes('/chat/completions')) {
737
+ const urlPath = req.url.split('?')[0];
738
+ // Auth when a token is configured.
739
+ const expected = proxyToken();
740
+ if (expected) {
741
+ const supplied = (req.headers['authorization'] || '').replace(/^Bearer\s+/i, '') || new URL(req.url, 'http://x').searchParams.get('token') || '';
742
+ if (!tokenMatches(supplied, expected)) { sendErr(res, 401, 'unauthorized', 'authentication_error'); return; }
743
+ }
744
+ if (req.method === 'GET' && (urlPath === '/v1/models' || urlPath === '/models')) {
745
+ let ids = [];
746
+ try { const r = await require('./backends').backendListModels(); ids = (r.models || []).map((m) => m.name || m); } catch (e) {}
747
+ if (!ids.length) ids = [process.env.AEGISAI_MODEL || 'llama3.2:3b'];
748
+ res.writeHead(200, { 'Content-Type': 'application/json' });
749
+ res.end(JSON.stringify({ object: 'list', data: ids.map((id) => ({ id, object: 'model', owned_by: 'aegisai' })) }));
750
+ return;
751
+ }
752
+ if (req.method === 'POST' && (urlPath === '/v1/chat/completions' || urlPath === '/chat/completions')) {
659
753
  let body = '';
660
- let aborted = false;
661
- req.on('aborted', () => { aborted = true; });
662
- req.on('close', () => { if (!req.complete) aborted = true; });
663
- req.on('data', (c) => { body += c; });
754
+ let bytes = 0;
755
+ let tooBig = false;
756
+ req.on('data', (c) => {
757
+ if (tooBig) return;
758
+ bytes += c.length;
759
+ if (bytes > MAX_BODY) { tooBig = true; sendErr(res, 413, 'request body too large'); return; }
760
+ body += c;
761
+ });
664
762
  req.on('end', async () => {
763
+ if (tooBig) return;
764
+ let parsed;
765
+ try { parsed = JSON.parse(body); } catch (e) { sendErr(res, 400, 'invalid JSON body'); return; }
766
+ const model = parsed.model || process.env.AEGISAI_MODEL || 'llama3.2:3b';
767
+ if (parsed.stream) {
768
+ let headersSent = false;
769
+ const send = (obj) => {
770
+ try {
771
+ if (!headersSent) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }); headersSent = true; }
772
+ if (!res.writableEnded) res.write('data: ' + JSON.stringify(obj) + '\n\n');
773
+ } catch (e) {}
774
+ };
775
+ try {
776
+ let text = '';
777
+ await runAgent({
778
+ model,
779
+ messages: parsed.messages || [],
780
+ projectRoot: process.cwd(),
781
+ onEvent: (e) => {
782
+ if (e.type === 'token' && e.content) {
783
+ text += e.content;
784
+ 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 }] });
785
+ }
786
+ },
787
+ autoApprove: true,
788
+ });
789
+ send({ id: 'chatcmpl-x', object: 'chat.completion.chunk', created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] });
790
+ try { if (!res.writableEnded) { res.write('data: [DONE]\n\n'); res.end(); } } catch (e) {}
791
+ } catch (e) {
792
+ if (!headersSent) sendErr(res, 500, String(e.message || e), 'server_error');
793
+ else { try { res.write('data: [DONE]\n\n'); res.end(); } catch (_) {} }
794
+ }
795
+ return;
796
+ }
665
797
  try {
666
- const parsed = JSON.parse(body);
667
- if (aborted) return;
668
798
  const result = await runAgent({
669
- model: parsed.model || process.env.AEGISAI_MODEL || 'llama3.2:3b',
799
+ model,
670
800
  messages: parsed.messages || [],
671
801
  projectRoot: process.cwd(),
672
802
  onEvent: () => {},
673
803
  autoApprove: true,
674
804
  });
675
- 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' }] };
805
+ 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' }] };
676
806
  res.writeHead(200, { 'Content-Type': 'application/json' });
677
807
  res.end(JSON.stringify(resp));
678
- } catch (e) {
679
- res.writeHead(500, { 'Content-Type': 'application/json' });
680
- res.end(JSON.stringify({ error: String(e.message || e) }));
681
- }
808
+ } catch (e) { sendErr(res, 500, String(e.message || e), 'server_error'); }
682
809
  });
683
- } else {
684
- res.writeHead(404); res.end();
810
+ return;
685
811
  }
812
+ sendErr(res, 404, 'not found', 'invalid_request_error');
686
813
  });
687
- server.listen(port, () => console.log('Proxy listening on :' + port));
814
+ server.listen(port, host, () => console.log('Proxy listening on http://' + host + ':' + port));
688
815
  return;
689
816
  }
690
817
 
@@ -68,4 +68,21 @@ function formatComparison(comparison) {
68
68
  return lines.join('\n');
69
69
  }
70
70
 
71
- module.exports = { compare, formatComparison };
71
+ // Pairwise similarity matrix + per-response token counts, for the comparison UI.
72
+ function analyze(comparison) {
73
+ const { similarity } = require('./text_diff');
74
+ const ok = (comparison.results || []).filter((r) => r.ok);
75
+ const pairs = [];
76
+ for (let i = 0; i < ok.length; i++) {
77
+ for (let j = i + 1; j < ok.length; j++) {
78
+ pairs.push({ a: ok[i].model, b: ok[j].model, similarity: +similarity(ok[i].reply, ok[j].reply).toFixed(3) });
79
+ }
80
+ }
81
+ return {
82
+ pairs,
83
+ lengths: ok.map((r) => ({ model: r.model, chars: (r.reply || '').length, words: (r.reply || '').split(/\s+/).filter(Boolean).length, duration: r.duration })),
84
+ agreement: pairs.length ? +(pairs.reduce((s, p) => s + p.similarity, 0) / pairs.length).toFixed(3) : null,
85
+ };
86
+ }
87
+
88
+ module.exports = { compare, formatComparison, analyze };
@@ -0,0 +1,132 @@
1
+ // src/pdf_writer.js
2
+ // Minimal, zero-dependency PDF 1.4 writer (Helvetica text only).
3
+ // Good enough for conversation exports: headings, body text, code blocks, page breaks.
4
+ const PAGE_W = 612; // US Letter
5
+ const PAGE_H = 792;
6
+ const MARGIN = 56;
7
+
8
+ // Approximate Helvetica advance widths (fraction of font size).
9
+ function charWidth(ch) {
10
+ if (ch === ' ') return 0.278;
11
+ if ('iljI.,:;\'`|!'.includes(ch)) return 0.222;
12
+ if ('ft()[]{}'.includes(ch)) return 0.333;
13
+ if ('mwMW'.includes(ch)) return 0.833;
14
+ if (ch >= 'A' && ch <= 'Z') return 0.667;
15
+ if (ch >= '0' && ch <= '9') return 0.556;
16
+ if (ch === '-') return 0.333;
17
+ return 0.5;
18
+ }
19
+ function textWidth(s, size) {
20
+ let w = 0;
21
+ for (const ch of s) w += charWidth(ch);
22
+ return w * size;
23
+ }
24
+ function escapePdf(s) {
25
+ return String(s == null ? '' : s)
26
+ .replace(/\\/g, '\\\\')
27
+ .replace(/\(/g, '\\(')
28
+ .replace(/\)/g, '\\)')
29
+ // Drop characters Helvetica/WinAnsi can't represent predictably.
30
+ .replace(/[^\x20-\x7e]/g, (c) => (c === '\t' ? ' ' : ''));
31
+ }
32
+ function wrap(text, size, maxWidth) {
33
+ const words = String(text == null ? '' : text).split(/\s+/);
34
+ const lines = [];
35
+ let cur = '';
36
+ for (const w of words) {
37
+ const next = cur ? cur + ' ' + w : w;
38
+ if (textWidth(next, size) <= maxWidth || !cur) cur = next;
39
+ else { lines.push(cur); cur = w; }
40
+ }
41
+ if (cur) lines.push(cur);
42
+ return lines.length ? lines : [''];
43
+ }
44
+
45
+ /**
46
+ * blocks: [{ text, size?, bold?, gap?, code? }]
47
+ * Returns a Buffer containing a valid PDF.
48
+ */
49
+ function buildPdf(blocks, meta) {
50
+ meta = meta || {};
51
+ const size = 11;
52
+ const lineH = (s) => Math.round(s * 1.42);
53
+ const maxW = PAGE_W - MARGIN * 2;
54
+
55
+ // Layout into pages of positioned runs.
56
+ const pages = [];
57
+ let runs = [];
58
+ let y = PAGE_H - MARGIN;
59
+
60
+ const newPage = () => {
61
+ // header/footer on each page
62
+ if (runs.length) pages.push(runs);
63
+ runs = [];
64
+ y = PAGE_H - MARGIN;
65
+ runs.push({ text: meta.title || 'Conversation Export', size: 9, bold: false, x: MARGIN, y: PAGE_H - 30, gray: 0.45 });
66
+ runs.push({ text: 'Page ' + (pages.length + 1), size: 9, bold: false, x: PAGE_W - MARGIN - 45, y: 30, gray: 0.45 });
67
+ };
68
+ newPage();
69
+
70
+ for (const b of blocks || []) {
71
+ const s = b.size || size;
72
+ const bold = Boolean(b.bold);
73
+ const lh = lineH(s);
74
+ const gapBefore = b.gap ? Math.round(b.gap) : 0;
75
+ y -= gapBefore;
76
+ const lines = b.noWrap ? [String(b.text || '')] : wrap(b.text, s, maxW - (b.indent || 0));
77
+ for (const line of lines) {
78
+ if (y - lh < MARGIN) newPage();
79
+ y -= lh;
80
+ runs.push({ text: line, size: s, bold, x: MARGIN + (b.indent || 0), y, gray: b.gray });
81
+ }
82
+ }
83
+ if (runs.length) pages.push(runs);
84
+
85
+ // Build content streams.
86
+ const contentOf = (pageRuns) => {
87
+ let out = '';
88
+ for (const r of pageRuns) {
89
+ const font = r.bold ? '/F2' : '/F1';
90
+ const gray = typeof r.gray === 'number' ? r.gray : 0;
91
+ out += 'BT ' + font + ' ' + r.size + ' Tf ' + gray + ' g ' + r.x + ' ' + r.y + ' Td (' + escapePdf(r.text) + ') Tj ET\n';
92
+ }
93
+ return out;
94
+ };
95
+
96
+ // Objects: 1 catalog, 2 pages, then per page (page + content), then fonts.
97
+ const objs = [];
98
+ const add = (s) => { objs.push(s); return objs.length; };
99
+ const catalogId = add('<< /Type /Catalog /Pages 2 0 R >>');
100
+ const pagesId = 2; // reserved below
101
+ objs.push('PLACEHOLDER_PAGES'); // index 1 → id 2
102
+ const pageIds = [];
103
+ const contentIds = [];
104
+ for (let i = 0; i < pages.length; i++) {
105
+ const content = contentOf(pages[i]);
106
+ const cId = add('<< /Length ' + Buffer.byteLength(content, 'latin1') + ' >>\nstream\n' + content + 'endstream');
107
+ contentIds.push(cId);
108
+ const pId = add('<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ' + PAGE_W + ' ' + PAGE_H + '] /Resources << /Font << /F1 100 0 R /F2 101 0 R >> >> /Contents ' + cId + ' 0 R >>');
109
+ pageIds.push(pId);
110
+ }
111
+ const f1 = add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>');
112
+ const f2 = add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>');
113
+ objs[pagesId - 1] = '<< /Type /Pages /Kids [' + pageIds.map((i) => i + ' 0 R').join(' ') + '] /Count ' + pages.length + ' >>';
114
+
115
+ // Assemble with cross-reference table.
116
+ let pdf = '%PDF-1.4\n%\xE2\xE3\xCF\xD3\n';
117
+ const offsets = [0];
118
+ for (let i = 0; i < objs.length; i++) {
119
+ offsets[i + 1] = Buffer.byteLength(pdf, 'latin1');
120
+ pdf += (i + 1) + ' 0 obj\n' + objs[i] + '\nendobj\n';
121
+ }
122
+ const xrefStart = Buffer.byteLength(pdf, 'latin1');
123
+ pdf += 'xref\n0 ' + (objs.length + 1) + '\n';
124
+ pdf += '0000000000 65535 f \n';
125
+ for (let i = 1; i <= objs.length; i++) {
126
+ pdf += String(offsets[i]).padStart(10, '0') + ' 00000 n \n';
127
+ }
128
+ pdf += 'trailer\n<< /Size ' + (objs.length + 1) + ' /Root 1 0 R >>\nstartxref\n' + xrefStart + '\n%%EOF\n';
129
+ return Buffer.from(pdf, 'latin1');
130
+ }
131
+
132
+ module.exports = { buildPdf, escapePdf, wrap, PAGE_W, PAGE_H };
package/src/storage/db.js CHANGED
@@ -143,6 +143,9 @@ function open(dbPath) {
143
143
  db.exec(`CREATE TABLE IF NOT EXISTS access_tokens (id TEXT PRIMARY KEY, token TEXT, name TEXT, scopes TEXT, created TEXT)`);
144
144
  db.exec(`CREATE TABLE IF NOT EXISTS metrics (name TEXT, value REAL, labels TEXT, ts INTEGER)`);
145
145
  },
146
+ function v26() {
147
+ try { db.exec(`ALTER TABLE sessions ADD COLUMN tags TEXT DEFAULT '[]'`); } catch (e) {}
148
+ },
146
149
  ];
147
150
  for (let i = currentVersion; i < migrations.length; i++) {
148
151
  migrations[i]();
@@ -165,10 +168,16 @@ function run(sql, params) { db.prepare(sql).run(...(params || [])); }
165
168
  function rowToSession(r) {
166
169
  let messages = [];
167
170
  try { messages = JSON.parse(r.messages || '[]'); } catch (e) { messages = []; }
168
- return { id: r.id, title: r.title, updated: r.updated, parent_id: r.parent_id, branch_from: r.branch_from, messages };
171
+ let tags = [];
172
+ try { tags = JSON.parse(r.tags || '[]'); } catch (e) { tags = []; }
173
+ return { id: r.id, title: r.title, updated: r.updated, parent_id: r.parent_id, branch_from: r.branch_from, messages, tags };
169
174
  }
170
- function listSessions() { return all('SELECT id, title, updated, parent_id, branch_from FROM sessions ORDER BY updated DESC').map(rowToSession); }
175
+ function listSessions() { return all('SELECT * FROM sessions ORDER BY updated DESC').map(rowToSession); }
171
176
  function getSession(id) { const row = one('SELECT * FROM sessions WHERE id = ?', [id]); return row ? rowToSession(row) : null; }
177
+ function setSessionTags(id, tags) {
178
+ try { run('UPDATE sessions SET tags=? WHERE id=?', [JSON.stringify(tags || []), id]); return { ok: true, id, tags: tags || [] }; }
179
+ catch (e) { return { ok: false, error: String(e.message || e) }; }
180
+ }
172
181
  function saveSession(s) {
173
182
  const id = s.id || ('sess_' + Date.now());
174
183
  const title = s.title || 'Untitled';
@@ -176,11 +185,16 @@ function saveSession(s) {
176
185
  const updated = new Date().toISOString();
177
186
  const parentId = s.parent_id || null;
178
187
  const branchFrom = (s.branch_from === undefined) ? null : s.branch_from;
188
+ const tags = JSON.stringify(s.tags || []);
179
189
  const existing = one('SELECT id FROM sessions WHERE id = ?', [id]);
180
190
  if (existing) {
181
- run('UPDATE sessions SET title=?, updated=?, messages=?, parent_id=?, branch_from=? WHERE id=?', [title, updated, messages, parentId, branchFrom, id]);
191
+ run('UPDATE sessions SET title=?, updated=?, messages=?, parent_id=?, branch_from=?, tags=? WHERE id=?', [title, updated, messages, parentId, branchFrom, tags, id]);
182
192
  } else {
183
- run('INSERT INTO sessions (id, title, updated, parent_id, branch_from, messages) VALUES (?,?,?,?,?,?)', [id, title, updated, parentId, branchFrom, messages]);
193
+ try {
194
+ run('INSERT INTO sessions (id, title, updated, parent_id, branch_from, messages, tags) VALUES (?,?,?,?,?,?,?)', [id, title, updated, parentId, branchFrom, messages, tags]);
195
+ } catch (e) {
196
+ run('INSERT INTO sessions (id, title, updated, parent_id, branch_from, messages) VALUES (?,?,?,?,?,?)', [id, title, updated, parentId, branchFrom, messages]);
197
+ }
184
198
  }
185
199
  return id;
186
200
  }
@@ -214,5 +228,5 @@ function saveMemory(m) {
214
228
  function deleteMemory(id) { run('DELETE FROM memories WHERE id = ?', [id]); }
215
229
 
216
230
  module.exports = { open, get, isOpen, close, backend,
217
- listSessions, getSession, saveSession, deleteSession,
231
+ listSessions, getSession, saveSession, deleteSession, setSessionTags,
218
232
  listMemories, getMemory, saveMemory, deleteMemory };
@@ -0,0 +1,48 @@
1
+ // src/text_diff.js
2
+ // Word-level diff (LCS) for comparing model responses side by side.
3
+ function tokenize(s) {
4
+ return String(s == null ? '' : s).split(/(\s+)/).filter((t) => t !== '');
5
+ }
6
+ function diffWords(a, b) {
7
+ const A = tokenize(a);
8
+ const B = tokenize(b);
9
+ const n = A.length;
10
+ const m = B.length;
11
+ // LCS table (bounded to keep memory sane for very long replies).
12
+ const cap = 4000;
13
+ const an = Math.min(n, cap);
14
+ const bm = Math.min(m, cap);
15
+ const dp = Array.from({ length: an + 1 }, () => new Uint32Array(bm + 1));
16
+ for (let i = an - 1; i >= 0; i--) {
17
+ for (let j = bm - 1; j >= 0; j--) {
18
+ dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
19
+ }
20
+ }
21
+ const out = [];
22
+ let i = 0; let j = 0;
23
+ while (i < an && j < bm) {
24
+ if (A[i] === B[j]) { out.push({ type: 'same', text: A[i] }); i++; j++; }
25
+ else if (dp[i + 1][j] >= dp[i][j + 1]) { out.push({ type: 'del', text: A[i] }); i++; }
26
+ else { out.push({ type: 'add', text: B[j] }); j++; }
27
+ }
28
+ while (i < an) { out.push({ type: 'del', text: A[i++] }); }
29
+ while (j < bm) { out.push({ type: 'add', text: B[j++] }); }
30
+ if (n > an) out.push({ type: 'del', text: ' …' + (n - an) + ' more words' });
31
+ if (m > bm) out.push({ type: 'add', text: ' …' + (m - bm) + ' more words' });
32
+ return out;
33
+ }
34
+ // Similarity ratio 0..1 (1 = identical).
35
+ function similarity(a, b) {
36
+ const A = tokenize(a);
37
+ const B = tokenize(b);
38
+ if (!A.length && !B.length) return 1;
39
+ const setB = new Map();
40
+ for (const t of B) setB.set(t, (setB.get(t) || 0) + 1);
41
+ let common = 0;
42
+ for (const t of A) {
43
+ const c = setB.get(t) || 0;
44
+ if (c > 0) { common++; setB.set(t, c - 1); }
45
+ }
46
+ return (2 * common) / (A.length + B.length);
47
+ }
48
+ module.exports = { diffWords, similarity, tokenize };
package/src/tui.js CHANGED
@@ -28,19 +28,30 @@ 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) {
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.75.0';
3
+ const VERSION = '0.77.0';
4
4
  module.exports = { VERSION, version: VERSION };