aegisai-harness 0.74.0 → 0.75.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -1
- package/README.md +1 -1
- package/llms.txt +1 -1
- package/package.json +1 -1
- package/packaging/windows/installer.iss +2 -2
- package/public/app.js +78 -15
- package/public/sw.js +18 -29
- package/src/a2a.js +1 -1
- package/src/acp.js +1 -1
- package/src/event_stream.js +8 -2
- package/src/index.js +111 -55
- package/src/model_discovery.js +5 -7
- package/src/projects.js +47 -9
- package/src/tui.js +22 -3
- 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.75.0] - 2026-11-24
|
|
6
6
|
|
|
7
7
|
### Fixed
|
|
8
8
|
- Installation: Windows installer now preflights Node.js 22.13+ with actionable messages; launcher no longer hides npm failures, uses `--omit=dev`, and records a dependency marker. Inno uninstall removes stale `node_modules`/lockfiles; `install.ps1` preserves `data/` and handles GitHub source zips.
|
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ A **feature-rich, local-only AI agent harness** — OpenCode-class runtime, but
|
|
|
10
10
|
offline-first: no cloud dependencies, no telemetry. 66 milestones, ~200 modules,
|
|
11
11
|
257 tests, CI green.
|
|
12
12
|
|
|
13
|
-
> Status: v0.
|
|
13
|
+
> Status: v0.75.0 (see [ROADMAP.md](./ROADMAP.md)).
|
|
14
14
|
> **Successor to [aegisai-next](https://github.com/user6811992/aegisai-next)** — that project is deprecated; all features have been ported here.
|
|
15
15
|
> **Live docs:** https://user6811992.github.io/aegisai-harness/
|
|
16
16
|
|
package/llms.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# AegisAi Harness — agent-readable catalog
|
|
2
2
|
|
|
3
|
-
A feature-rich, local-only AI agent harness. CLI-first, offline-first. v0.
|
|
3
|
+
A feature-rich, local-only AI agent harness. CLI-first, offline-first. v0.75.0.
|
|
4
4
|
|
|
5
5
|
## Capabilities
|
|
6
6
|
- Multi-backend LLM adapter (Ollama + OpenAI-compatible + 18 providers)
|
package/package.json
CHANGED
|
@@ -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.75.0
|
|
8
8
|
AppPublisher=AegisAi
|
|
9
9
|
AppPublisherURL=https://github.com/user6811992/aegisai-harness
|
|
10
10
|
DefaultDirName={autopf}\AegisAiHarness
|
|
11
11
|
DefaultGroupName=AegisAi Harness
|
|
12
12
|
OutputDir=..\..\dist
|
|
13
|
-
OutputBaseFilename=AegisAi-Harness-0.
|
|
13
|
+
OutputBaseFilename=AegisAi-Harness-0.75.0-Setup
|
|
14
14
|
Compression=lzma2
|
|
15
15
|
SolidCompression=yes
|
|
16
16
|
PrivilegesRequired=lowest
|
package/public/app.js
CHANGED
|
@@ -4,7 +4,37 @@ import { useState, useEffect, useRef, useCallback } from '/vendor/hooks.mjs';
|
|
|
4
4
|
import htm from '/vendor/htm.mjs';
|
|
5
5
|
const html = htm.bind(h);
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
// Auth token support: stored in sessionStorage, sent as Bearer on every API call.
|
|
8
|
+
function authToken() { try { return sessionStorage.getItem('aegisai_token') || localStorage.getItem('aegisai_token') || ''; } catch (e) { return ''; } }
|
|
9
|
+
function setAuthToken(t) { try { if (t) sessionStorage.setItem('aegisai_token', t); else sessionStorage.removeItem('aegisai_token'); } catch (e) {} }
|
|
10
|
+
function authHeaders(extra) {
|
|
11
|
+
const h = Object.assign({}, extra || {});
|
|
12
|
+
const t = authToken();
|
|
13
|
+
if (t) h.Authorization = 'Bearer ' + t;
|
|
14
|
+
return h;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Central API helper: throws on non-2xx so callers cannot report false success.
|
|
18
|
+
async function API(p, opts) {
|
|
19
|
+
const o = Object.assign({}, opts || {});
|
|
20
|
+
o.headers = authHeaders(o.headers);
|
|
21
|
+
const r = await fetch(p, o);
|
|
22
|
+
let body = null;
|
|
23
|
+
try { body = await r.json(); } catch (e) { body = null; }
|
|
24
|
+
if (!r.ok) {
|
|
25
|
+
if (r.status === 401) window.dispatchEvent(new CustomEvent('aegisai-unauthorized'));
|
|
26
|
+
const msg = (body && body.error) || ('HTTP ' + r.status);
|
|
27
|
+
throw Object.assign(new Error(msg), { status: r.status, body });
|
|
28
|
+
}
|
|
29
|
+
return body;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Fetch wrapper for streaming + non-JSON callers.
|
|
33
|
+
function apiFetch(p, opts) {
|
|
34
|
+
const o = Object.assign({}, opts || {});
|
|
35
|
+
o.headers = authHeaders(o.headers);
|
|
36
|
+
return fetch(p, o);
|
|
37
|
+
}
|
|
8
38
|
|
|
9
39
|
let toastFn = null;
|
|
10
40
|
function toast(msg, type = 'info') { if (toastFn) toastFn(msg, type); }
|
|
@@ -68,7 +98,9 @@ function OnboardingWizard({ onComplete }) {
|
|
|
68
98
|
const body = { BACKEND_TYPE: backend };
|
|
69
99
|
if (model) body.AEGISAI_MODEL = model;
|
|
70
100
|
if (token) body.AEGISAI_TOKEN = token;
|
|
71
|
-
await
|
|
101
|
+
await apiFetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
102
|
+
// Keep the UI authenticated after enabling a token.
|
|
103
|
+
if (token) setAuthToken(token.trim());
|
|
72
104
|
} catch (e) {
|
|
73
105
|
console.error('config save failed:', e);
|
|
74
106
|
}
|
|
@@ -149,11 +181,17 @@ function ConfigModal({ cfg, setCfg, onClose }) {
|
|
|
149
181
|
useEffect(() => { API('/api/config').then(setLocal); }, []);
|
|
150
182
|
async function save() {
|
|
151
183
|
setSaving(true);
|
|
152
|
-
|
|
153
|
-
|
|
184
|
+
try {
|
|
185
|
+
await apiFetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(local) }).then(async (r) => {
|
|
186
|
+
if (!r.ok) { let e = 'HTTP ' + r.status; try { const b = await r.json(); if (b && b.error) e = b.error; } catch (_) {} throw new Error(e); }
|
|
187
|
+
});
|
|
188
|
+
setCfg(local);
|
|
189
|
+
toast('Configuration saved', 'success');
|
|
190
|
+
onClose();
|
|
191
|
+
} catch (e) {
|
|
192
|
+
toast('Save failed: ' + e.message, 'error');
|
|
193
|
+
}
|
|
154
194
|
setSaving(false);
|
|
155
|
-
toast('Configuration saved', 'success');
|
|
156
|
-
onClose();
|
|
157
195
|
}
|
|
158
196
|
const keys = ['BACKEND_TYPE', 'BACKEND_URL', 'AEGISAI_MODEL', 'REA_BIN', 'GHIDRA_MCP_URL', 'CRAFT_BIN', 'sttUrl', 'ttsUrl'];
|
|
159
197
|
const [tab, setTab] = useState('config');
|
|
@@ -196,7 +234,7 @@ function ConfigModal({ cfg, setCfg, onClose }) {
|
|
|
196
234
|
async function pullModel(name) {
|
|
197
235
|
toast('Pulling ' + name + '...', 'info');
|
|
198
236
|
try {
|
|
199
|
-
const r = await
|
|
237
|
+
const r = await apiFetch('/api/models/pull', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: name }) });
|
|
200
238
|
const d = await r.json();
|
|
201
239
|
if (d.ok) toast('Pulled ' + name + ' successfully', 'success');
|
|
202
240
|
else toast('Pull failed: ' + (d.error || 'unknown'), 'error');
|
|
@@ -345,6 +383,8 @@ function App() {
|
|
|
345
383
|
const [toasts, setToasts] = useState([]);
|
|
346
384
|
const [toolLog, setToolLog] = useState([]);
|
|
347
385
|
const [dragOver, setDragOver] = useState(false);
|
|
386
|
+
const [needAuth, setNeedAuth] = useState(false);
|
|
387
|
+
const [tokenInput, setTokenInput] = useState('');
|
|
348
388
|
const inputRef = useRef(null);
|
|
349
389
|
const chatRef = useRef(null);
|
|
350
390
|
|
|
@@ -362,10 +402,16 @@ function App() {
|
|
|
362
402
|
}, [theme]);
|
|
363
403
|
|
|
364
404
|
useEffect(() => { updateCtx(); }, []);
|
|
405
|
+
useEffect(() => {
|
|
406
|
+
// Server rejected our request: prompt for a token instead of failing silently.
|
|
407
|
+
const onUnauth = () => setNeedAuth(true);
|
|
408
|
+
window.addEventListener('aegisai-unauthorized', onUnauth);
|
|
409
|
+
return () => window.removeEventListener('aegisai-unauthorized', onUnauth);
|
|
410
|
+
}, []);
|
|
365
411
|
useEffect(() => {
|
|
366
412
|
API('/api/version').then((v) => {
|
|
367
|
-
if (v
|
|
368
|
-
}).catch(() => {});
|
|
413
|
+
if (v && v.updateAvailable) toast('Update available: v' + (v.latest || '') + ' (current ' + (v.current || '') + ')', 'info');
|
|
414
|
+
}).catch((e) => { if (e && e.status === 401) setNeedAuth(true); });
|
|
369
415
|
}, []);
|
|
370
416
|
|
|
371
417
|
useEffect(() => {
|
|
@@ -433,7 +479,7 @@ function App() {
|
|
|
433
479
|
// Add empty assistant message for streaming
|
|
434
480
|
setMessages((m) => [...m, { role: 'assistant', content: '' }]);
|
|
435
481
|
try {
|
|
436
|
-
const r = await
|
|
482
|
+
const r = await apiFetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: text, stream: true }) });
|
|
437
483
|
if (!r.ok) throw new Error('HTTP ' + r.status);
|
|
438
484
|
const reader = r.body.getReader();
|
|
439
485
|
const decoder = new TextDecoder();
|
|
@@ -510,7 +556,7 @@ function App() {
|
|
|
510
556
|
|
|
511
557
|
async function exportChat(format) {
|
|
512
558
|
try {
|
|
513
|
-
const r = await
|
|
559
|
+
const r = await apiFetch('/api/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ format, title: 'Chat Export' }) });
|
|
514
560
|
const d = await r.json();
|
|
515
561
|
if (d.ok) toast('Exported to ' + d.path, 'success');
|
|
516
562
|
else toast('Export failed: ' + (d.error || 'unknown'), 'error');
|
|
@@ -546,7 +592,7 @@ function App() {
|
|
|
546
592
|
setComparing(true);
|
|
547
593
|
try {
|
|
548
594
|
const models = compareModels.split(',').map((m) => m.trim()).filter(Boolean);
|
|
549
|
-
const r = await
|
|
595
|
+
const r = await apiFetch('/api/compare', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: comparePrompt, models }) });
|
|
550
596
|
const d = await r.json();
|
|
551
597
|
setCompareResult(d);
|
|
552
598
|
toast('Comparison complete', 'success');
|
|
@@ -564,8 +610,19 @@ function App() {
|
|
|
564
610
|
<${CommandPalette} open=${showPalette} onClose=${() => setShowPalette(false)} commands=${commands} />
|
|
565
611
|
${showConfig ? html`<${ConfigModal} cfg=${cfg} setCfg=${setCfg} onClose=${() => setShowConfig(false)} />` : null}
|
|
566
612
|
${showHelp ? html`<${HelpPanel} onClose=${() => setShowHelp(false)} />` : null}
|
|
567
|
-
${
|
|
568
|
-
<div class="modal-backdrop"
|
|
613
|
+
${needAuth ? html`
|
|
614
|
+
<div class="modal-backdrop">
|
|
615
|
+
<div class="modal" onClick=${(e) => e.stopPropagation()}>
|
|
616
|
+
<h2>Authentication Required</h2>
|
|
617
|
+
<p>The server requires an access token. Enter it below (stored in this browser session only).</p>
|
|
618
|
+
<input type="password" value=${tokenInput} onInput=${(e) => setTokenInput(e.target.value)} placeholder="Access token" style="width:100%" />
|
|
619
|
+
<div class="modal-actions">
|
|
620
|
+
<button class="btn-primary" onClick=${() => { setAuthToken(tokenInput.trim()); setNeedAuth(false); setTokenInput(''); toast('Token set', 'success'); updateCtx(); }}>Use Token</button>
|
|
621
|
+
</div>
|
|
622
|
+
</div>
|
|
623
|
+
</div>
|
|
624
|
+
` : null}
|
|
625
|
+
${showShortcuts ? html` <div class="modal-backdrop" onClick=${() => setShowShortcuts(false)}>
|
|
569
626
|
<div class="modal" onClick=${(e) => e.stopPropagation()}>
|
|
570
627
|
<h2>Keyboard Shortcuts</h2>
|
|
571
628
|
<div class="shortcuts-list">
|
|
@@ -668,7 +725,13 @@ function App() {
|
|
|
668
725
|
</div>
|
|
669
726
|
</div>
|
|
670
727
|
` : null}
|
|
671
|
-
<${SessionSidebar} open=${showSessions} onClose=${() => setShowSessions(false)} onSelect=${(s) => {
|
|
728
|
+
<${SessionSidebar} open=${showSessions} onClose=${() => setShowSessions(false)} onSelect=${async (s) => {
|
|
729
|
+
try {
|
|
730
|
+
const d = await API('/api/sessions?id=' + encodeURIComponent(s.id));
|
|
731
|
+
setMessages((d.messages || []).map((m) => ({ role: m.role, content: m.content })));
|
|
732
|
+
toast('Loaded session: ' + (s.title || s.id), 'success');
|
|
733
|
+
} catch (e) { toast('Load failed: ' + e.message, 'error'); }
|
|
734
|
+
}} />
|
|
672
735
|
<header class="topbar">
|
|
673
736
|
<h1>AegisAi Harness</h1>
|
|
674
737
|
<span class="ctx-meter">ctx ${ctx.tokens}/${ctx.limit}${ctx.compacted ? ' · compacted' : ''}</span>
|
package/public/sw.js
CHANGED
|
@@ -1,44 +1,33 @@
|
|
|
1
|
-
// Offline cache for the local web UI. Bump CACHE when bundled assets change.
|
|
2
1
|
const CACHE = 'aegisai-harness-v2';
|
|
3
|
-
const
|
|
4
|
-
'/', '/index.html', '/style.css', '/app.js', '/markdown.js', '/manifest.json',
|
|
5
|
-
'/vendor/preact.mjs', '/vendor/hooks.mjs', '/vendor/htm.mjs', '/vendor/tailwind.js'
|
|
6
|
-
];
|
|
2
|
+
const PRECACHE = ['/', '/style.css', '/app.js', '/manifest.json', '/vendor/preact.mjs', '/vendor/hooks.mjs', '/vendor/htm.mjs', '/vendor/tailwind.js'];
|
|
7
3
|
|
|
8
|
-
self.addEventListener('install', (
|
|
9
|
-
|
|
4
|
+
self.addEventListener('install', (e) => {
|
|
5
|
+
self.skipWaiting();
|
|
6
|
+
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(PRECACHE)).catch(() => {}));
|
|
10
7
|
});
|
|
11
8
|
|
|
12
|
-
self.addEventListener('activate', (
|
|
13
|
-
|
|
14
|
-
caches.keys()
|
|
15
|
-
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
|
9
|
+
self.addEventListener('activate', (e) => {
|
|
10
|
+
e.waitUntil(
|
|
11
|
+
caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
|
16
12
|
.then(() => self.clients.claim())
|
|
17
13
|
);
|
|
18
14
|
});
|
|
19
15
|
|
|
20
|
-
self.addEventListener('fetch', (
|
|
21
|
-
const req =
|
|
16
|
+
self.addEventListener('fetch', (e) => {
|
|
17
|
+
const req = e.request;
|
|
22
18
|
if (req.method !== 'GET') return;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
caches.open(CACHE).then((c) => c.put('/index.html', copy));
|
|
30
|
-
return res;
|
|
31
|
-
}).catch(() => caches.match('/index.html')));
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
event.respondWith(
|
|
19
|
+
let url;
|
|
20
|
+
try { url = new URL(req.url); } catch (err) { return; }
|
|
21
|
+
if (url.origin !== self.location.origin) return;
|
|
22
|
+
// Never intercept API / protocol calls: always network, never cached.
|
|
23
|
+
if (url.pathname.startsWith('/api/') || url.pathname === '/mcp' || url.pathname.startsWith('/mcp/')) return;
|
|
24
|
+
e.respondWith(
|
|
36
25
|
caches.match(req).then((hit) => hit || fetch(req).then((res) => {
|
|
37
|
-
if (res.ok) {
|
|
26
|
+
if (res && res.ok && res.type === 'basic') {
|
|
38
27
|
const copy = res.clone();
|
|
39
|
-
caches.open(CACHE).then((c) => c.put(req, copy));
|
|
28
|
+
caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {});
|
|
40
29
|
}
|
|
41
30
|
return res;
|
|
42
|
-
}))
|
|
31
|
+
}).catch(() => hit))
|
|
43
32
|
);
|
|
44
33
|
});
|
package/src/a2a.js
CHANGED
|
@@ -8,7 +8,7 @@ function agentCard() {
|
|
|
8
8
|
return {
|
|
9
9
|
name: 'aegisai-harness',
|
|
10
10
|
description: 'Local-only AI agent harness',
|
|
11
|
-
version: '
|
|
11
|
+
version: require('./version').VERSION,
|
|
12
12
|
capabilities: { streaming: false, pushNotifications: false, stateTransitionHistory: true },
|
|
13
13
|
defaultInputModes: ['text'],
|
|
14
14
|
defaultOutputModes: ['text'],
|
package/src/acp.js
CHANGED
|
@@ -6,7 +6,7 @@ function createServer(opts) {
|
|
|
6
6
|
opts = opts || {};
|
|
7
7
|
const sessions = new Map();
|
|
8
8
|
const methods = {
|
|
9
|
-
initialize: async (params) => ({ protocolVersion: 1, capabilities: { prompt: true, cancel: true }, agentInfo: { name: 'aegisai-harness', version: '
|
|
9
|
+
initialize: async (params) => ({ protocolVersion: 1, capabilities: { prompt: true, cancel: true }, agentInfo: { name: 'aegisai-harness', version: require('./version').VERSION } }),
|
|
10
10
|
'session/new': async (params) => {
|
|
11
11
|
const id = 'acp_' + Date.now();
|
|
12
12
|
sessions.set(id, { cwd: (params && params.cwd) || process.cwd(), messages: [] });
|
package/src/event_stream.js
CHANGED
|
@@ -4,11 +4,17 @@ const { bus } = require('./event_bus');
|
|
|
4
4
|
|
|
5
5
|
const clients = new Set();
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
// Subscribe an SSE response. Pass the request so disconnects are cleaned up
|
|
8
|
+
// automatically (otherwise every closed tab leaks a listener + socket).
|
|
9
|
+
function subscribe(res, req) {
|
|
8
10
|
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
|
|
9
11
|
res.write(': connected\n\n');
|
|
10
12
|
clients.add(res);
|
|
11
|
-
|
|
13
|
+
const cleanup = () => { clients.delete(res); try { res.end(); } catch (e) {} };
|
|
14
|
+
res.on('close', cleanup);
|
|
15
|
+
res.on('error', cleanup);
|
|
16
|
+
if (req) { req.on('close', cleanup); req.on('aborted', cleanup); }
|
|
17
|
+
return cleanup;
|
|
12
18
|
}
|
|
13
19
|
function broadcast(event, data) {
|
|
14
20
|
const payload = 'event: ' + event + '\ndata: ' + JSON.stringify(data || {}) + '\n\n';
|
package/src/index.js
CHANGED
|
@@ -156,13 +156,25 @@ async function main() {
|
|
|
156
156
|
const rateWindow = parseInt(process.env.AEGISAI_RATE_WINDOW || '60', 10) * 1000;
|
|
157
157
|
const rateHits = new Map();
|
|
158
158
|
const sessions = new Map(); // session id -> messages array
|
|
159
|
+
const sessionToolLogs = new Map(); // session id -> last tool log (for /api/context)
|
|
160
|
+
const sessionUpdated = new Map(); // session id -> ISO timestamp
|
|
161
|
+
const warnMissing = (v) => String(v || 'default');
|
|
159
162
|
const pendingActions = new Map();
|
|
160
163
|
|
|
161
164
|
function readJson(req) {
|
|
165
|
+
const MAX_BODY = parseInt(process.env.AEGISAI_MAX_BODY_BYTES || '1048576', 10); // 1 MiB default
|
|
162
166
|
return new Promise((resolve, reject) => {
|
|
163
167
|
let body = '';
|
|
164
|
-
|
|
165
|
-
|
|
168
|
+
let bytes = 0;
|
|
169
|
+
let aborted = false;
|
|
170
|
+
req.on('data', (c) => {
|
|
171
|
+
if (aborted) return;
|
|
172
|
+
bytes += c.length;
|
|
173
|
+
if (bytes > MAX_BODY) { aborted = true; reject(Object.assign(new Error('request body too large'), { status: 413 })); req.resume(); return; }
|
|
174
|
+
body += c;
|
|
175
|
+
});
|
|
176
|
+
req.on('error', (e) => { if (!aborted) { aborted = true; reject(e); } });
|
|
177
|
+
req.on('end', () => { if (aborted) return; try { resolve(JSON.parse(body || '{}')); } catch (e) { reject(Object.assign(e, { status: 400 })); } });
|
|
166
178
|
});
|
|
167
179
|
}
|
|
168
180
|
function sendJson(res, status, obj) {
|
|
@@ -170,7 +182,7 @@ async function main() {
|
|
|
170
182
|
res.end(JSON.stringify(obj));
|
|
171
183
|
}
|
|
172
184
|
|
|
173
|
-
const
|
|
185
|
+
const handleRequest = async (req, res) => {
|
|
174
186
|
// CORS headers (needed for browser fetch with application/json content type)
|
|
175
187
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
176
188
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
@@ -180,10 +192,19 @@ async function main() {
|
|
|
180
192
|
const expectedToken = currentToken();
|
|
181
193
|
if (expectedToken) {
|
|
182
194
|
const supplied = (req.headers['authorization'] || '').replace(/^Bearer\s+/i, '') || new URL(req.url, 'http://x').searchParams.get('token') || '';
|
|
183
|
-
if (!tokenMatches(supplied, expectedToken)) {
|
|
195
|
+
if (!tokenMatches(supplied, expectedToken)) {
|
|
196
|
+
// A valid personal access token (PAT) may stand in for the global token.
|
|
197
|
+
let patOk = false;
|
|
198
|
+
try {
|
|
199
|
+
const pats = require('./access_tokens');
|
|
200
|
+
const v = pats.verify ? pats.verify(supplied) : null;
|
|
201
|
+
patOk = Boolean(v && (v.ok !== false));
|
|
202
|
+
} catch (e) { patOk = false; }
|
|
203
|
+
if (!patOk) { sendJson(res, 401, { error: 'unauthorized' }); return; }
|
|
204
|
+
}
|
|
184
205
|
}
|
|
185
|
-
// rate limit
|
|
186
|
-
if (rateLimit > 0) {
|
|
206
|
+
// rate limit — API only; static assets must not consume the API budget
|
|
207
|
+
if (rateLimit > 0 && req.url.split('?')[0].startsWith('/api/')) {
|
|
187
208
|
const ip = req.socket.remoteAddress || 'unknown';
|
|
188
209
|
const now = Date.now();
|
|
189
210
|
const arr = (rateHits.get(ip) || []).filter((t) => now - t < rateWindow);
|
|
@@ -206,10 +227,10 @@ async function main() {
|
|
|
206
227
|
messages: history.concat([{ role: 'user', content: parsed.message || '' }]),
|
|
207
228
|
projectRoot: process.cwd(),
|
|
208
229
|
onEvent: (e) => {
|
|
209
|
-
if (e.type === 'token') { fullReply += (e.content || ''); res.write('data: ' + JSON.stringify({ type: 'token', content: e.content || '' }) + '
|
|
210
|
-
else if (e.type === 'tool_call') { res.write('data: ' + JSON.stringify({ type: 'tool_call', name: e.name, args: e.args }) + '
|
|
211
|
-
else if (e.type === 'tool_result') { res.write('data: ' + JSON.stringify({ type: 'tool_result', preview: (e.preview || '').slice(0, 200) }) + '
|
|
212
|
-
else if (e.type === 'status') { res.write('data: ' + JSON.stringify({ type: 'status', message: e.message }) + '
|
|
230
|
+
if (e.type === 'token') { fullReply += (e.content || ''); res.write('data: ' + JSON.stringify({ type: 'token', content: e.content || '' }) + '\n\n'); }
|
|
231
|
+
else if (e.type === 'tool_call') { res.write('data: ' + JSON.stringify({ type: 'tool_call', name: e.name, args: e.args }) + '\n\n'); }
|
|
232
|
+
else if (e.type === 'tool_result') { res.write('data: ' + JSON.stringify({ type: 'tool_result', preview: (e.preview || '').slice(0, 200) }) + '\n\n'); }
|
|
233
|
+
else if (e.type === 'status') { res.write('data: ' + JSON.stringify({ type: 'status', message: e.message }) + '\n\n'); }
|
|
213
234
|
},
|
|
214
235
|
autoApprove,
|
|
215
236
|
approvalHandler: async () => false,
|
|
@@ -217,7 +238,9 @@ async function main() {
|
|
|
217
238
|
const reply = (result.final && result.final.final) || fullReply;
|
|
218
239
|
const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
|
|
219
240
|
sessions.set(sid, updated);
|
|
220
|
-
|
|
241
|
+
sessionToolLogs.set(sid, result.toolLog || []);
|
|
242
|
+
sessionUpdated.set(sid, new Date().toISOString());
|
|
243
|
+
res.write('data: ' + JSON.stringify({ type: 'done', reply, toolLog: result.toolLog || [] }) + '\n\n');
|
|
221
244
|
res.end();
|
|
222
245
|
return;
|
|
223
246
|
}
|
|
@@ -233,6 +256,8 @@ async function main() {
|
|
|
233
256
|
const reply = (result.final && result.final.final) || '';
|
|
234
257
|
const updated = history.concat([{ role: 'user', content: parsed.message || '' }, { role: 'assistant', content: reply }]);
|
|
235
258
|
sessions.set(sid, updated);
|
|
259
|
+
sessionToolLogs.set(sid, result.toolLog || []);
|
|
260
|
+
sessionUpdated.set(sid, new Date().toISOString());
|
|
236
261
|
sendJson(res, 200, { reply, toolLog: result.toolLog || [], pendingActions: pendingActions.get(sid) || [] });
|
|
237
262
|
return;
|
|
238
263
|
}
|
|
@@ -303,7 +328,7 @@ async function main() {
|
|
|
303
328
|
let results = [];
|
|
304
329
|
try {
|
|
305
330
|
// Search without filter first, then filter for gguf client-side
|
|
306
|
-
const r = await fetch('https://huggingface.co/api/models?search=' + encodeURIComponent(q) + '&sort=downloads&direction=-1&limit=30');
|
|
331
|
+
const r = await fetch('https://huggingface.co/api/models?search=' + encodeURIComponent(q) + '&sort=downloads&direction=-1&limit=30', { signal: AbortSignal.timeout(15000) });
|
|
307
332
|
if (r.ok) {
|
|
308
333
|
const data = await r.json();
|
|
309
334
|
const all = Array.isArray(data) ? data : [];
|
|
@@ -323,43 +348,6 @@ async function main() {
|
|
|
323
348
|
sendJson(res, 200, { results, query: q });
|
|
324
349
|
return;
|
|
325
350
|
}
|
|
326
|
-
if (req.method === 'GET' && req.url.split('?')[0] === '/api/models/scan') {
|
|
327
|
-
const roots = new URL(req.url, 'http://x').searchParams.get('roots');
|
|
328
|
-
const rootList = roots ? roots.split(',') : undefined;
|
|
329
|
-
const backend = require('./backends').getType();
|
|
330
|
-
const found = require('./model_discovery').scan(rootList, 500, backend);
|
|
331
|
-
// Also list models from the active backend
|
|
332
|
-
try {
|
|
333
|
-
const r = await require('./backends').backendListModels();
|
|
334
|
-
const backendModels = (r.models || []).map((m) => ({ path: backend + '://' + (m.name || m), name: m.name || m, sizeGB: m.size ? +(m.size / 1024 ** 3).toFixed(2) : 0, type: backend }));
|
|
335
|
-
// Only add if not already in found
|
|
336
|
-
const existingNames = new Set(found.map((f) => f.name));
|
|
337
|
-
for (const bm of backendModels) {
|
|
338
|
-
if (!existingNames.has(bm.name)) found.push(bm);
|
|
339
|
-
}
|
|
340
|
-
} catch (e) {}
|
|
341
|
-
sendJson(res, 200, { models: found, backend });
|
|
342
|
-
return;
|
|
343
|
-
}
|
|
344
|
-
if (req.method === 'GET' && req.url.split('?')[0] === '/api/models/hf-search') {
|
|
345
|
-
const q = new URL(req.url, 'http://x').searchParams.get('q') || '';
|
|
346
|
-
// Simple HuggingFace search via their API
|
|
347
|
-
let results = [];
|
|
348
|
-
try {
|
|
349
|
-
const r = await fetch('https://huggingface.co/api/models?search=' + encodeURIComponent(q) + '&filter=gguf&sort=downloads&direction=-1&limit=20');
|
|
350
|
-
if (r.ok) {
|
|
351
|
-
const data = await r.json();
|
|
352
|
-
results = (Array.isArray(data) ? data : []).map((m) => ({
|
|
353
|
-
id: m.id || m.modelId,
|
|
354
|
-
downloads: m.downloads || 0,
|
|
355
|
-
likes: m.likes || 0,
|
|
356
|
-
tags: m.tags || [],
|
|
357
|
-
}));
|
|
358
|
-
}
|
|
359
|
-
} catch (e) {}
|
|
360
|
-
sendJson(res, 200, { results });
|
|
361
|
-
return;
|
|
362
|
-
}
|
|
363
351
|
if (req.method === 'POST' && req.url.split('?')[0] === '/api/models/pull') {
|
|
364
352
|
const parsed = await readJson(req);
|
|
365
353
|
let ok = false;
|
|
@@ -378,7 +366,7 @@ async function main() {
|
|
|
378
366
|
sendJson(res, 200, { ok: true });
|
|
379
367
|
return;
|
|
380
368
|
}
|
|
381
|
-
} catch (e) { sendJson(res, 500, { error: String(e.message || e) }); return; }
|
|
369
|
+
} catch (e) { sendJson(res, (e && e.status) || 500, { error: String(e.message || e) }); return; }
|
|
382
370
|
|
|
383
371
|
if (req.method === 'GET' && req.url.split('?')[0] === '/api/stream') {
|
|
384
372
|
const u = new URL(req.url, 'http://x');
|
|
@@ -389,7 +377,8 @@ async function main() {
|
|
|
389
377
|
const tokenizer = require('./tokenizer');
|
|
390
378
|
const sid = new URL(req.url, 'http://x').searchParams.get('session') || 'default';
|
|
391
379
|
const tokens = tokenizer.countMessages(sessions.get(sid) || []);
|
|
392
|
-
|
|
380
|
+
const tl = sessionToolLogs.get(sid) || [];
|
|
381
|
+
sendJson(res, 200, { tokens, limit: 8192, ratio: +(tokens / 8192).toFixed(3), compacted: tl.some((t) => t.name === '__compact__') });
|
|
393
382
|
return;
|
|
394
383
|
}
|
|
395
384
|
if (req.url.split('?')[0] === '/mcp') {
|
|
@@ -457,8 +446,31 @@ async function main() {
|
|
|
457
446
|
sendJson(res, 200, { events: require('./event_bus').bus.events() });
|
|
458
447
|
return;
|
|
459
448
|
}
|
|
449
|
+
if (req.method === 'GET' && req.url.split('?')[0] === '/api/sessions') {
|
|
450
|
+
const u = new URL(req.url, 'http://x');
|
|
451
|
+
const wantId = u.searchParams.get('id');
|
|
452
|
+
if (wantId) {
|
|
453
|
+
const sid = warnMissing(wantId);
|
|
454
|
+
const msgs = sessions.get(sid) || [];
|
|
455
|
+
sendJson(res, 200, { id: sid, messages: msgs });
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
const list = [];
|
|
459
|
+
for (const [id, msgs] of sessions.entries()) {
|
|
460
|
+
const firstUser = (msgs || []).find((m) => m.role === 'user');
|
|
461
|
+
list.push({
|
|
462
|
+
id,
|
|
463
|
+
title: firstUser ? String(firstUser.content || '').slice(0, 60) : id,
|
|
464
|
+
messages: (msgs || []).length,
|
|
465
|
+
updated: sessionUpdated.get(id) || null,
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
list.sort((a, b) => String(b.updated || '').localeCompare(String(a.updated || '')));
|
|
469
|
+
sendJson(res, 200, { sessions: list });
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
460
472
|
if (req.method === 'GET' && req.url.split('?')[0] === '/api/events') {
|
|
461
|
-
require('./event_stream').subscribe(res);
|
|
473
|
+
require('./event_stream').subscribe(res, req);
|
|
462
474
|
return;
|
|
463
475
|
}
|
|
464
476
|
try {
|
|
@@ -509,6 +521,8 @@ async function main() {
|
|
|
509
521
|
if (req.method === 'GET' && req.url.split('?')[0] === '/api/version') {
|
|
510
522
|
const v = require('./updater');
|
|
511
523
|
let info = v.checkLocal();
|
|
524
|
+
if (!info || typeof info !== 'object') info = {};
|
|
525
|
+
info.version = require('./version').VERSION;
|
|
512
526
|
try { info.node = process.version; } catch (e) {}
|
|
513
527
|
sendJson(res, 200, info);
|
|
514
528
|
return;
|
|
@@ -565,10 +579,12 @@ async function main() {
|
|
|
565
579
|
const url = process.env.STT_URL;
|
|
566
580
|
if (!url) { sendJson(res, 400, { error: 'STT_URL not configured' }); return; }
|
|
567
581
|
try {
|
|
582
|
+
const MAX_AUDIO = parseInt(process.env.AEGISAI_MAX_AUDIO_BYTES || '26214400', 10); // 25 MiB
|
|
568
583
|
const chunks = [];
|
|
569
|
-
|
|
584
|
+
let total = 0;
|
|
585
|
+
for await (const c of req) { total += c.length; if (total > MAX_AUDIO) { sendJson(res, 413, { error: 'audio too large' }); return; } chunks.push(c); }
|
|
570
586
|
const body = Buffer.concat(chunks);
|
|
571
|
-
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': req.headers['content-type'] || 'audio/webm' }, body });
|
|
587
|
+
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': req.headers['content-type'] || 'audio/webm' }, body, signal: AbortSignal.timeout(60000) });
|
|
572
588
|
const data = await r.json();
|
|
573
589
|
sendJson(res, 200, { text: data.text || '' });
|
|
574
590
|
} catch (e) { sendJson(res, 500, { error: String(e.message || e) }); }
|
|
@@ -595,7 +611,17 @@ async function main() {
|
|
|
595
611
|
res.writeHead(200, { 'Content-Type': ct });
|
|
596
612
|
res.end(fs.readFileSync(filePath));
|
|
597
613
|
} else { res.writeHead(404); res.end(); }
|
|
614
|
+
};
|
|
615
|
+
const server = http.createServer((req, res) => {
|
|
616
|
+
handleRequest(req, res).catch((e) => {
|
|
617
|
+
try {
|
|
618
|
+
if (!res.headersSent) sendJson(res, (e && e.status) || 500, { error: String((e && e.message) || e) });
|
|
619
|
+
else res.end();
|
|
620
|
+
} catch (_) { try { res.end(); } catch (__) {} }
|
|
621
|
+
});
|
|
598
622
|
});
|
|
623
|
+
// Never let a stray rejection kill the web server.
|
|
624
|
+
process.on('unhandledRejection', (e) => { try { console.error('[unhandledRejection]', (e && e.stack) || e); } catch (_) {} });
|
|
599
625
|
server.listen(port, host, () => console.log('Web UI at http://' + host + ':' + port));
|
|
600
626
|
return;
|
|
601
627
|
}
|
|
@@ -692,10 +718,36 @@ async function main() {
|
|
|
692
718
|
};
|
|
693
719
|
rl.prompt();
|
|
694
720
|
rl.on('line', async (line) => {
|
|
721
|
+
try {
|
|
695
722
|
const t = line.trim();
|
|
696
723
|
if (!t) { rl.prompt(); return; }
|
|
697
724
|
if (t === '/exit' || t === '/quit') { rl.close(); return; }
|
|
698
|
-
if (t === '/help') {
|
|
725
|
+
if (t === '/help') {
|
|
726
|
+
const groups = [
|
|
727
|
+
['Session', ['/exit', '/model <name>', '/root <path>', '/sandbox on|off', '/autoapprove on|off', '/offline on|off', '/agent <name>', '/plan <goal>']],
|
|
728
|
+
['Index & replay', ['/index', '/replay <sessionId>', '/traces', '/search-sessions <q>', '/session-export <id>|<format>']],
|
|
729
|
+
['Health & data', ['/health', '/backup <file>', '/restore <file>', '/vault set|get|list|delete ...', '/metrics', '/score', '/reliability']],
|
|
730
|
+
['Eval & bench', ['/eval add|run|list', '/pass-at-k', '/bench <models...>', '/failure-clusters', '/lint', '/stress']],
|
|
731
|
+
['Models', ['/providers', '/provider-list', '/model-scan', '/models', '/cheapest <prompt>', '/cost-route', '/routing-eval']],
|
|
732
|
+
['Memory', ['/remember <text>', '/recall <q>', '/reflect', '/sremember', '/srecall', '/tremember', '/tasof', '/memory-graph', '/habits', '/geo-wake', '/mem-reindex']],
|
|
733
|
+
['Memory (graph)', ['/graph-observe', '/graph-recall', '/graph-prompt', '/mem-md-search', '/memory-hierarchy']],
|
|
734
|
+
['Governance', ['/charter', '/governance', '/constitution', '/constitution-propose', '/constitution-decide', '/policy', '/auto-rules', '/ahp-check', '/security-layers', '/identity-list']],
|
|
735
|
+
['Audit & evidence', ['/ledger-verify', '/ledger-replay', '/ledger-rewind', '/merkle-root', '/evidence-bundle', '/contract-save', '/contract-check', '/contracts', '/honesty', '/waste', '/diagnose', '/evolve']],
|
|
736
|
+
['Orchestration', ['/dag <json|file>', '/dag-runs', '/critique <text>', '/board', '/board-add', '/task-create', '/task-update', '/tasks', '/team-create', '/team-run', '/teams', '/swarm <plan>', '/schedule', '/sched-tick']],
|
|
737
|
+
['Tools', ['/tools', '/tool-contract', '/tool-eval', '/tool-state', '/equipment', '/equipment-add', '/semantic-tools <q>', '/mcp-pins', '/mcp-registry', '/mcp-market']],
|
|
738
|
+
['Security & RE', ['/vuln-scan <path>', '/security-kb', '/sarif <path>', '/pentest <target>', '/rea-status', '/ghidra-status', '/craft-status', '/re-search <q>', '/re-categories', '/re-online <q>']],
|
|
739
|
+
['Browser & web', ['/browser-targets', '/browser-nav <url>', '/browser-snapshot', '/browser-eval <js>', '/extract <url>', '/search <q>', '/multi-search <q>', '/fetch <url>', '/squeeze <url>|<q>']],
|
|
740
|
+
['Workspace', ['/git-status', '/git-diff', '/git-branch', '/git-log', '/git-stash', '/git-show', '/diff-review', '/review-start', '/project-create', '/projects', '/project-add-doc', '/ctxfs', '/files']],
|
|
741
|
+
['Misc', ['/time', '/export <format>|<title>', '/compare <prompt>|<model1>|<model2>', '/ui-record', '/ui-replay', '/plugins-ui', '/dag-ui', '/trajectory-ui', '/backup', '/help']],
|
|
742
|
+
];
|
|
743
|
+
console.log('\nAegisAi Harness — command reference\n');
|
|
744
|
+
for (const [g, cmds] of groups) {
|
|
745
|
+
console.log(g + ':');
|
|
746
|
+
console.log(' ' + cmds.join(', '));
|
|
747
|
+
}
|
|
748
|
+
console.log('\nType /<command> to run. Many commands accept "|" separated arguments.');
|
|
749
|
+
rl.prompt(); return;
|
|
750
|
+
}
|
|
699
751
|
if (t.startsWith('/model ')) { model = t.slice(7).trim(); console.log('model =', model); rl.prompt(); return; }
|
|
700
752
|
if (t.startsWith('/root ')) { root = t.slice(6).trim(); console.log('root =', root); rl.prompt(); return; }
|
|
701
753
|
if (t.startsWith('/sandbox ')) { sandbox = t.slice(9).trim() === 'on'; console.log('sandbox =', sandbox); rl.prompt(); return; }
|
|
@@ -1083,6 +1135,10 @@ async function main() {
|
|
|
1083
1135
|
}
|
|
1084
1136
|
try { await runOne(t); } catch (e) { console.error('error:', e.message || e); }
|
|
1085
1137
|
rl.prompt();
|
|
1138
|
+
} catch (err) {
|
|
1139
|
+
console.error('[command error]', (err && err.message) || err);
|
|
1140
|
+
try { rl.prompt(); } catch (_) {}
|
|
1141
|
+
}
|
|
1086
1142
|
});
|
|
1087
1143
|
rl.on('close', () => { db.close(); process.exit(0); });
|
|
1088
1144
|
return;
|
package/src/model_discovery.js
CHANGED
|
@@ -80,7 +80,11 @@ function scan(roots, maxFiles, backend) {
|
|
|
80
80
|
} else if (extensions.test(e.name)) {
|
|
81
81
|
let size = 0;
|
|
82
82
|
try { size = fs.statSync(p).size; } catch (err) {}
|
|
83
|
-
|
|
83
|
+
const ext = path.extname(e.name).slice(1).toLowerCase();
|
|
84
|
+
// `.bin` is used by many non-model artefacts; require a model-sized file.
|
|
85
|
+
const MIN_BIN_BYTES = 50 * 1024 * 1024;
|
|
86
|
+
if (ext === 'bin' && size < MIN_BIN_BYTES) continue;
|
|
87
|
+
found.push({ path: p, name: e.name, sizeGB: +(size / 1024 ** 3).toFixed(2), type: ext });
|
|
84
88
|
count += 1;
|
|
85
89
|
}
|
|
86
90
|
}
|
|
@@ -120,9 +124,3 @@ function huggingFacePull(repo, filename) {
|
|
|
120
124
|
}
|
|
121
125
|
|
|
122
126
|
module.exports = { ROOTS: [], getDefaultRoots, scan, huggingFacePull };
|
|
123
|
-
function huggingFacePull(repo, filename) {
|
|
124
|
-
const url = 'https://huggingface.co/' + repo + '/resolve/main/' + (filename || '');
|
|
125
|
-
return { ok: true, url, note: 'streaming download not implemented; open URL or use huggingface-cli' };
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// (duplicate removed)
|
package/src/projects.js
CHANGED
|
@@ -5,27 +5,65 @@ const path = require('path');
|
|
|
5
5
|
const { DATA_DIR } = require('./core/config');
|
|
6
6
|
|
|
7
7
|
function dir() { return path.join(DATA_DIR, 'projects'); }
|
|
8
|
+
|
|
9
|
+
// Reject traversal/absolute paths for project names.
|
|
10
|
+
function safeName(name) {
|
|
11
|
+
if (typeof name !== 'string') throw Object.assign(new Error('project name must be a string'), { status: 400 });
|
|
12
|
+
const n = name.trim();
|
|
13
|
+
if (!n) throw Object.assign(new Error('project name is required'), { status: 400 });
|
|
14
|
+
if (n.includes('..') || n.includes('/') || n.includes('\\') || n.includes('\0') || path.isAbsolute(n)) {
|
|
15
|
+
throw Object.assign(new Error('invalid project name (no path separators or "..")'), { status: 400 });
|
|
16
|
+
}
|
|
17
|
+
return n;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Reject anything that isn't a plain filename for documents.
|
|
21
|
+
function safeFilename(filename) {
|
|
22
|
+
if (typeof filename !== 'string') throw Object.assign(new Error('filename must be a string'), { status: 400 });
|
|
23
|
+
const f = path.basename(filename.trim());
|
|
24
|
+
if (!f || f === '.' || f === '..' || f.includes('\0')) {
|
|
25
|
+
throw Object.assign(new Error('invalid filename'), { status: 400 });
|
|
26
|
+
}
|
|
27
|
+
return f;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Ensure the resolved target stays inside the projects base.
|
|
31
|
+
function resolveInside(base, target) {
|
|
32
|
+
const resolvedBase = path.resolve(base);
|
|
33
|
+
const resolved = path.resolve(resolvedBase, target);
|
|
34
|
+
const rel = path.relative(resolvedBase, resolved);
|
|
35
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
36
|
+
throw Object.assign(new Error('path escapes projects directory'), { status: 400 });
|
|
37
|
+
}
|
|
38
|
+
return resolved;
|
|
39
|
+
}
|
|
40
|
+
|
|
8
41
|
function create(name, instructions) {
|
|
9
|
-
const
|
|
42
|
+
const n = safeName(name);
|
|
43
|
+
const p = resolveInside(dir(), n);
|
|
10
44
|
fs.mkdirSync(p, { recursive: true });
|
|
11
45
|
fs.mkdirSync(path.join(p, 'docs'), { recursive: true });
|
|
12
|
-
fs.writeFileSync(path.join(p, 'instructions.md'), instructions || '# ' +
|
|
13
|
-
return { name, path: p };
|
|
46
|
+
fs.writeFileSync(path.join(p, 'instructions.md'), instructions || '# ' + n + '\n');
|
|
47
|
+
return { name: n, path: p };
|
|
14
48
|
}
|
|
15
49
|
function get(name) {
|
|
16
|
-
const
|
|
50
|
+
const n = safeName(name);
|
|
51
|
+
const p = resolveInside(dir(), n);
|
|
17
52
|
if (!fs.existsSync(p)) return null;
|
|
18
53
|
let instructions = '';
|
|
19
54
|
try { instructions = fs.readFileSync(path.join(p, 'instructions.md'), 'utf8'); } catch (e) {}
|
|
20
55
|
let shelf = [];
|
|
21
56
|
try { shelf = fs.readdirSync(path.join(p, 'docs')).filter((f) => f.endsWith('.md') || f.endsWith('.txt')); } catch (e) {}
|
|
22
|
-
return { name, path: p, instructions, shelf };
|
|
57
|
+
return { name: n, path: p, instructions, shelf };
|
|
23
58
|
}
|
|
24
59
|
function addDoc(name, filename, content) {
|
|
25
|
-
const
|
|
60
|
+
const n = safeName(name);
|
|
61
|
+
const f = safeFilename(filename);
|
|
62
|
+
const base = resolveInside(dir(), n);
|
|
63
|
+
const p = resolveInside(path.join(base, 'docs'), f);
|
|
26
64
|
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
27
65
|
fs.writeFileSync(p, content || '');
|
|
28
|
-
return { name, file:
|
|
66
|
+
return { name: n, file: f };
|
|
29
67
|
}
|
|
30
68
|
function list() {
|
|
31
69
|
try { return fs.readdirSync(dir()).filter((d) => fs.statSync(path.join(dir(), d)).isDirectory()); } catch (e) { return []; }
|
|
@@ -36,7 +74,7 @@ function systemText(name) {
|
|
|
36
74
|
const docs = p.shelf.map((f) => {
|
|
37
75
|
try { return '### ' + f + '\n' + fs.readFileSync(path.join(p.path, 'docs', f), 'utf8').slice(0, 4000); } catch (e) { return ''; }
|
|
38
76
|
}).filter(Boolean);
|
|
39
|
-
return 'Project: ' + name + '\n\n' + p.instructions + (docs.length ? '\n\n## Document shelf\n\n' + docs.join('\n\n---\n\n') : '');
|
|
77
|
+
return 'Project: ' + p.name + '\n\n' + p.instructions + (docs.length ? '\n\n## Document shelf\n\n' + docs.join('\n\n---\n\n') : '');
|
|
40
78
|
}
|
|
41
79
|
|
|
42
|
-
module.exports = { create, get, addDoc, list, systemText };
|
|
80
|
+
module.exports = { create, get, addDoc, list, systemText, safeName, safeFilename };
|
package/src/tui.js
CHANGED
|
@@ -45,7 +45,9 @@ class Tui extends EventEmitter {
|
|
|
45
45
|
}
|
|
46
46
|
handleKey(d) {
|
|
47
47
|
const s = d.toString();
|
|
48
|
+
if (!s) return;
|
|
48
49
|
if (s === '\u0003') { this.stop(); return; } // Ctrl+C
|
|
50
|
+
// Split pasted/multi-byte chunks into lines and printable runs.
|
|
49
51
|
if (s === '\r' || s === '\n') {
|
|
50
52
|
const cmd = this.input.trim();
|
|
51
53
|
this.input = '';
|
|
@@ -59,9 +61,26 @@ class Tui extends EventEmitter {
|
|
|
59
61
|
this.render();
|
|
60
62
|
return;
|
|
61
63
|
}
|
|
62
|
-
if (s.startsWith('\x1b[')) return; // ignore
|
|
63
|
-
|
|
64
|
-
|
|
64
|
+
if (s.startsWith('\x1b[') || s.startsWith('\x1bO')) return; // ignore escape sequences
|
|
65
|
+
// Handle pasted text containing newlines: submit each complete line.
|
|
66
|
+
if (s.includes('\n') || s.includes('\r')) {
|
|
67
|
+
const parts = s.split(/\r\n|\r|\n/);
|
|
68
|
+
for (let i = 0; i < parts.length; i++) {
|
|
69
|
+
if (parts[i]) this.input += parts[i].replace(/[^\x20-\x7e\t]/g, '');
|
|
70
|
+
if (i < parts.length - 1) {
|
|
71
|
+
const cmd = this.input.trim();
|
|
72
|
+
this.input = '';
|
|
73
|
+
this.emit('command', cmd);
|
|
74
|
+
if (cmd) this.addMessage('user', cmd);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
this.render();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
// Accept the whole printable run (paste support), dropping control chars.
|
|
81
|
+
const printable = s.replace(/[^\x20-\x7e\t]/g, '');
|
|
82
|
+
if (printable) {
|
|
83
|
+
this.input += printable;
|
|
65
84
|
this.render();
|
|
66
85
|
}
|
|
67
86
|
}
|
package/src/version.js
CHANGED