aegisai-harness 0.76.0 → 0.78.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 +1 -1
- package/README.md +1 -1
- package/ROADMAP.md +82 -0
- package/llms.txt +1 -1
- package/package.json +1 -1
- package/packaging/windows/installer.iss +2 -2
- package/public/app.js +163 -23
- package/public/style.css +39 -0
- package/src/conversation_export.js +22 -10
- package/src/index.js +102 -17
- package/src/mcp_server.js +32 -4
- package/src/model_compare.js +18 -1
- package/src/pdf_writer.js +132 -0
- package/src/storage/db.js +18 -4
- package/src/text_diff.js +48 -0
- package/src/tui.js +4 -17
- package/src/version.js +1 -1
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.
|
|
5
|
+
## [0.78.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.
|
|
13
|
+
> Status: v0.78.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/ROADMAP.md
CHANGED
|
@@ -457,6 +457,88 @@ Feasibility: **H** = fits current JS architecture, **M** = needs external servic
|
|
|
457
457
|
- [x] Codex-style approval modes: suggest / auto-edit / full-auto — **H**
|
|
458
458
|
- [ ] Codex-style MCP server configuration patterns — **H** (covered)
|
|
459
459
|
|
|
460
|
+
## v0.78 — From nvidia, cloudflare, trufflesecurity, semgrep, cisco-talos, haydenschmitty, sandbox-quantum, plus re-scan of bytedance/openai/modelcontextprotocol
|
|
461
|
+
Feasibility: **H** = fits current JS architecture, **M** = needs external service/tool, **L** = native/platform-scale.
|
|
462
|
+
|
|
463
|
+
### LLM red-teaming (nvidia/garak)
|
|
464
|
+
- [ ] Model behaviour probe suite — hallucination, jailbreak, prompt-injection, data-leakage, toxicity probes run against the configured backend with scored pass/fail and a JSON report. Sits beside the existing code-pattern scanner (`vuln_scan`) and harness `adversarial` suite. — **H**
|
|
465
|
+
|
|
466
|
+
### Skill & plugin security (nvidia/SkillSpector)
|
|
467
|
+
- [ ] Dedicated skill scanner — extend `skill_eval` with SkillSpector-style rule classes: malicious patterns, prompt injection, data exfiltration intent, credential access, unsafe tool grants, obfuscation. Emit SARIF. — **H**
|
|
468
|
+
|
|
469
|
+
### Verified secret scanning (trufflesecurity/trufflehog)
|
|
470
|
+
- [ ] Detect **and verify** credentials — current tooling does regex/PII only. Add provider-aware verifiers (GitHub, Slack, AWS, Stripe, SendGrid, npm, OpenAI-style keys) that confirm liveness, with an explicit offline mode that reports `unverified`. — **H**
|
|
471
|
+
|
|
472
|
+
### Multi-phase security audit with independent verification (cloudflare/security-audit-skill)
|
|
473
|
+
- [ ] Audit pipeline upgrade — recon → candidate findings → **independent re-verification pass that drops false positives** → machine-readable SARIF/JSON with evidence per finding. Replaces the current single-pass `pentest_pipeline`. — **H**
|
|
474
|
+
|
|
475
|
+
### MCP testing & registry alignment (modelcontextprotocol/inspector, /registry)
|
|
476
|
+
- [ ] `mcp-inspect` command — deterministic MCP server tests: tool schema validity, error-path behaviour, resource/prompt round-trips, timeouts; machine-readable results. — **H**
|
|
477
|
+
- [ ] Align registry client with the official MCP registry API (`modelcontextprotocol/registry`) instead of the hand-rolled catalog. — **M**
|
|
478
|
+
|
|
479
|
+
### Cross-agent delegation (openai/codex-plugin-cc, openai/skills)
|
|
480
|
+
- [ ] External agent adapters — delegate a task to a locally installed `codex` / `claude` / `aider` CLI and capture the result as an evidence record. Complements `agents_as_tools` and `peer_review`. — **M**
|
|
481
|
+
- [ ] Codex skills catalog import — map the public skills catalog onto `skill_pkg`/`default_skills`. — **M**
|
|
482
|
+
|
|
483
|
+
### Visual grounding for computer use (bytedance/UI-TARS-desktop)
|
|
484
|
+
- [ ] Screenshot → vision → coordinate click — extend the CDP browser tools with `browser_screenshot`, `browser_click_at(x,y)` and a vision-model locator ("click the Submit button") using the existing `vision.js`. — **H**
|
|
485
|
+
|
|
486
|
+
### Plain-English architecture map (haydenschmitty/floorplan)
|
|
487
|
+
- [ ] Interactive architecture map page — render `code_map` as a navigable module/edge diagram in the web UI with plain-English summaries per module. — **H**
|
|
488
|
+
|
|
489
|
+
### Channels & trust (sandbox-quantum/switch, switch-trust-*)
|
|
490
|
+
- [ ] Microsoft Teams + Mattermost channel adapters — completes the IM set alongside Slack/Telegram/Discord/DingTalk/Feishu. — **M**
|
|
491
|
+
- [ ] Guardrail routing SDK surface — expose the guardrails/policy engine as a small documented JS API (`evaluate(tool, args)`) so external tools can reuse it. — **H**
|
|
492
|
+
- [ ] Project-wide symbol rename — LSP `rename` + apply-edits across the workspace. — **M**
|
|
493
|
+
|
|
494
|
+
### Malware & artifact hygiene (cisco-talos)
|
|
495
|
+
- [ ] Attachment malware scan — if `clamscan` is present, scan dropped/ingested files before the agent reads them; quarantine and report. — **M**
|
|
496
|
+
- [ ] Binary function similarity for RE — near-duplicate function detection across builds to support diffing patched binaries (feeds `re_index` / Ghidra workflow). — **M**
|
|
497
|
+
- [ ] Synthetic security log corpus (talos/EvidenceForge) — generated hunt datasets for testing `security_kb` and detection rules. — **H**
|
|
498
|
+
- [ ] IoC feed import (talos/IOCs) — load indicators into `security_kb` with hashes/domains/IPs for offline matching. — **H**
|
|
499
|
+
|
|
500
|
+
## Batch plan (updated)
|
|
501
|
+
|
|
502
|
+
### Batch 3 — next
|
|
503
|
+
| Item | Source | Feasibility |
|
|
504
|
+
|---|---|---|
|
|
505
|
+
| Model behaviour probe suite | nvidia/garak | H |
|
|
506
|
+
| Skill scanner rule classes + SARIF | nvidia/SkillSpector | H |
|
|
507
|
+
| Verified secret scanning | trufflesecurity/trufflehog | H |
|
|
508
|
+
| Multi-phase audit with independent verification | cloudflare/security-audit-skill | H |
|
|
509
|
+
| `mcp-inspect` deterministic MCP tests | modelcontextprotocol/inspector | H |
|
|
510
|
+
| Screenshot → vision → click | bytedance/UI-TARS-desktop | H |
|
|
511
|
+
| Conversation templates | prior backlog | H |
|
|
512
|
+
| Multi-model A/B testing across runs | prior backlog | H |
|
|
513
|
+
|
|
514
|
+
### Batch 4 — after
|
|
515
|
+
| Item | Source | Feasibility |
|
|
516
|
+
|---|---|---|
|
|
517
|
+
| Interactive architecture map page | haydenschmitty/floorplan | H |
|
|
518
|
+
| Guardrail routing API surface | sandbox-quantum/switch-trust | H |
|
|
519
|
+
| IoC feed import | cisco-talos/IOCs | H |
|
|
520
|
+
| Synthetic security log corpus | cisco-talos/EvidenceForge | H |
|
|
521
|
+
| Teams + Mattermost channels | sandbox-quantum/switch | M |
|
|
522
|
+
| External agent CLI adapters | openai/codex-plugin-cc | M |
|
|
523
|
+
| Official MCP registry alignment | modelcontextprotocol/registry | M |
|
|
524
|
+
| Codex skills catalog import | openai/skills | M |
|
|
525
|
+
| Attachment malware scan (`clamscan`) | cisco-talos/clamav | M |
|
|
526
|
+
| Project-wide symbol rename (LSP) | sandbox-quantum/bartleby | M |
|
|
527
|
+
| Binary function similarity | cisco-talos/binary_function_similarity | M |
|
|
528
|
+
| RAGFlow-style private retrieval | bytedance/deer-flow | M |
|
|
529
|
+
| Codex-style MCP config presets | openai/codex | H |
|
|
530
|
+
| Plugin marketplace maturity | prior backlog | M |
|
|
531
|
+
| Mobile PWA polish | prior backlog | H |
|
|
532
|
+
|
|
533
|
+
### Batch 5 — polish / ecosystem
|
|
534
|
+
| Item | Source | Feasibility |
|
|
535
|
+
|---|---|---|
|
|
536
|
+
| Community plugin ecosystem | prior backlog | ecosystem |
|
|
537
|
+
| Docs & tutorials | prior backlog | H |
|
|
538
|
+
| Performance optimization (large context) | prior backlog | H |
|
|
539
|
+
| Accessibility (ARIA, screen readers) | prior backlog | H |
|
|
540
|
+
| i18n | prior backlog | H |
|
|
541
|
+
|
|
460
542
|
## Non-goals
|
|
461
543
|
- Cloud-hosted backends as a requirement (local-first always).
|
|
462
544
|
- Telemetry or phone-home.
|
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.
|
|
3
|
+
A feature-rich, local-only AI agent harness. CLI-first, offline-first. v0.78.0.
|
|
4
4
|
|
|
5
5
|
## Capabilities
|
|
6
6
|
- Multi-backend LLM adapter (Ollama + OpenAI-compatible + 18 providers)
|
package/package.json
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
[Setup]
|
|
5
5
|
AppId={{8F3D1B2A-6C4E-4B9A-9D21-AE615A010001}}
|
|
6
6
|
AppName=AegisAi Harness
|
|
7
|
-
AppVersion=0.
|
|
7
|
+
AppVersion=0.78.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.
|
|
13
|
+
OutputBaseFilename=AegisAi-Harness-0.78.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
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
const filtered = sessions.filter((s) =>
|
|
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"
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
<
|
|
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-
|
|
745
|
-
${compareResult.
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
//
|
|
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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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') {
|
|
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
|
-
|
|
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
|
@@ -201,6 +201,33 @@ async function main() {
|
|
|
201
201
|
res.end(JSON.stringify(obj));
|
|
202
202
|
}
|
|
203
203
|
|
|
204
|
+
// Scope required by a route. Read-only GETs need `read`; anything that
|
|
205
|
+
// executes the agent or mutates state needs `execute`.
|
|
206
|
+
function requiredScope(method, urlPath) {
|
|
207
|
+
if (method !== 'GET') return 'execute';
|
|
208
|
+
const readOnly = ['/api/version', '/api/config', '/api/models', '/api/models/scan', '/api/models/hf-search',
|
|
209
|
+
'/api/context', '/api/sessions', '/api/sessions/search', '/api/search-sessions', '/api/files', '/api/file',
|
|
210
|
+
'/api/projects', '/api/skills', '/api/memories', '/api/errors', '/api/integrations', '/api/dag-runs',
|
|
211
|
+
'/api/stream', '/api/events'];
|
|
212
|
+
return readOnly.includes(urlPath) ? 'read' : 'read';
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Filesystem roots the file browser/editor may touch.
|
|
216
|
+
function allowedRoots() {
|
|
217
|
+
const configured = (process.env.AEGISAI_PROJECT_ROOT_ALLOWLIST || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
218
|
+
if (configured.length) return configured.map((r) => path.resolve(r));
|
|
219
|
+
return [path.resolve(process.cwd())];
|
|
220
|
+
}
|
|
221
|
+
function assertAllowedPath(target) {
|
|
222
|
+
const resolved = path.resolve(String(target || ''));
|
|
223
|
+
const roots = allowedRoots();
|
|
224
|
+
for (const root of roots) {
|
|
225
|
+
const rel = path.relative(root, resolved);
|
|
226
|
+
if (!rel.startsWith('..') && !path.isAbsolute(rel)) return resolved;
|
|
227
|
+
}
|
|
228
|
+
throw Object.assign(new Error('path outside allowed roots'), { status: 403 });
|
|
229
|
+
}
|
|
230
|
+
|
|
204
231
|
const handleRequest = async (req, res) => {
|
|
205
232
|
// CORS: never wildcard. Reflect only same-host origins; reject cross-site.
|
|
206
233
|
const origin = req.headers.origin;
|
|
@@ -215,19 +242,29 @@ async function main() {
|
|
|
215
242
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
216
243
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
217
244
|
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
|
|
218
|
-
// auth
|
|
245
|
+
// ---- auth ----
|
|
246
|
+
// Static assets stay public so a fresh browser can load the UI shell and
|
|
247
|
+
// prompt for a token. Only /api/* and /mcp are gated.
|
|
248
|
+
const urlPathOnly = req.url.split('?')[0];
|
|
249
|
+
const needsAuth = urlPathOnly.startsWith('/api/') || urlPathOnly === '/mcp';
|
|
219
250
|
const expectedToken = currentToken();
|
|
220
|
-
if (expectedToken) {
|
|
251
|
+
if (expectedToken && needsAuth) {
|
|
221
252
|
const supplied = (req.headers['authorization'] || '').replace(/^Bearer\s+/i, '') || new URL(req.url, 'http://x').searchParams.get('token') || '';
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
253
|
+
let authorized = tokenMatches(supplied, expectedToken);
|
|
254
|
+
let patScopes = null;
|
|
255
|
+
if (!authorized) {
|
|
256
|
+
// A personal access token may stand in, but only within its scopes.
|
|
225
257
|
try {
|
|
226
258
|
const pats = require('./access_tokens');
|
|
227
259
|
const v = pats.verify ? pats.verify(supplied) : null;
|
|
228
|
-
|
|
229
|
-
} catch (e) {
|
|
230
|
-
|
|
260
|
+
if (v && v.ok !== false) { authorized = true; patScopes = Array.isArray(v.scopes) ? v.scopes : []; }
|
|
261
|
+
} catch (e) { authorized = false; }
|
|
262
|
+
}
|
|
263
|
+
if (!authorized) { sendJson(res, 401, { error: 'unauthorized' }); return; }
|
|
264
|
+
if (patScopes) {
|
|
265
|
+
const required = requiredScope(req.method, urlPathOnly);
|
|
266
|
+
const allowed = patScopes.includes('*') || patScopes.includes(required) || (required === 'read' && patScopes.includes('execute'));
|
|
267
|
+
if (!allowed) { sendJson(res, 403, { error: 'insufficient_scope', required, granted: patScopes }); return; }
|
|
231
268
|
}
|
|
232
269
|
}
|
|
233
270
|
// rate limit — API only; static assets must not consume the API budget
|
|
@@ -352,7 +389,26 @@ async function main() {
|
|
|
352
389
|
const parsed = await readJson(req);
|
|
353
390
|
const models = parsed.models || [process.env.AEGISAI_MODEL || 'llama3.2:3b'];
|
|
354
391
|
const result = await require('./model_compare').compare(parsed.prompt || '', models, { projectRoot: process.cwd() });
|
|
355
|
-
|
|
392
|
+
const analysis = require('./model_compare').analyze(result);
|
|
393
|
+
sendJson(res, 200, { comparison: result, formatted: require('./model_compare').formatComparison(result), analysis });
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
if (req.method === 'POST' && req.url.split('?')[0] === '/api/diff') {
|
|
397
|
+
const parsed = await readJson(req);
|
|
398
|
+
const d = require('./text_diff');
|
|
399
|
+
sendJson(res, 200, { diff: d.diffWords(parsed.a || '', parsed.b || ''), similarity: +d.similarity(parsed.a || '', parsed.b || '').toFixed(3) });
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
if (req.method === 'POST' && req.url.split('?')[0] === '/api/file') {
|
|
403
|
+
const parsed = await readJson(req);
|
|
404
|
+
if (!parsed.path) { sendJson(res, 400, { error: 'path required' }); return; }
|
|
405
|
+
let resolved;
|
|
406
|
+
try { resolved = assertAllowedPath(parsed.path); }
|
|
407
|
+
catch (e) { sendJson(res, e.status || 403, { error: String(e.message || e) }); return; }
|
|
408
|
+
try {
|
|
409
|
+
require('fs').writeFileSync(resolved, String(parsed.content == null ? '' : parsed.content), 'utf8');
|
|
410
|
+
sendJson(res, 200, { ok: true, path: resolved, bytes: Buffer.byteLength(String(parsed.content || '')) });
|
|
411
|
+
} catch (e) { sendJson(res, 500, { error: String(e.message || e) }); }
|
|
356
412
|
return;
|
|
357
413
|
}
|
|
358
414
|
if (req.method === 'GET' && req.url.split('?')[0] === '/api/models/hf-search') {
|
|
@@ -420,19 +476,35 @@ async function main() {
|
|
|
420
476
|
if (req.method === 'GET' && req.url.split('?')[0] === '/api/search-sessions') {
|
|
421
477
|
const q = (new URL(req.url, 'http://x').searchParams.get('q') || '').toLowerCase();
|
|
422
478
|
const results = [];
|
|
423
|
-
|
|
424
|
-
|
|
479
|
+
const seen = new Set();
|
|
480
|
+
const scan = (sid, msgs) => {
|
|
481
|
+
for (const m of msgs || []) {
|
|
425
482
|
if ((m.content || '').toLowerCase().includes(q)) {
|
|
426
|
-
results.push({ sessionId: sid, role: m.role, snippet: (m.content || '').slice(0,
|
|
427
|
-
|
|
483
|
+
results.push({ sessionId: sid, role: m.role, snippet: (m.content || '').slice(0, 140), match: true });
|
|
484
|
+
return;
|
|
428
485
|
}
|
|
429
486
|
}
|
|
487
|
+
};
|
|
488
|
+
// Persisted sessions first so search survives restarts.
|
|
489
|
+
try {
|
|
490
|
+
const d = dbSafe();
|
|
491
|
+
for (const s of (d ? d.listSessions() : [])) {
|
|
492
|
+
if (seen.has(s.id)) continue;
|
|
493
|
+
seen.add(s.id);
|
|
494
|
+
scan(s.id, s.messages);
|
|
495
|
+
}
|
|
496
|
+
} catch (e) {}
|
|
497
|
+
for (const [sid, msgs] of sessions.entries()) {
|
|
498
|
+
if (seen.has(sid)) continue;
|
|
499
|
+
scan(sid, msgs);
|
|
430
500
|
}
|
|
431
501
|
sendJson(res, 200, { results, query: q });
|
|
432
502
|
return;
|
|
433
503
|
}
|
|
434
504
|
if (req.method === 'GET' && req.url.split('?')[0] === '/api/files') {
|
|
435
|
-
|
|
505
|
+
let dir;
|
|
506
|
+
try { dir = assertAllowedPath(new URL(req.url, 'http://x').searchParams.get('dir') || process.cwd()); }
|
|
507
|
+
catch (e) { sendJson(res, e.status || 403, { error: String(e.message || e) }); return; }
|
|
436
508
|
let entries = [];
|
|
437
509
|
try {
|
|
438
510
|
const fs = require('fs');
|
|
@@ -449,8 +521,11 @@ async function main() {
|
|
|
449
521
|
return;
|
|
450
522
|
}
|
|
451
523
|
if (req.method === 'GET' && req.url.split('?')[0] === '/api/file') {
|
|
452
|
-
const
|
|
453
|
-
if (!
|
|
524
|
+
const requested = new URL(req.url, 'http://x').searchParams.get('path');
|
|
525
|
+
if (!requested) { sendJson(res, 400, { error: 'path required' }); return; }
|
|
526
|
+
let filePath;
|
|
527
|
+
try { filePath = assertAllowedPath(requested); }
|
|
528
|
+
catch (e) { sendJson(res, e.status || 403, { error: String(e.message || e) }); return; }
|
|
454
529
|
try {
|
|
455
530
|
const fs = require('fs');
|
|
456
531
|
const content = fs.readFileSync(filePath, 'utf8');
|
|
@@ -492,7 +567,7 @@ async function main() {
|
|
|
492
567
|
try {
|
|
493
568
|
const d = dbSafe();
|
|
494
569
|
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 });
|
|
570
|
+
byId.set(s.id, { id: s.id, title: s.title || s.id, messages: (s.messages || []).length, updated: s.updated || null, tags: s.tags || [] });
|
|
496
571
|
}
|
|
497
572
|
} catch (e) {}
|
|
498
573
|
// Merge live in-memory sessions (fresher).
|
|
@@ -503,12 +578,22 @@ async function main() {
|
|
|
503
578
|
title: firstUser ? String(firstUser.content || '').slice(0, 60) : id,
|
|
504
579
|
messages: (msgs || []).length,
|
|
505
580
|
updated: sessionUpdated.get(id) || (byId.get(id) || {}).updated || null,
|
|
581
|
+
tags: (byId.get(id) || {}).tags || [],
|
|
506
582
|
});
|
|
507
583
|
}
|
|
508
584
|
const list = Array.from(byId.values()).sort((a, b) => String(b.updated || '').localeCompare(String(a.updated || '')));
|
|
509
585
|
sendJson(res, 200, { sessions: list });
|
|
510
586
|
return;
|
|
511
587
|
}
|
|
588
|
+
if (req.method === 'POST' && req.url.split('?')[0] === '/api/sessions/tags') {
|
|
589
|
+
const parsed = await readJson(req);
|
|
590
|
+
const sid = warnMissing(parsed.id);
|
|
591
|
+
const tags = Array.isArray(parsed.tags) ? parsed.tags.map((t) => String(t).trim()).filter(Boolean) : [];
|
|
592
|
+
const d = dbSafe();
|
|
593
|
+
const r = d ? d.setSessionTags(sid, tags) : { ok: false, error: 'db unavailable' };
|
|
594
|
+
sendJson(res, r.ok ? 200 : 500, r);
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
512
597
|
if (req.method === 'GET' && req.url.split('?')[0] === '/api/events') {
|
|
513
598
|
require('./event_stream').subscribe(res, req);
|
|
514
599
|
return;
|
package/src/mcp_server.js
CHANGED
|
@@ -99,19 +99,47 @@ async function dispatch(msg) {
|
|
|
99
99
|
function createHandler() {
|
|
100
100
|
return async (req, res) => {
|
|
101
101
|
if (req.method === 'POST') {
|
|
102
|
+
const MAX = parseInt(process.env.AEGISAI_MCP_MAX_BODY || String(2 * 1024 * 1024), 10);
|
|
102
103
|
let body = '';
|
|
103
|
-
|
|
104
|
+
let bytes = 0;
|
|
105
|
+
let done = false;
|
|
106
|
+
req.on('data', (c) => {
|
|
107
|
+
if (done) return;
|
|
108
|
+
bytes += c.length;
|
|
109
|
+
if (bytes > MAX) {
|
|
110
|
+
done = true;
|
|
111
|
+
res.writeHead(413, { 'Content-Type': 'application/json' });
|
|
112
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32600, message: 'request body too large' } }));
|
|
113
|
+
req.resume();
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
body += c;
|
|
117
|
+
});
|
|
118
|
+
req.on('error', () => {
|
|
119
|
+
if (done) return;
|
|
120
|
+
done = true;
|
|
121
|
+
try { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32600, message: 'request stream error' } })); } catch (e) {}
|
|
122
|
+
});
|
|
104
123
|
req.on('end', async () => {
|
|
124
|
+
if (done) return;
|
|
125
|
+
done = true;
|
|
105
126
|
let msg;
|
|
106
127
|
try { msg = JSON.parse(body); } catch (e) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32700, message: 'parse error' } })); return; }
|
|
107
|
-
|
|
128
|
+
// Dispatch error boundary: a throwing tool must not kill the transport.
|
|
129
|
+
let result;
|
|
130
|
+
try {
|
|
131
|
+
result = await dispatch(msg);
|
|
132
|
+
} catch (e) {
|
|
133
|
+
const id = msg && msg.id !== undefined ? msg.id : null;
|
|
134
|
+
try { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', id, error: { code: -32603, message: String((e && e.message) || e) } })); } catch (_) {}
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
108
137
|
if (result === null) { res.writeHead(202, { 'Content-Type': 'application/json' }); res.end(); return; }
|
|
109
138
|
const headers = { 'Content-Type': 'application/json' };
|
|
110
139
|
if (result._sessionId) { headers['Mcp-Session-Id'] = result._sessionId; delete result._sessionId; }
|
|
111
140
|
const sid = req.headers['mcp-session-id'];
|
|
112
141
|
if (sid && sessions.has(sid)) headers['Mcp-Session-Id'] = sid;
|
|
113
|
-
res.writeHead(200, headers);
|
|
114
|
-
res.end(JSON.stringify(result));
|
|
142
|
+
try { res.writeHead(200, headers); res.end(JSON.stringify(result)); } catch (e) {}
|
|
115
143
|
});
|
|
116
144
|
return;
|
|
117
145
|
}
|
package/src/model_compare.js
CHANGED
|
@@ -68,4 +68,21 @@ function formatComparison(comparison) {
|
|
|
68
68
|
return lines.join('\n');
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 };
|
package/src/text_diff.js
ADDED
|
@@ -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
|
@@ -73,23 +73,10 @@ class Tui extends EventEmitter {
|
|
|
73
73
|
return;
|
|
74
74
|
}
|
|
75
75
|
if (s.startsWith('\x1b[') || s.startsWith('\x1bO')) return; // ignore escape sequences
|
|
76
|
-
//
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if (parts[i]) this.input += parts[i].replace(/[^\x20-\x7e\t]/g, '');
|
|
81
|
-
if (i < parts.length - 1) {
|
|
82
|
-
const cmd = this.input.trim();
|
|
83
|
-
this.input = '';
|
|
84
|
-
this.emit('command', cmd);
|
|
85
|
-
if (cmd) this.addMessage('user', cmd);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
this.render();
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
// Accept the whole printable run (paste support), dropping control chars.
|
|
92
|
-
const printable = s.replace(/[^\x20-\x7e\t]/g, '');
|
|
76
|
+
// A pasted block (multi-char, may contain newlines) is inserted verbatim so the
|
|
77
|
+
// user can review/edit it; only a bare Enter submits. Newlines become spaces
|
|
78
|
+
// because the input is single-line.
|
|
79
|
+
const printable = s.replace(/[\r\n]+/g, ' ').replace(/[^\x20-\x7e\t]/g, '');
|
|
93
80
|
if (printable) {
|
|
94
81
|
this.input += printable;
|
|
95
82
|
this.render();
|
package/src/version.js
CHANGED