lampson 0.5.5 → 0.5.7
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/bin/lampson.js +1 -1
- package/chat.syn +7 -2
- package/cli.syn +3 -0
- package/hub.tpl.syn +3 -0
- package/lib/agents.syn +30 -13
- package/lib/approvals.syn +4 -1
- package/lib/loop.syn +103 -56
- package/lib/mailbox.syn +29 -2
- package/lib/prompt.syn +3 -3
- package/lib/runtime.syn +19 -0
- package/lib/settings.syn +23 -0
- package/lib/webchat.syn +373 -0
- package/package.json +3 -2
- package/public/css/chat.css +28 -0
- package/public/css/layout.css +3 -1
- package/public/index.html +3 -0
- package/public/js/app.js +2 -1
- package/public/js/chat.js +148 -25
- package/public/js/core.js +32 -13
- package/public/js/editor.js +11 -1
- package/public/js/markdown.js +72 -0
- package/public/js/sessions.js +31 -10
- package/public/js/tree.js +2 -1
- package/public/vendor/README.md +8 -0
- package/public/vendor/dompurify.LICENSE +202 -0
- package/public/vendor/marked.LICENSE +44 -0
- package/public/vendor/marked.umd.js +92 -0
- package/public/vendor/purify.min.js +7 -0
- package/run.syn +5 -0
- package/synsema.json +3 -0
- package/web.syn +104 -63
package/public/js/chat.js
CHANGED
|
@@ -38,28 +38,143 @@ function imagesHtml(ims) { if (!ims || !ims.length) return ''; return '<div clas
|
|
|
38
38
|
log.addEventListener('click', e => { const im = e.target.closest('.user .th img'); if (im) window.open(im.src, '_blank'); });
|
|
39
39
|
|
|
40
40
|
// ---- envío (SSE) ----
|
|
41
|
-
let
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
41
|
+
let activeRun = null;
|
|
42
|
+
const inputRows = new Map();
|
|
43
|
+
let inputSequence = 0;
|
|
44
|
+
function setBusy(b) {
|
|
45
|
+
busy = b; $('#f').classList.toggle('busy', b); $('#send').disabled = sessionLoading;
|
|
46
|
+
$('#agent').disabled = b; $('#perm').disabled = b; $('#new').disabled = false;
|
|
47
|
+
$('#send').title = b ? 'enviar una corrección (Enter)' : 'enviar (Enter)';
|
|
48
|
+
}
|
|
49
|
+
function inputState(row, text, failed = false) {
|
|
50
|
+
let state = row.querySelector('.input-state');
|
|
51
|
+
if (!state) { state = document.createElement('small'); row.appendChild(state); }
|
|
52
|
+
state.className = 'input-state' + (failed ? ' failed' : ''); state.textContent = text;
|
|
53
|
+
return state;
|
|
54
|
+
}
|
|
55
|
+
async function steer(message, images, row, run) {
|
|
56
|
+
const id = 'input-' + Date.now().toString(36) + '-' + (++inputSequence) + '-' + Math.random().toString(36).slice(2, 10);
|
|
57
|
+
inputRows.set(id, { row, run }); inputState(row, 'pendiente · se suma al trabajo en curso');
|
|
58
|
+
// Mantener el orden de escritura incluso si el usuario envía varias correcciones muy rápido.
|
|
59
|
+
const post = async () => {
|
|
60
|
+
try {
|
|
61
|
+
const sid = await run.ready;
|
|
62
|
+
const res = await fetch(BASE + '/api/chat/input', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ session: sid, message, images, id }) });
|
|
63
|
+
if (res.status === 409) {
|
|
64
|
+
inputRows.delete(id); await run.finished;
|
|
65
|
+
if (run.detached) throw new Error('la conversación cambió antes de enviar el mensaje');
|
|
66
|
+
return send(message, images, row);
|
|
67
|
+
}
|
|
68
|
+
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
69
|
+
} catch (e) {
|
|
70
|
+
inputRows.delete(id);
|
|
71
|
+
const state = inputState(row, 'no se pudo enviar · ' + e.message + ' ', true);
|
|
72
|
+
const retry = document.createElement('button'); retry.type = 'button'; retry.textContent = 'reintentar';
|
|
73
|
+
retry.onclick = () => { retry.disabled = true; send(message, images, row); }; state.appendChild(retry);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
run.submissions = run.submissions.then(post, post);
|
|
77
|
+
return run.submissions;
|
|
78
|
+
}
|
|
79
|
+
$('#stop').onclick = async () => {
|
|
80
|
+
const run = activeRun; if (!run || run.stopping) return;
|
|
81
|
+
run.stopping = true; $('#stop').disabled = true;
|
|
82
|
+
try {
|
|
83
|
+
const sid = await run.ready;
|
|
84
|
+
await run.submissions;
|
|
85
|
+
const res = await fetch(BASE + '/api/chat/stop', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ session: sid }) });
|
|
86
|
+
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
87
|
+
run.thinking.querySelector('span:last-child').textContent = 'deteniendo al terminar la operación actual…';
|
|
88
|
+
} catch (e) { add('meta', 'no se pudo detener: ' + esc(e.message)); run.stopping = false; $('#stop').disabled = false; }
|
|
89
|
+
};
|
|
90
|
+
function createRun() {
|
|
91
|
+
let resolveSid, rejectSid, finish;
|
|
92
|
+
const run = { ready: new Promise((ok, no) => { resolveSid = ok; rejectSid = no; }), finished: new Promise(ok => { finish = ok; }), submissions: Promise.resolve(), session: null, runId: null, cursor: 0, done: false, detached: false, controller: null, rejectSid, finish };
|
|
93
|
+
run.resolveSid = sid => { run.session = sid; resolveSid(sid); };
|
|
94
|
+
run.ready.catch(() => {}); activeRun = run;
|
|
95
|
+
setBusy(true); $('#stop').disabled = false; pending = null;
|
|
96
|
+
run.thinking = add('working', '<span class="dot"></span><span>iniciando conversación…</span>');
|
|
97
|
+
return run;
|
|
98
|
+
}
|
|
99
|
+
function detachChat() {
|
|
100
|
+
const run = activeRun; if (!run) return;
|
|
101
|
+
run.detached = true; if (run.controller) run.controller.abort();
|
|
102
|
+
run.rejectSid(new Error('cambiaste de conversación')); run.finish(); run.thinking.remove();
|
|
103
|
+
for (const [id, item] of inputRows) if (item.run === run) inputRows.delete(id);
|
|
104
|
+
activeRun = null; pending = null; setBusy(false);
|
|
105
|
+
}
|
|
106
|
+
async function followRun(run, initialRequest) {
|
|
107
|
+
let retry = 0, request = initialRequest;
|
|
50
108
|
try {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
109
|
+
while (!run.done && !run.detached && activeRun === run) {
|
|
110
|
+
try {
|
|
111
|
+
run.controller = new AbortController();
|
|
112
|
+
if (request) {
|
|
113
|
+
const admitted = await fetch(BASE + '/api/chat/start', { ...request, signal: run.controller.signal }); request = null;
|
|
114
|
+
if (!admitted.ok) throw new Error('HTTP ' + admitted.status);
|
|
115
|
+
const started = await admitted.json(); if (run.detached) break;
|
|
116
|
+
run.resolveSid(started.session); run.runId = started.run;
|
|
117
|
+
selectSession(started.session, 'replace'); continue;
|
|
118
|
+
}
|
|
119
|
+
const res = await fetch(BASE + '/api/chat/events?session=' + encodeURIComponent(run.session) + '&run=' + encodeURIComponent(run.runId) + '&after=' + run.cursor, { signal: run.controller.signal });
|
|
120
|
+
if (!res.ok || !res.body) throw new Error('HTTP ' + res.status);
|
|
121
|
+
const reader = res.body.getReader(); const dec = new TextDecoder(); let buf = '';
|
|
122
|
+
while (!run.detached && activeRun === run) {
|
|
123
|
+
const { value, done } = await reader.read(); if (done) break;
|
|
124
|
+
buf += dec.decode(value, { stream: true });
|
|
125
|
+
let i; while ((i = buf.indexOf('\n\n')) >= 0) {
|
|
126
|
+
const chunk = buf.slice(0, i); buf = buf.slice(i + 2);
|
|
127
|
+
if (!run.detached && activeRun === run) handle(chunk, run.thinking);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (run.needsSnapshot) {
|
|
131
|
+
const sid = run.session; detachChat(); await openSession(sid, 'replace');
|
|
132
|
+
add('meta', 'La ejecución ya no está activa. Se recuperó la conversación guardada.'); return;
|
|
133
|
+
}
|
|
134
|
+
if (run.done || run.detached) break;
|
|
135
|
+
if (!run.runId || !run.session) throw new Error('la conexión terminó antes de confirmar la sesión');
|
|
136
|
+
} catch (e) {
|
|
137
|
+
if (run.detached) break;
|
|
138
|
+
if (!run.runId || !run.session) throw e;
|
|
139
|
+
if (e.message === 'HTTP 404') {
|
|
140
|
+
// El servidor pudo reiniciarse: volver al historial persistido, sin relanzar el agente.
|
|
141
|
+
const sid = run.session; detachChat(); await openSession(sid, 'replace');
|
|
142
|
+
add('meta', 'La ejecución ya no está activa. Se recuperó la conversación guardada.'); return;
|
|
143
|
+
}
|
|
59
144
|
}
|
|
145
|
+
if (!run.done && !run.detached) {
|
|
146
|
+
run.thinking.querySelector('span:last-child').textContent = 'reconectando con la conversación…';
|
|
147
|
+
await new Promise(ok => setTimeout(ok, Math.min(1000 * ++retry, 5000)));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} catch (e) { if (!run.detached) add('meta', '‼ ' + esc(e.message)); }
|
|
151
|
+
finally {
|
|
152
|
+
run.rejectSid(new Error('el turno terminó antes de abrir la sesión'));
|
|
153
|
+
run.thinking.remove(); run.finish();
|
|
154
|
+
if (activeRun === run) {
|
|
155
|
+
activeRun = null; setBusy(false); $('#stop').disabled = false;
|
|
156
|
+
loadSessions(); loadTree(); loadProcs(); loadMemory(); loadAgents();
|
|
60
157
|
}
|
|
61
|
-
}
|
|
62
|
-
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function attachChat(sid, runId, queued = []) {
|
|
161
|
+
const run = createRun(); run.resolveSid(sid); run.runId = runId;
|
|
162
|
+
run.thinking.querySelector('span:last-child').textContent = 'recuperando el trabajo en curso…';
|
|
163
|
+
for (const it of queued) {
|
|
164
|
+
const row = add('user', esc(it.text) + imagesHtml(it.images));
|
|
165
|
+
inputRows.set(it.id, { row, run }); inputState(row, 'pendiente · se suma al trabajo en curso');
|
|
166
|
+
}
|
|
167
|
+
return followRun(run, null);
|
|
168
|
+
}
|
|
169
|
+
async function send(message, suppliedImages, suppliedRow) {
|
|
170
|
+
const images = suppliedImages || attachments.map(a => ({ media_type: a.media_type, data: a.data, w: a.w, h: a.h }));
|
|
171
|
+
if (!suppliedImages) { attachments = []; paintAttach(); }
|
|
172
|
+
if (log.querySelector('.empty')) { log.innerHTML = ''; log.classList.remove('hero'); }
|
|
173
|
+
const row = suppliedRow || add('user', esc(message) + imagesHtml(images));
|
|
174
|
+
if (busy && activeRun) return steer(message, images, row, activeRun);
|
|
175
|
+
const oldState = row.querySelector('.input-state'); if (oldState) oldState.remove();
|
|
176
|
+
const run = createRun();
|
|
177
|
+
return followRun(run, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ session, message, agent: $('#agent').value || 'build', permission: $('#perm').value || 'ask', images }) });
|
|
63
178
|
}
|
|
64
179
|
let pending = null;
|
|
65
180
|
function resultHtml(out, bad) { return `<details><summary class="${bad ? 'bad' : ''}">${esc(out.split('\n')[0].slice(0, 140))} <span style="color:var(--ink-3)">(${out.length} chars)</span></summary><pre>${esc(out)}</pre></details>`; }
|
|
@@ -67,16 +182,24 @@ function handle(chunk, thinking) {
|
|
|
67
182
|
const data = chunk.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).join('\n'); if (!data) return;
|
|
68
183
|
let ev; try { ev = JSON.parse(data); } catch { return; }
|
|
69
184
|
const k = ev.kind, d = ev.data;
|
|
70
|
-
if (
|
|
185
|
+
if (activeRun && ev.run) {
|
|
186
|
+
if (activeRun.runId === ev.run && ev.seq <= activeRun.cursor) return;
|
|
187
|
+
activeRun.runId = ev.run; activeRun.cursor = ev.seq;
|
|
188
|
+
}
|
|
189
|
+
if (k === 'session') { if (activeRun) activeRun.resolveSid(d); const changed = d !== session; selectSession(d, 'replace'); thinking.querySelector('span:last-child').textContent = 'pensando…'; if (changed) loadTodo(); }
|
|
190
|
+
else if (k === 'run_missing') { if (activeRun) activeRun.needsSnapshot = true; }
|
|
191
|
+
else if (k === 'user_input') { if (!inputRows.has(d.id)) add('user', esc(d.text) + imagesHtml(d.images)); }
|
|
192
|
+
else if (k === 'input_applied') { const item = inputRows.get(d.id); if (item) { inputState(item.row, 'incorporado'); inputRows.delete(d.id); } }
|
|
193
|
+
else if (k === 'tool_skipped') { add('step', `<span class="ic">↷</span>${cmdHtml(describe(d.call))}<span class="denied"> no ejecutada</span>`); }
|
|
71
194
|
else if (k === 'assistant') add('assistant', md(d));
|
|
72
195
|
else if (k === 'tool_call') { thinking.querySelector('span:last-child').textContent = 'ejecutando ' + esc(d.name) + '…'; pending = add('step', `<span class="ic">⚙</span>${cmdHtml(describe(d))}`); wireMore(pending); if (d.name === 'process') setTimeout(loadProcs, 2500); if (d.name === 'delegate') { setTimeout(loadAgents, 800); setTimeout(loadAgents, 4000); } if (d.name === 'todo') setTimeout(loadTodo, 300); if (d.name === 'plugin') setTimeout(loadPlugins, 300); if (d.name === 'lsp') setTimeout(loadLsp, 1500); }
|
|
73
196
|
else if (k === 'inbox') { add('meta', '✉ ' + esc(String(d).split('\n')[0].slice(0, 160))); loadAgents(); }
|
|
74
|
-
else if (k === 'tool_result') { const out = String(d.output); const bad = /^(ERROR|DENIED)/.test(out);
|
|
197
|
+
else if (k === 'tool_result') { const out = String(d.output); const bad = /^(ERROR|DENIED)/.test(out); const skipped = /^NOT RUN:/.test(out);
|
|
75
198
|
if (!bad && d.call && /^(write|edit|bash|process|delegate|plugin|skill)$/.test(d.call.name)) { treeChanged(); edTouched(/^(write|edit)$/.test(d.call.name) ? (d.call.args || {}).path : ''); }
|
|
76
199
|
if (d.call && d.call.name === 'schedule') { setTimeout(loadSched, 300); if (/^scheduled '/.test(out)) setSec('sched', true); }
|
|
77
200
|
// plugin recién creado: avisar en el chat con un acceso directo al switch (el modelo no sabe cómo se enciende en esta UI)
|
|
78
201
|
if (d.call && d.call.name === 'plugin' && /^plugin '([^']+)' created/.test(out)) { const nm = out.match(/^plugin '([^']+)' created/)[1]; const m = add('meta', `☼ plugin <b>${esc(nm)}</b> creado — está apagado: <a href="#" class="plugingo">encenderlo en «plugins»</a>`); m.querySelector('.plugingo').onclick = (ev) => { ev.preventDefault(); openPlugins(nm); }; $('#plugins').classList.add('new'); setTimeout(() => $('#plugins').classList.remove('new'), 4000); }
|
|
79
|
-
const el = pending || add('step', '<span class="ic">→</span>'); pending = null; thinking.querySelector('span:last-child').textContent = 'pensando…'; const ic = el.querySelector('.ic'); if (ic) { ic.textContent = bad ? '✗' : '✓'; ic.className = 'ic ' + (bad ? 'bad' : 'ok'); } el.insertAdjacentHTML('beforeend', resultHtml(out, bad)); }
|
|
202
|
+
const el = pending || add('step', '<span class="ic">→</span>'); pending = null; thinking.querySelector('span:last-child').textContent = 'pensando…'; const ic = el.querySelector('.ic'); if (ic) { ic.textContent = skipped ? '↷' : (bad ? '✗' : '✓'); ic.className = 'ic ' + (bad ? 'bad' : 'ok'); } el.insertAdjacentHTML('beforeend', resultHtml(out, bad)); }
|
|
80
203
|
else if (k === 'approval_request') { const el = add('approval', `<div class="card"><div class="why">⚠ ${esc(d.why)}</div><code>${esc(describe({name: d.name, args: d.args}))}</code><div class="btns"><button class="primary" data-ok="1">Permitir</button><button data-ok="0">Denegar</button></div></div>`); el.querySelectorAll('button').forEach(b => b.onclick = async () => { el.querySelectorAll('button').forEach(x => x.disabled = true); await api(BASE + '/api/approve', { id: d.id, decision: b.dataset.ok === '1' }); }); el.dataset.id = d.id; }
|
|
81
204
|
else if (k === 'approval_result') { const el = [...log.querySelectorAll('.approval')].find(x => x.dataset.id === d.id); if (el) el.querySelector('.btns').innerHTML = d.approved ? '<span style="color:var(--str)">✓ permitido</span>' : (d.timeout ? '<span class="denied">✗ sin respuesta, denegado</span>' : '<span class="denied">✗ denegado</span>'); }
|
|
82
205
|
else if (k === 'mode') { $('#agent').value = d.agent; $('#perm').value = d.permission; if (d.has_key === false) { add('denied', `‼ no hay API key para ${esc(d.provider)} — cargala en la ventana de modelo (clic en «${esc(d.provider)} · ${esc(d.model)}» arriba)`); } }
|
|
@@ -84,9 +207,9 @@ function handle(chunk, thinking) {
|
|
|
84
207
|
// el hint de "modelo inválido" solo cuando el error realmente habla de eso
|
|
85
208
|
else if (k === 'error') { add('denied', '‼ ' + esc(d)); if (/(invalid|unknown|no such|not exist|not found|unsupported).{0,30}model|model.{0,30}(invalid|unknown|does not exist|not found|unsupported)/i.test(String(d))) add('meta', `el proveedor rechazó el nombre del modelo (${esc(cfg.model || '')}) — clic en «${esc(cfg.provider || '')} · ${esc(cfg.model || '')}» arriba: la lista de modelos válidos aparece al elegir el proveedor`); }
|
|
86
209
|
else if (k === 'compact') add('meta', '⧗ compactando contexto (~' + d.before + ' tokens)');
|
|
87
|
-
else if (k === 'done') { if (d.stopped !== 'user_command') add('meta', `${d.steps} paso${d.steps === 1 ? '' : 's'} · ${d.usage.input + d.usage.output} tokens · ${d.stopped}`); }
|
|
210
|
+
else if (k === 'done') { if (activeRun) activeRun.done = true; if (d.stopped !== 'user_command') add('meta', `${d.steps} paso${d.steps === 1 ? '' : 's'} · ${d.usage.input + d.usage.output} tokens · ${d.stopped}`); }
|
|
88
211
|
log.appendChild(thinking); $('#stage').scrollTop = $('#stage').scrollHeight;
|
|
89
212
|
}
|
|
90
|
-
$('#f').onsubmit = e => { e.preventDefault(); const t = $('#in').value.trim(); if ((!t && !attachments.length)
|
|
91
|
-
$('#in').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault();
|
|
213
|
+
$('#f').onsubmit = e => { e.preventDefault(); const t = $('#in').value.trim(); if (sessionLoading || (!t && !attachments.length)) return; $('#in').value = ''; send(t || '(imagen adjunta)'); };
|
|
214
|
+
$('#in').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); $('#f').requestSubmit(); } });
|
|
92
215
|
$('#in').addEventListener('input', () => { const t = $('#in'); t.style.height = 'auto'; t.style.height = Math.min(t.scrollHeight, 220) + 'px'; });
|
package/public/js/core.js
CHANGED
|
@@ -4,24 +4,43 @@ const $ = s => document.querySelector(s);
|
|
|
4
4
|
const BASE = (location.pathname.match(/^\/w\/[^/]+/) || [''])[0];
|
|
5
5
|
const WS_SLUG = BASE ? BASE.slice(3) : '';
|
|
6
6
|
const log = $('#log');
|
|
7
|
-
let
|
|
8
|
-
|
|
7
|
+
let SESSION_KEY = 'lampson.session:' + (BASE || location.pathname);
|
|
8
|
+
const sessionQuery = new URLSearchParams(location.search);
|
|
9
|
+
let session = sessionQuery.has('session') ? (sessionQuery.get('session') || '') : (localStorage.getItem(SESSION_KEY) || '');
|
|
10
|
+
let busy = false; let cfg = {}; let sessionLoading = false;
|
|
11
|
+
function scopeSessionStorage(project) {
|
|
12
|
+
if (BASE || !project) return;
|
|
13
|
+
SESSION_KEY = 'lampson.session:project:' + project;
|
|
14
|
+
const query = new URLSearchParams(location.search);
|
|
15
|
+
session = query.has('session') ? (query.get('session') || '') : (localStorage.getItem(SESSION_KEY) || '');
|
|
16
|
+
}
|
|
17
|
+
function selectSession(id, navigation = 'replace') {
|
|
18
|
+
session = id;
|
|
19
|
+
if (id) localStorage.setItem(SESSION_KEY, id); else localStorage.removeItem(SESSION_KEY);
|
|
20
|
+
if (navigation === 'none') return;
|
|
21
|
+
const url = new URL(location.href); url.searchParams.delete('proc');
|
|
22
|
+
if (id) url.searchParams.set('session', id); else url.searchParams.delete('session');
|
|
23
|
+
if (url.href !== location.href) history[navigation === 'push' ? 'pushState' : 'replaceState']({ session: id }, '', url);
|
|
24
|
+
}
|
|
9
25
|
|
|
10
26
|
// la carpeta del usuario se muestra como ~ (igual que en el inicio): el nombre de usuario no aparece al compartir
|
|
11
27
|
// pantalla o grabar un video, y la ruta sigue siendo inequívoca
|
|
12
28
|
function shortPath(p) { return String(p || '').replace(/^[a-z]:[\\/]users[\\/][^\\/]+/i, '~').replace(/^\/(home|Users)\/[^/]+/, '~'); }
|
|
13
29
|
function esc(s) { return String(s ?? '').replace(/[&<>]/g, c => ({'&':'&','<':'<','>':'>'}[c])); }
|
|
14
|
-
function
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
30
|
+
function chatFilePath(value) {
|
|
31
|
+
let path = String(value).replace(/\\/g, '/').replace(/(?:#L\d+(?:C\d+)?|:\d+(?::\d+)?)$/, '');
|
|
32
|
+
const root = String(cfg.workspace || '').replace(/\\/g, '/').replace(/\/$/, '');
|
|
33
|
+
if (root && path.toLowerCase().startsWith(root.toLowerCase() + '/')) path = path.slice(root.length + 1);
|
|
34
|
+
path = path.replace(/^\.\//, '').replace(/^workspace\//, '');
|
|
35
|
+
if (!path || /\s/.test(path) || /^(?:[a-z][\w+.-]*:|\/|#)/i.test(path) || path.split('/').includes('..')) return '';
|
|
36
|
+
return /(?:^|\/)[^/]+\.(?:syn|fsyn|md|mdx|txt|json|jsonl|csv|tsv|html?|css|[cm]?js|jsx|tsx?|py|rs|go|toml|ya?ml|xml|sql|sh|ps1|log|pdf|png|jpe?g|svg|webp|xlsx?|docx?|zip)(?::\d+)?$/i.test(path) ? path : '';
|
|
37
|
+
}
|
|
38
|
+
function chatLink(label, target) {
|
|
39
|
+
const attr = s => esc(s).replace(/"/g, '"').replace(/'/g, ''');
|
|
40
|
+
if (/^https?:\/\/[^\s<>]+$/i.test(target)) return `<a href="${attr(target)}" target="_blank" rel="noopener noreferrer">${label}</a>`;
|
|
41
|
+
const path = chatFilePath(target);
|
|
42
|
+
const pos = String(target).match(/(?:#L|:)(\d+)(?:(?:C|:)(\d+))?$/);
|
|
43
|
+
return path ? `<a href="#" data-chat-file="${attr(path)}"${pos ? ` data-chat-line="${Number(pos[1])}" data-chat-column="${Number(pos[2] || 1)}"` : ''}>${label}</a>` : label;
|
|
25
44
|
}
|
|
26
45
|
// un bloque en el chat: 'user' | 'assistant' | 'step' | 'meta' | 'denied' | 'approval' | 'working'
|
|
27
46
|
function add(cls, html) { showPane('log'); log.classList.remove('hero'); const d = document.createElement('div'); d.className = 'msg ' + cls; d.innerHTML = html; log.appendChild(d); $('#stage').scrollTop = $('#stage').scrollHeight; return d; }
|
package/public/js/editor.js
CHANGED
|
@@ -33,7 +33,7 @@ function langOf(path) {
|
|
|
33
33
|
const i = base.lastIndexOf('.'); const ext = i >= 0 ? base.slice(i + 1) : '';
|
|
34
34
|
return LANG_BY_EXT[ext] || 'plaintext';
|
|
35
35
|
}
|
|
36
|
-
// código en un bloque ``` del chat (
|
|
36
|
+
// código en un bloque ``` del chat (markdown.js): resaltado si el fence trae un lenguaje conocido
|
|
37
37
|
function hlCode(code, lang) {
|
|
38
38
|
if (typeof hljs === 'undefined') return esc(code);
|
|
39
39
|
const l = String(lang || '').toLowerCase(); const name = LANG_BY_EXT[l] || (l && hljs.getLanguage(l) ? l : '');
|
|
@@ -125,6 +125,16 @@ function edOpen(d) {
|
|
|
125
125
|
eta.scrollTop = 0; eta.scrollLeft = 0; edSync();
|
|
126
126
|
if (!ED.readonly) eta.focus({ preventScroll: true });
|
|
127
127
|
}
|
|
128
|
+
function edGoTo(line, column = 1) {
|
|
129
|
+
const lines = eta.value.split('\n');
|
|
130
|
+
const index = Math.max(0, Math.min(lines.length - 1, Math.floor(Number(line) || 1) - 1));
|
|
131
|
+
const col = Math.max(0, Math.min(lines[index].length, Math.floor(Number(column) || 1) - 1));
|
|
132
|
+
let offset = col;
|
|
133
|
+
for (let i = 0; i < index; i++) offset += lines[i].length + 1;
|
|
134
|
+
eta.focus({ preventScroll: true }); eta.setSelectionRange(offset, offset);
|
|
135
|
+
const height = parseFloat(getComputedStyle(eta).lineHeight) || 21;
|
|
136
|
+
eta.scrollTop = Math.max(0, index * height - eta.clientHeight / 3); edSync();
|
|
137
|
+
}
|
|
128
138
|
function edStash() { if (!ED.path) return; if (ED.dirty) drafts.set(ED.path, eta.value); else drafts.delete(ED.path); }
|
|
129
139
|
// cierra el editor (✕ del visor, tras confirmar si había cambios); el visor vuelve a su <pre> de texto
|
|
130
140
|
function edClose(discard) {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Marked + DOMPurify are vendored: rendering needs no CDN or network connection.
|
|
2
|
+
let chatMarkdown;
|
|
3
|
+
function md(src) {
|
|
4
|
+
if (typeof marked === 'undefined' || typeof DOMPurify === 'undefined') return '<p>' + esc(src) + '</p>';
|
|
5
|
+
if (!chatMarkdown) {
|
|
6
|
+
let inLink = false;
|
|
7
|
+
const filePattern = /^(?:[A-Za-z]:[\\/])?[\w./\\-]+\.(?:syn|fsyn|md|mdx|txt|json|jsonl|csv|tsv|html?|css|[cm]?js|jsx|tsx?|py|rs|go|toml|ya?ml|xml|sql|sh|ps1|log|pdf|png|jpe?g|svg|webp|xlsx?|docx?|zip)(?::\d+(?::\d+)?|#L\d+(?:C\d+)?)?(?![\w.])/i;
|
|
8
|
+
chatMarkdown = new marked.Marked({
|
|
9
|
+
gfm: true, breaks: true,
|
|
10
|
+
renderer: {
|
|
11
|
+
html({ text }) { return esc(text); },
|
|
12
|
+
link({ href, tokens }) {
|
|
13
|
+
const previous = inLink; inLink = true;
|
|
14
|
+
let label;
|
|
15
|
+
try { label = this.parser.parseInline(tokens); } finally { inLink = previous; }
|
|
16
|
+
return chatLink(label, href);
|
|
17
|
+
},
|
|
18
|
+
image({ text, href }) { return chatLink(esc(text || href), href); },
|
|
19
|
+
codespan({ text }) {
|
|
20
|
+
const label = '<code>' + esc(text) + '</code>';
|
|
21
|
+
return inLink ? label : chatLink(label, text);
|
|
22
|
+
},
|
|
23
|
+
code({ text, lang }) {
|
|
24
|
+
const language = String(lang || '').split(/\s+/)[0];
|
|
25
|
+
const highlighted = typeof hlCode === 'function' ? hlCode(text, language) : esc(text);
|
|
26
|
+
return '<div class="chat-code"><div class="chat-code-bar"><span>' + esc(language || 'texto') +
|
|
27
|
+
'</span><button type="button" data-copy-code aria-label="Copiar código">Copiar</button></div><pre><code class="hljs">' + highlighted + '</code></pre></div>\n';
|
|
28
|
+
},
|
|
29
|
+
table(token) {
|
|
30
|
+
return '<div class="chat-table" role="region" aria-label="Tabla" tabindex="0">' + marked.Renderer.prototype.table.call(this, token) + '</div>';
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
extensions: [{
|
|
34
|
+
name: 'chatFile', level: 'inline',
|
|
35
|
+
start(src) { const m = /(?:^|[\s(])(?=(?:[A-Za-z]:[\\/])?[\w./\\-]+\.[a-z])/i.exec(src); return m ? m.index + m[0].length : undefined; },
|
|
36
|
+
tokenizer(src) {
|
|
37
|
+
const m = filePattern.exec(src);
|
|
38
|
+
if (m && chatFilePath(m[0])) return { type: 'chatFile', raw: m[0], text: m[0] };
|
|
39
|
+
},
|
|
40
|
+
renderer(token) { return inLink ? esc(token.text) : chatLink(esc(token.text), token.text); },
|
|
41
|
+
}],
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return DOMPurify.sanitize(chatMarkdown.parse(String(src ?? '')), {
|
|
45
|
+
ALLOWED_TAGS: ['p', 'br', 'strong', 'b', 'em', 'i', 'del', 's', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'hr', 'a', 'pre', 'code', 'span', 'div', 'button', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'input'],
|
|
46
|
+
ALLOWED_ATTR: ['href', 'target', 'rel', 'class', 'type', 'disabled', 'checked', 'start', 'align', 'role', 'tabindex', 'aria-label', 'data-chat-file', 'data-chat-line', 'data-chat-column', 'data-copy-code'],
|
|
47
|
+
ALLOW_DATA_ATTR: false,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
async function copyChatCode(button) {
|
|
51
|
+
const code = button.closest('.chat-code').querySelector('pre code').textContent;
|
|
52
|
+
try {
|
|
53
|
+
if (navigator.clipboard && window.isSecureContext) await navigator.clipboard.writeText(code);
|
|
54
|
+
else {
|
|
55
|
+
const field = document.createElement('textarea'); field.value = code;
|
|
56
|
+
field.style.cssText = 'position:fixed;opacity:0;pointer-events:none'; document.body.appendChild(field);
|
|
57
|
+
const focused = document.activeElement;
|
|
58
|
+
try { field.select(); if (!document.execCommand('copy')) throw new Error('copy'); }
|
|
59
|
+
finally { field.remove(); if (focused) focused.focus({ preventScroll: true }); }
|
|
60
|
+
}
|
|
61
|
+
button.textContent = 'Copiado';
|
|
62
|
+
} catch (_) { button.textContent = 'No se pudo copiar'; }
|
|
63
|
+
setTimeout(() => { button.textContent = 'Copiar'; }, 2000);
|
|
64
|
+
}
|
|
65
|
+
log.addEventListener('click', ev => {
|
|
66
|
+
const button = ev.target.closest('button[data-copy-code]');
|
|
67
|
+
if (button) { ev.preventDefault(); copyChatCode(button); return; }
|
|
68
|
+
const link = ev.target.closest('a[data-chat-file]');
|
|
69
|
+
if (!link) return;
|
|
70
|
+
ev.preventDefault();
|
|
71
|
+
openFile(link.dataset.chatFile, null, { line: Number(link.dataset.chatLine || 1), column: Number(link.dataset.chatColumn || 1) });
|
|
72
|
+
});
|
package/public/js/sessions.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// sessions.js — sesiones: las últimas 4 en el panel, «ver todas» abre el Panel (browse) con búsqueda en
|
|
2
2
|
// títulos y contenido (GET /api/sessions/search?q=) y una previsualización de la conversación; traza.
|
|
3
|
-
function forgetSession(id) { if (id === session)
|
|
4
|
-
async function deleteSession(id) { await api(BASE + '/api/sessions/delete', { id }); forgetSession(id); loadSessions(); }
|
|
3
|
+
function forgetSession(id) { if (id === session) newConversation('replace'); }
|
|
4
|
+
async function deleteSession(id) { if (busy && id === session) return; await api(BASE + '/api/sessions/delete', { id }); forgetSession(id); loadSessions(); }
|
|
5
5
|
// etiqueta corta de una sesión: la hora HHMMSS de su id (YYYYMMDD-HHMMSS, o YYYYMMDD-HHMMSS-NNNN las del runtime)
|
|
6
6
|
function sessionLabel(id) { const m = /^\d{8}-(\d{6})/.exec(id); return m ? m[1] : id.slice(-6); }
|
|
7
7
|
async function loadSessions() {
|
|
@@ -48,23 +48,44 @@ function openSessionsPanel() {
|
|
|
48
48
|
}
|
|
49
49
|
});
|
|
50
50
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const r = await fetch(BASE + '/api/sessions/' + id); if (!r.ok) { session = ''; empty(); return loadSessions(); }
|
|
54
|
-
const d = await r.json();
|
|
51
|
+
let sessionLoadVersion = 0;
|
|
52
|
+
function paintSessionMessages(messages) {
|
|
55
53
|
const queue = []; // pasos sin resultado todavía, en orden (varias tool calls por turno)
|
|
56
|
-
for (const m of
|
|
54
|
+
for (const m of messages) {
|
|
57
55
|
// los avisos del harness viajan con role user (lo exige el wire) pero no los escribió el usuario:
|
|
58
56
|
// al recargar se muestran como meta (✉), igual que en vivo — nunca con la etiqueta "vos"
|
|
59
57
|
if (m.role === 'user') { queue.length = 0; const t = String(m.content || ''); if (t.startsWith('[harness]') || t.startsWith('[Context compacted')) add('meta', '✉ ' + esc(t.split('\n')[0].slice(0, 160))); else add('user', esc(m.content) + imagesHtml(m.images)); }
|
|
60
58
|
else if (m.role === 'assistant') { if (m.content) add('assistant', md(m.content)); for (const c of (m.tool_calls || [])) { const el = add('step', `<span class="ic">⚙</span>${cmdHtml(describe(c))}`); wireMore(el); queue.push(el); } }
|
|
61
|
-
else if (m.role === 'tool') { const out = String(m.content); const bad = /^(ERROR|DENIED)/.test(out); const el = queue.shift() || add('step', '<span class="ic">→</span>'); const ic = el.querySelector('.ic'); if (ic) { ic.textContent = bad ? '✗' : '✓'; ic.className = 'ic ' + (bad ? 'bad' : 'ok'); } el.insertAdjacentHTML('beforeend', `<details><summary class="${bad ? 'bad' : ''}">${esc(out.split('\n')[0].slice(0, 140))} <span style="color:var(--ink-3)">(${out.length} chars)</span></summary><pre>${esc(out)}</pre></details>`); }
|
|
59
|
+
else if (m.role === 'tool') { const out = String(m.content); const bad = /^(ERROR|DENIED)/.test(out); const skipped = /^NOT RUN:/.test(out); const el = queue.shift() || add('step', '<span class="ic">→</span>'); const ic = el.querySelector('.ic'); if (ic) { ic.textContent = skipped ? '↷' : (bad ? '✗' : '✓'); ic.className = 'ic ' + (bad ? 'bad' : 'ok'); } el.insertAdjacentHTML('beforeend', `<details><summary class="${bad ? 'bad' : ''}">${esc(out.split('\n')[0].slice(0, 140))} <span style="color:var(--ink-3)">(${out.length} chars)</span></summary><pre>${esc(out)}</pre></details>`); }
|
|
62
60
|
}
|
|
63
|
-
loadSessions();
|
|
64
61
|
}
|
|
62
|
+
function newConversation(navigation = 'push') {
|
|
63
|
+
sessionLoadVersion++; detachChat(); sessionLoading = false; $('#send').disabled = false;
|
|
64
|
+
selectSession('', navigation); log.innerHTML = ''; showPane('log'); empty(); loadSessions(); loadTodo();
|
|
65
|
+
}
|
|
66
|
+
async function openSession(id, navigation = 'push') {
|
|
67
|
+
if (!id) { newConversation(navigation); return; }
|
|
68
|
+
const version = ++sessionLoadVersion;
|
|
69
|
+
detachChat(); selectSession(id, navigation); log.innerHTML = ''; log.classList.remove('hero'); showPane('log');
|
|
70
|
+
sessionLoading = true; $('#send').disabled = true;
|
|
71
|
+
const loading = add('working', '<span class="dot"></span><span>cargando conversación…</span>');
|
|
72
|
+
try {
|
|
73
|
+
const r = await fetch(BASE + '/api/sessions/' + encodeURIComponent(id));
|
|
74
|
+
if (version !== sessionLoadVersion) return;
|
|
75
|
+
if (r.status === 404) { newConversation('replace'); return; }
|
|
76
|
+
if (!r.ok) throw new Error('HTTP ' + r.status);
|
|
77
|
+
const d = await r.json(); if (version !== sessionLoadVersion) return;
|
|
78
|
+
loading.remove(); paintSessionMessages(d.messages || []); loadTodo(); loadSessions();
|
|
79
|
+
sessionLoading = false; $('#send').disabled = false;
|
|
80
|
+
if (d.run && d.run.active) attachChat(id, d.run.id, d.run.pending || []);
|
|
81
|
+
} catch (e) { if (version === sessionLoadVersion) add('meta', 'No se pudo abrir la conversación: ' + esc(e.message)); }
|
|
82
|
+
finally { loading.remove(); if (version === sessionLoadVersion) { sessionLoading = false; $('#send').disabled = false; } }
|
|
83
|
+
}
|
|
84
|
+
|
|
65
85
|
// objetivos y equipos: su pantalla propia (public/teams.html)
|
|
66
86
|
$('#teamsBtn').onclick = () => { location.href = BASE + '/equipos'; };
|
|
67
|
-
$('#new').onclick = () =>
|
|
87
|
+
$('#new').onclick = () => newConversation();
|
|
88
|
+
window.addEventListener('popstate', () => openSession(new URLSearchParams(location.search).get('session') || '', 'none'));
|
|
68
89
|
// traza legible de una sesión (.lampson/trace/<sid>.log)
|
|
69
90
|
async function openTrace(id) {
|
|
70
91
|
procOpen = null; agentOpen = null;
|
package/public/js/tree.js
CHANGED
|
@@ -242,7 +242,7 @@ function showMenu(x, y, e, only) {
|
|
|
242
242
|
}
|
|
243
243
|
|
|
244
244
|
// abre el archivo en el editor (js/editor.js): colores por tipo de archivo, Ctrl+S guarda. El <pre> #vbody queda para logs.
|
|
245
|
-
async function openFile(path, row) {
|
|
245
|
+
async function openFile(path, row, position) {
|
|
246
246
|
document.querySelectorAll('.row.active').forEach(x => x.classList.remove('active')); if (row) row.classList.add('active');
|
|
247
247
|
const r = await fetch(BASE + '/api/file?path=' + encodeURIComponent(path)); const d = await r.json();
|
|
248
248
|
if (!r.ok) { viewerNotice(path, 'no se pudo abrir', String(d.error || 'error')); return; }
|
|
@@ -251,6 +251,7 @@ async function openFile(path, row) {
|
|
|
251
251
|
$('#vpath').textContent = d.path; $('#vbody').className = '';
|
|
252
252
|
edOpen(d);
|
|
253
253
|
showPane('viewer'); $('#stage').scrollTop = 0;
|
|
254
|
+
if (position) edGoTo(position.line, position.column);
|
|
254
255
|
}
|
|
255
256
|
// avisos del visor (binario, error al abrir): en el propio visor, no como mensaje en el chat
|
|
256
257
|
function viewerNotice(path, meta, text) { showText(path, meta, text, false); }
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Browser dependencies are stored locally so the UI works without a CDN.
|
|
2
|
+
|
|
3
|
+
Markdown rendering:
|
|
4
|
+
|
|
5
|
+
- Marked 18.4.0: `https://cdn.jsdelivr.net/npm/marked@18.4.0/lib/marked.umd.js` (MIT, see marked.LICENSE).
|
|
6
|
+
- DOMPurify 3.5.0: `https://cdn.jsdelivr.net/npm/dompurify@3.5.0/dist/purify.min.js` (see dompurify.LICENSE).
|
|
7
|
+
|
|
8
|
+
When upgrading, replace the pinned build and license together and run the chat Markdown tests.
|