aegisai-harness 0.76.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.76.0] - 2026-11-25
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.76.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.76.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.76.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.76.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.76.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,10 +530,16 @@ 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
@@ -565,6 +631,7 @@ function App() {
565
631
  const [comparePrompt, setComparePrompt] = useState('');
566
632
  const [compareResult, setCompareResult] = useState(null);
567
633
  const [comparing, setComparing] = useState(false);
634
+ const [compareDiff, setCompareDiff] = useState(false);
568
635
 
569
636
  async function exportChat(format) {
570
637
  try {
@@ -599,6 +666,24 @@ function App() {
599
666
  } catch (e) { toast('Failed to read file: ' + e.message, 'error'); }
600
667
  }
601
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
+
602
687
  async function runCompare() {
603
688
  if (!comparePrompt.trim() || !compareModels.trim()) { toast('Enter a prompt and models', 'error'); return; }
604
689
  setComparing(true);
@@ -715,7 +800,10 @@ function App() {
715
800
  </div>
716
801
  ${selectedFile ? html`
717
802
  <div class="file-preview">
718
- <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>
719
807
  <pre class="file-content">${fileContent.slice(0, 5000)}</pre>
720
808
  </div>
721
809
  ` : null}
@@ -741,14 +829,29 @@ function App() {
741
829
  <button onClick=${() => setShowCompare(false)}>Close</button>
742
830
  </div>
743
831
  ${compareResult ? html`
744
- <div class="compare-results">
745
- ${compareResult.comparison.results.map((r) => html`
746
- <div class="compare-card">
747
- <h3>${r.model} ${r.ok ? '✓' : '✗'} ${r.duration}ms</h3>
748
- <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>
749
850
  </div>
750
851
  `)}
751
- <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>
752
855
  </div>
753
856
  ` : null}
754
857
  </div>
@@ -774,7 +877,7 @@ function App() {
774
877
  <button onClick=${() => setShowCompare(true)} title="Compare models">⚖️</button>
775
878
  <button onClick=${() => setShowHelp(true)} title="Help (Ctrl+/)">?</button>
776
879
  </header>
777
- <div class="main-layout">
880
+ <div class=${'main-layout' + (fileEditor ? ' split' : '')}>
778
881
  <main class="chat ${dragOver ? 'drag-over' : ''}">
779
882
  ${dragOver ? html`<div class="drag-overlay">Drop files here to attach</div>` : null}
780
883
  ${messages.length === 0 ? html`
@@ -796,11 +899,48 @@ function App() {
796
899
  ${loading ? html`<div class="msg assistant"><div class="bubble loading">Thinking<span class="dots">...</span></div></div>` : null}
797
900
  ${toolLog.length > 0 ? html`<${ToolTimeline} tools=${toolLog} />` : null}
798
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}
799
918
  </div>
800
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}
801
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>
802
- <button onClick=${send} disabled=${loading || !input.trim()}>Send</button>
933
+ <button onClick=${send} disabled=${loading || (!input.trim() && attachments.length === 0)}>Send</button>
803
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}
804
944
  </div>
805
945
  `;
806
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
@@ -352,7 +352,30 @@ async function main() {
352
352
  const parsed = await readJson(req);
353
353
  const models = parsed.models || [process.env.AEGISAI_MODEL || 'llama3.2:3b'];
354
354
  const result = await require('./model_compare').compare(parsed.prompt || '', models, { projectRoot: process.cwd() });
355
- 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) }); }
356
379
  return;
357
380
  }
358
381
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/models/hf-search') {
@@ -492,7 +515,7 @@ async function main() {
492
515
  try {
493
516
  const d = dbSafe();
494
517
  for (const s of (d ? d.listSessions() : [])) {
495
- byId.set(s.id, { id: s.id, title: s.title || s.id, messages: (s.messages || []).length, updated: s.updated || null });
518
+ byId.set(s.id, { id: s.id, title: s.title || s.id, messages: (s.messages || []).length, updated: s.updated || null, tags: s.tags || [] });
496
519
  }
497
520
  } catch (e) {}
498
521
  // Merge live in-memory sessions (fresher).
@@ -503,12 +526,22 @@ async function main() {
503
526
  title: firstUser ? String(firstUser.content || '').slice(0, 60) : id,
504
527
  messages: (msgs || []).length,
505
528
  updated: sessionUpdated.get(id) || (byId.get(id) || {}).updated || null,
529
+ tags: (byId.get(id) || {}).tags || [],
506
530
  });
507
531
  }
508
532
  const list = Array.from(byId.values()).sort((a, b) => String(b.updated || '').localeCompare(String(a.updated || '')));
509
533
  sendJson(res, 200, { sessions: list });
510
534
  return;
511
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
+ }
512
545
  if (req.method === 'GET' && req.url.split('?')[0] === '/api/events') {
513
546
  require('./event_stream').subscribe(res, req);
514
547
  return;
@@ -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
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/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.76.0';
3
+ const VERSION = '0.77.0';
4
4
  module.exports = { VERSION, version: VERSION };