lampson 0.5.4 → 0.5.6

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.
@@ -0,0 +1,373 @@
1
+ -- Chat web: sesión persistida antes del inicio y worker independiente de las conexiones del navegador.
2
+ -- Input entre herramientas, aprobaciones y diario de eventos reanudable; una ejecución por sesión.
3
+ use "./runtime.syn" as runtime
4
+ use "./mailbox.syn" as mailbox
5
+ use "./loop.syn" as loop
6
+ use "./agents.syn" as agents
7
+ use "./session.syn" as session
8
+ use "./approvals.syn" as approvals
9
+ use "./permission.syn" as permission
10
+
11
+ export task enqueue(sid, item)
12
+ when not session.valid_id(sid)
13
+ give false
14
+ give mailbox.enqueue_active("web:" + sid, item)
15
+
16
+ export task stop_pending(sid)
17
+ give length(where(mailbox.peek("web:" + sid), (it) => it["kind"] == "stop")) > 0
18
+
19
+ task deliver(sobre, hooks)
20
+ require db(".lampson/teams.db")
21
+ require net
22
+ require net("0.0.0.0/0")
23
+ require net("::/0")
24
+ require exec
25
+ require judge
26
+ require time
27
+ require random
28
+ require file(".lampson")
29
+ require file(".lampson/**")
30
+ require file("workspace")
31
+ require file("workspace/**")
32
+ require file.read("skills")
33
+ require file.read("skills/**")
34
+ require file.read("plugins")
35
+ require file.read("plugins/**")
36
+ require file.read("agents")
37
+ require file.read("agents/**")
38
+ require file.read("memory")
39
+ require file.read("memory/**")
40
+ require env("LAMPSON_*")
41
+ require env("OS")
42
+ require secret("LAMPSON_*")
43
+ let o be runtime.open(sobre, hooks)
44
+ let sid be o["session"]
45
+ let k be "web:" + sid
46
+ let cb be hooks["on_event"]
47
+ let ctx be o["ctx"]
48
+ let opts be ctx["opts"]
49
+ let prev be opts["inbox_fn"]
50
+ task inputs(step, tag)
51
+ let msgs be []
52
+ let halt be false
53
+ each it in mailbox.take(k)
54
+ when it["kind"] == "stop"
55
+ set halt to true
56
+ otherwise
57
+ set msgs to append(msgs, {"role": "user", "content": it["text"], "images": it["images"]})
58
+ call(cb, {"kind": "user_input", "data": it, "tag": ""})
59
+ call(cb, {"kind": "input_applied", "data": {"id": it["id"]}, "tag": ""})
60
+ when length(msgs) == 0 and not halt
61
+ give nothing
62
+ give {"messages": msgs, "stop": halt}
63
+ task inbox(step, tag)
64
+ let incoming be inputs(step, tag)
65
+ let msgs be when incoming == nothing then [] otherwise incoming["messages"]
66
+ let halt be when incoming == nothing then false otherwise incoming["stop"]
67
+ when prev != nothing
68
+ let reports be call(prev, {"step": step, "tag": tag})
69
+ when reports != nothing
70
+ set msgs to msgs + reports["messages"]
71
+ when length(msgs) == 0 and not halt
72
+ give nothing
73
+ give {"messages": msgs, "stop": halt}
74
+ task final_inbox(step, tag)
75
+ let deadline be now() + 900
76
+ while true
77
+ let incoming be inbox(step, tag)
78
+ when incoming != nothing
79
+ give incoming
80
+ let children be where(agents.list_children(), (c) => get(c, "parent", "") == sid and c["status"] == "running" and not c["delivered"])
81
+ when length(children) == 0 or now() >= deadline
82
+ give inbox(step, tag)
83
+ sleep(0.25)
84
+ set opts to loop.with_final_inbox(loop.with_inbox(opts, inbox, ""))
85
+ -- Como Hermes/DeepSeek/OpenCode: el texto entra en el próximo paso del modelo, tras el lote.
86
+ -- Entre herramientas solo se consulta Detener; no se acusa una indicación como incorporada antes de tiempo.
87
+ task control(step, tag)
88
+ when stop_pending(sid)
89
+ give inputs(step, tag)
90
+ give nothing
91
+ set opts["control_fn"] to control
92
+ task stop_requested()
93
+ give stop_pending(sid)
94
+ set opts["stop_pending_fn"] to stop_requested
95
+ set opts["final_inbox_fn"] to final_inbox
96
+ set ctx["opts"] to opts
97
+ set o["ctx"] to ctx
98
+ -- start() ya guardó el primer mensaje antes de anunciar la sesión.
99
+ let msgs be o["messages"]
100
+ let system be msgs[0]
101
+ set system["content"] to system["content"] + "\n\n# Live web conversation\nMessages received while you work are updates to the active conversation. A status question, acknowledgement, or supplementary instruction does not cancel or replace the original task. Briefly answer side questions and continue outstanding authorized work in the same turn, without asking whether to continue. Redirect or stop only when the user actually requests that. Pending tool batches can finish before you see an update; review their results and apply new constraints to subsequent actions. Do not claim that a tool was cancelled merely because a new message arrived."
102
+ set msgs to [system] + slice(msgs, 1, length(msgs))
103
+ let result be nothing
104
+ let steps be 0
105
+ let usage be {"input": 0, "output": 0, "cached": 0}
106
+ let running be true
107
+ try
108
+ let cfg be ctx["cfg"]
109
+ call(hooks["on_start"], {"info": {"session": sid, "agent": ctx["agent"], "thread": o["thread"], "mode": o["mode"], "provider": cfg["provider"], "model": cfg["model"], "has_key": cfg["has_key"]}})
110
+ when o["note"] != ""
111
+ call(cb, {"kind": "inbox", "data": o["note"], "tag": ""})
112
+ when starts_with(trim(sobre["text"]), "!")
113
+ -- El comando lo escribió el usuario: misma autorización explícita que la puerta web original.
114
+ let cmd be trim(slice(trim(sobre["text"]), 1, length(trim(sobre["text"]))))
115
+ let tc be {"id": "user", "name": "bash", "args": {"command": cmd}}
116
+ set msgs to append(msgs, {"role": "assistant", "content": "", "tool_calls": [tc]})
117
+ call(cb, {"kind": "tool_call", "data": tc, "tag": ""})
118
+ let bash_tool be agents.registry_for("build")["bash"]
119
+ let output be call_tool(bash_tool, {"command": cmd, "timeout": 600})
120
+ set msgs to append(msgs, {"role": "tool", "tool_call_id": "user", "name": "bash", "content": output})
121
+ call(cb, {"kind": "tool_result", "data": {"call": tc, "output": output}, "tag": ""})
122
+ runtime.save(o, msgs)
123
+ set result to {"text": "", "stopped": "user_command"}
124
+ when mailbox.release(k)
125
+ set running to false
126
+ while running
127
+ set result to runtime.turn(o, msgs, "", hooks)
128
+ set msgs to result["messages"]
129
+ set steps to steps + result["steps"]
130
+ each field in ["input", "output", "cached"]
131
+ set usage[field] to usage[field] + get(result["usage"], field, 0)
132
+ -- Si el input llegó entre el checkpoint final y el guardado, se atiende antes de soltar la sesión.
133
+ -- Encolar y soltar usan el mismo lock: el mensaje se acepta aquí o el cliente recibe 409 y reenvía.
134
+ when mailbox.release(k)
135
+ set running to false
136
+ recover err
137
+ -- Un fallo libera la sesión y conserva el input que todavía esté en la cola.
138
+ while running
139
+ each it in mailbox.take(k)
140
+ when it["kind"] == "input"
141
+ set msgs to append(msgs, {"role": "user", "content": it["text"], "images": it["images"]})
142
+ runtime.save(o, msgs)
143
+ when mailbox.release(k)
144
+ set running to false
145
+ call(cb, {"kind": "error", "data": text(err), "tag": ""})
146
+ set result to {"text": "", "stopped": "error: " + text(err)}
147
+ give {"agent": ctx["agent"], "thread": o["thread"], "session": sid, "text": result["text"], "steps": steps, "usage": usage, "stopped": result["stopped"]}
148
+
149
+ -- Diario de eventos independiente de las conexiones del navegador. Un solo worker escribe por corrida.
150
+ -- El lector nunca avanza sobre un hueco: una recarga puede repetir eventos sin duplicarlos.
151
+ task publish(run_id, kind, data, tag)
152
+ let seq be state_incr("wc:seq:" + run_id, 1)
153
+ state_set("wc:event:" + run_id + ":" + text(seq), {"kind": kind, "data": data, "tag": tag, "run": run_id, "seq": seq})
154
+
155
+ export task event_at(run_id, seq)
156
+ give state_get("wc:event:" + run_id + ":" + text(seq), nothing)
157
+
158
+ export task run_info(run_id)
159
+ give state_get("wc:run:" + run_id, nothing)
160
+
161
+ task purge_run(run_id)
162
+ let seq be state_get("wc:seq:" + run_id, 0)
163
+ let i be 1
164
+ while i <= seq
165
+ state_delete("wc:event:" + run_id + ":" + text(i))
166
+ set i to i + 1
167
+ state_delete("wc:seq:" + run_id)
168
+ state_delete("wc:run:" + run_id)
169
+
170
+ export task forget(sid)
171
+ let run_id be state_get("wc:current:" + sid, "")
172
+ when run_id != ""
173
+ let info be run_info(run_id)
174
+ when info != nothing
175
+ when info["active"]
176
+ give false
177
+ purge_run(run_id)
178
+ state_delete("wc:current:" + sid)
179
+ give true
180
+
181
+ export task status(sid)
182
+ let run_id be state_get("wc:current:" + sid, "")
183
+ when run_id == ""
184
+ give nothing
185
+ let info be run_info(run_id)
186
+ when info == nothing
187
+ give nothing
188
+ give {"id": run_id, "active": info["active"], "base": when info["active"] then info["base"] otherwise [], "pending": where(mailbox.peek("web:" + sid), (it) => it["kind"] == "input")}
189
+
190
+ export task begin(body)
191
+ require db(".lampson/teams.db")
192
+ require net
193
+ require net("0.0.0.0/0")
194
+ require net("::/0")
195
+ require exec
196
+ require judge
197
+ require time
198
+ require random
199
+ require file(".lampson")
200
+ require file(".lampson/**")
201
+ require file("workspace")
202
+ require file("workspace/**")
203
+ require file.read("skills")
204
+ require file.read("skills/**")
205
+ require file.read("plugins")
206
+ require file.read("plugins/**")
207
+ require file.read("agents")
208
+ require file.read("agents/**")
209
+ require file.read("memory")
210
+ require file.read("memory/**")
211
+ require env("LAMPSON_*")
212
+ require env("OS")
213
+ require secret("LAMPSON_*")
214
+ let mode be lower(text(get(body, "permission", env("LAMPSON_PERMISSION", "ask"))))
215
+ when not contains(["ask", "yolo", "strict"], mode)
216
+ set mode to "ask"
217
+ let want be lower(text(get(body, "agent", "build")))
218
+ when not contains(runtime.names(), want)
219
+ set want to "build"
220
+ let images be []
221
+ let total be 0
222
+ each im in get(body, "images", [])
223
+ when contains(im, "data") and contains(im, "media_type")
224
+ set total to total + length(im["data"])
225
+ when total <= 5000000
226
+ let entry be {"media_type": text(im["media_type"]), "data": text(im["data"])}
227
+ when contains(im, "w") and contains(im, "h")
228
+ set entry to {"media_type": entry["media_type"], "data": entry["data"], "w": floor(number(im["w"])), "h": floor(number(im["h"]))}
229
+ set images to append(images, entry)
230
+ let envelope be {"to": want, "session": text(get(body, "session", "")), "from": {"id": "", "name": "", "kind": "human"}, "text": body["message"], "images": images, "channel": "web", "meta": {}}
231
+ give start(envelope, {"mode": mode, "provider": lower(text(get(body, "provider", ""))), "model": text(get(body, "model", "")), "await_subagents": true})
232
+
233
+ export task start(sobre, options)
234
+ require db(".lampson/teams.db")
235
+ require net
236
+ require net("0.0.0.0/0")
237
+ require net("::/0")
238
+ require exec
239
+ require judge
240
+ require time
241
+ require random
242
+ require file(".lampson")
243
+ require file(".lampson/**")
244
+ require file("workspace")
245
+ require file("workspace/**")
246
+ require file.read("skills")
247
+ require file.read("skills/**")
248
+ require file.read("plugins")
249
+ require file.read("plugins/**")
250
+ require file.read("agents")
251
+ require file.read("agents/**")
252
+ require file.read("memory")
253
+ require file.read("memory/**")
254
+ require env("LAMPSON_*")
255
+ require env("OS")
256
+ require secret("LAMPSON_*")
257
+ -- Rechazar una segunda pestaña antes de reconstruir el contexto; el lock de abajo cierra la carrera.
258
+ let requested be get(sobre, "session", "")
259
+ when requested != "" and mailbox.is_active("web:" + requested)
260
+ give {"ok": false, "session": requested, "error": "conversation is already running"}
261
+ let o be runtime.open(sobre, options)
262
+ let sid be o["session"]
263
+ let k be "web:" + sid
264
+ when not mailbox.begin_inline(k)
265
+ give {"ok": false, "session": sid, "error": "conversation is already running"}
266
+ -- La conversación completa vive en disco; solo la corrida reciente necesita diario de reconexión.
267
+ let previous be state_get("wc:current:" + sid, "")
268
+ when previous != ""
269
+ let old be run_info(previous)
270
+ when old != nothing
271
+ when not old["active"]
272
+ purge_run(previous)
273
+ let run_id be mailbox.new_id()
274
+ let msgs be append(o["messages"], {"role": "user", "content": sobre["text"], "images": sobre["images"]})
275
+ try
276
+ -- La sesión existe en disco ANTES de arrancar el worker o devolver su identificador.
277
+ runtime.save(o, msgs)
278
+ state_set("wc:run:" + run_id, {"session": sid, "active": true, "base": where(msgs, (m) => m["role"] != "system")})
279
+ state_set("wc:current:" + sid, run_id)
280
+ let envelope be sobre
281
+ set envelope["session"] to sid
282
+ spawn WebChatWorker with spec_json = json_encode({"run": run_id, "sobre": envelope, "options": options})
283
+ recover err
284
+ mailbox.release(k)
285
+ state_set("wc:run:" + run_id, {"session": sid, "active": false, "base": []})
286
+ raise(text(err))
287
+ give {"ok": true, "session": sid, "run": run_id}
288
+
289
+ export task work(spec_json)
290
+ require db(".lampson/teams.db")
291
+ require net
292
+ require net("0.0.0.0/0")
293
+ require net("::/0")
294
+ require exec
295
+ require judge
296
+ require time
297
+ require random
298
+ require file(".lampson")
299
+ require file(".lampson/**")
300
+ require file("workspace")
301
+ require file("workspace/**")
302
+ require file.read("skills")
303
+ require file.read("skills/**")
304
+ require file.read("plugins")
305
+ require file.read("plugins/**")
306
+ require file.read("agents")
307
+ require file.read("agents/**")
308
+ require file.read("memory")
309
+ require file.read("memory/**")
310
+ require env("LAMPSON_*")
311
+ require env("OS")
312
+ require secret("LAMPSON_*")
313
+ let spec be json_decode(spec_json)
314
+ let run_id be spec["run"]
315
+ let sid be spec["sobre"]["session"]
316
+ task emit(kind, data, tag)
317
+ publish(run_id, kind, data, tag)
318
+ task on_start(info)
319
+ emit("session", sid, "")
320
+ emit("mode", {"agent": info["agent"], "permission": info["mode"], "provider": info["provider"], "model": info["model"], "has_key": info["has_key"]}, "")
321
+ task ask_web(name, args, why)
322
+ let id be approvals.open("chat", permission.describe_call(name, args), why, 180)
323
+ emit("approval_request", {"id": id, "name": name, "args": args, "why": why, "timeout": 180}, "")
324
+ let t0 be now()
325
+ task stopped()
326
+ give stop_pending(sid)
327
+ let ok be approvals.wait(id, 180, stopped)
328
+ emit("approval_result", {"id": id, "approved": ok, "timeout": (not ok) and now() - t0 >= 179}, "")
329
+ give ok
330
+ let hooks be spec["options"]
331
+ set hooks["on_event"] to emit
332
+ set hooks["on_start"] to on_start
333
+ set hooks["ask_fn"] to ask_web
334
+ let result be nothing
335
+ try
336
+ set result to deliver(spec["sobre"], hooks)
337
+ recover err
338
+ mailbox.release("web:" + sid)
339
+ emit("error", text(err), "")
340
+ set result to {"session": sid, "text": "", "steps": 0, "usage": {"input": 0, "output": 0}, "stopped": "error: " + text(err)}
341
+ emit("done", result, "")
342
+ let info be run_info(run_id)
343
+ set info["active"] to false
344
+ set info["base"] to []
345
+ state_set("wc:run:" + run_id, info)
346
+ give true
347
+
348
+ agent WebChatWorker
349
+ require db(".lampson/teams.db")
350
+ require net
351
+ require net("0.0.0.0/0")
352
+ require net("::/0")
353
+ require exec
354
+ require judge
355
+ require time
356
+ require random
357
+ require file(".lampson")
358
+ require file(".lampson/**")
359
+ require file("workspace")
360
+ require file("workspace/**")
361
+ require file.read("skills")
362
+ require file.read("skills/**")
363
+ require file.read("plugins")
364
+ require file.read("plugins/**")
365
+ require file.read("agents")
366
+ require file.read("agents/**")
367
+ require file("memory")
368
+ require file("memory/**")
369
+ require env("LAMPSON_*")
370
+ require env("OS")
371
+ require secret("LAMPSON_*")
372
+ require sign("LAMPSON_TOOLS")
373
+ lampson_webchat_worker(spec_json)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lampson",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
4
4
  "description": "A coding agent written in Synsema: terminal + web, tools confined to the mounted project, plugins (your own tools, any language), LSP, MCP, sub-agents. Also an SDK: import { Lampson } from \"lampson\" (server or local mode).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -36,6 +36,7 @@
36
36
  "hub.tpl.syn",
37
37
  "edge.syn",
38
38
  "cli.syn",
39
+ "synsema.json",
39
40
  "lampson.ps1",
40
41
  "lampson.sh",
41
42
  "lampson.cmd",
@@ -47,7 +48,7 @@
47
48
  "node": ">=18"
48
49
  },
49
50
  "dependencies": {
50
- "synsema": "0.6.64"
51
+ "synsema": "0.6.67"
51
52
  },
52
53
  "scripts": {
53
54
  "test": "pwsh -NoProfile -File tests/run.ps1"
@@ -128,7 +128,9 @@ textarea:focus { outline:none; }
128
128
  .crow .keys { color:var(--ink-3); font:400 10.5px/1 var(--mono); letter-spacing:.03em; }
129
129
  #send { width:34px; height:30px; padding:0; font-size:15px; display:inline-flex; align-items:center; justify-content:center; }
130
130
  #stop { color:var(--rubric); border-color:var(--rubric); display:none; height:30px; }
131
- form.busy #send { display:none; } form.busy #stop { display:inline-flex; align-items:center; gap:6px; }
131
+ form.busy #stop { display:inline-flex; align-items:center; gap:6px; }
132
+ .input-state { display:block; margin-top:6px; color:var(--ink-3); font-size:12px; }
133
+ .input-state.failed { color:var(--rubric); }
132
134
  .hint { display:none; }
133
135
 
134
136
  @media (max-width:900px) { body { grid-template-columns:1fr; grid-template-areas:"top" "main"; } aside { display:none; } #log, form { padding-left:20px; padding-right:20px; } }
package/public/js/app.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // app.js — arranque: config de la cabecera y primera carga de cada sección (se carga último)
2
2
  async function loadCfg() {
3
3
  try { cfg = await (await fetch(BASE + '/api/config')).json(); } catch (e) { cfg = {}; }
4
+ scopeSessionStorage(cfg.project);
4
5
  const ws = cfg.workspace || '';
5
6
  $('#proj').textContent = ws.split(/[\\/]/).filter(Boolean).pop() || 'workspace'; $('#proj').title = shortPath(ws);
6
7
  $('#hpath').textContent = shortPath(ws); $('#hpath').title = shortPath(ws);
@@ -14,7 +15,7 @@ async function loadCfg() {
14
15
  sel.onchange = () => { localStorage.setItem('lampson.agent', sel.value); hint(); }; hint();
15
16
  if (!log.children.length) empty();
16
17
  }
17
- loadCfg().then(() => { loadTree(); loadSessions(); loadProcs(); loadMemory(); loadAgents(); loadMcp(); loadLsp(); loadPlugins(); loadKeys(); loadChannels(); loadTodo(); loadSched(); loadApprovals(); checkUpdate(); const pq = new URLSearchParams(location.search).get('proc'); if (pq) openProc(pq); else if (session) openSession(session); });
18
+ loadCfg().then(() => { loadTree(); loadSessions(); loadProcs(); loadMemory(); loadAgents(); loadMcp(); loadLsp(); loadPlugins(); loadKeys(); loadChannels(); loadTodo(); loadSched(); loadApprovals(); checkUpdate(); const pq = new URLSearchParams(location.search).get('proc'); if (pq) openProc(pq); else if (session) openSession(session, 'replace'); });
18
19
  // respaldos lentos por si el stream de eventos se cae
19
20
  setInterval(loadProcs, events ? 60000 : 10000);
20
21
  setInterval(() => { loadSched(); if (!events) loadApprovals(); }, events ? 60000 : 15000);
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 aborter = null;
42
- function setBusy(b) { busy = b; $('#f').classList.toggle('busy', b); $('#send').disabled = b; }
43
- $('#stop').onclick = () => { if (aborter) aborter.abort(); };
44
- async function send(message) {
45
- setBusy(true); aborter = new AbortController();
46
- if (log.querySelector('.empty')) { log.innerHTML = ''; log.classList.remove('hero'); }
47
- const images = attachments.map(a => ({ media_type: a.media_type, data: a.data, w: a.w, h: a.h })); attachments = []; paintAttach();
48
- add('user', esc(message) + imagesHtml(images));
49
- const thinking = add('working', '<span class="dot"></span><span>pensando…</span>');
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
- const res = await fetch(BASE + '/api/chat', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ session, message, agent: $('#agent').value || 'build', permission: $('#perm').value || 'ask', images }), signal: aborter.signal });
52
- if (!res.ok || !res.body) { add('denied', 'error HTTP ' + res.status + ' ' + esc(await res.text())); }
53
- else {
54
- const reader = res.body.getReader(); const dec = new TextDecoder(); let buf = '';
55
- while (true) {
56
- const { value, done } = await reader.read(); if (done) break;
57
- buf += dec.decode(value, { stream: true });
58
- let i; while ((i = buf.indexOf('\n\n')) >= 0) { const chunk = buf.slice(0, i); buf = buf.slice(i + 2); handle(chunk, thinking); }
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
- } catch (e) { add('meta', e.name === 'AbortError' ? '■ detenido por vos (el agente para en el próximo paso; el historial queda guardado hasta ahí)' : '‼ ' + esc(e.message)); }
62
- thinking.remove(); aborter = null; setBusy(false); loadSessions(); loadTree(); loadProcs(); loadMemory(); loadAgents();
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 (k === 'session') { const changed = d !== session; session = d; localStorage.setItem('lampson.session', d); if (changed) loadTodo(); }
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) || busy) return; $('#in').value = ''; send(t || '(imagen adjunta)'); };
91
- $('#in').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (!busy) $('#f').requestSubmit(); } });
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'; });