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.
package/public/js/core.js CHANGED
@@ -4,8 +4,24 @@ 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 session = new URLSearchParams(location.search).get('session') || localStorage.getItem('lampson.session') || '';
8
- let busy = false; let cfg = {};
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
@@ -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) { session = ''; localStorage.removeItem('lampson.session'); log.innerHTML = ''; showPane('log'); empty(); } }
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
- async function openSession(id) {
52
- session = id; localStorage.setItem('lampson.session', id); log.innerHTML = ''; log.classList.remove('hero'); showPane('log'); loadTodo();
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 d.messages) {
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 = () => { session = ''; localStorage.removeItem('lampson.session'); log.innerHTML = ''; showPane('log'); empty(); loadSessions(); loadTodo(); };
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/synsema.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "synsema": "0.6.67"
3
+ }
package/web.syn CHANGED
@@ -82,6 +82,7 @@ use "./lib/runtime.syn" as runtime
82
82
  use "./lib/api.syn" as api
83
83
  use "./lib/apikeys.syn" as apikeys
84
84
  use "./lib/mailbox.syn" as mailbox
85
+ use "./lib/webchat.syn" as webchat
85
86
  use "./lib/teamrun.syn" as teamrun
86
87
  use "./lib/teams.syn" as teams
87
88
  use "./lib/channels.syn" as channels
@@ -129,6 +130,9 @@ task lampson_subagent(spec_json)
129
130
  task lampson_mailbox_worker(spec_json)
130
131
  give mailbox.work(spec_json)
131
132
 
133
+ task lampson_webchat_worker(spec_json)
134
+ give webchat.work(spec_json)
135
+
132
136
  -- Canales en modo sin URL pública (lib/channels.syn): un agente ChannelPoller por canal; el tick lo mantiene vivo
133
137
  task lampson_channel_poller(name)
134
138
  give channels.poll_loop(name)
@@ -232,13 +236,21 @@ serve on 8080
232
236
  when not session.exists(params.id)
233
237
  give not_found("session not found")
234
238
  let doc be session.load(params.id)
239
+ when get(doc["meta"], "project", memo.slug()) != memo.slug()
240
+ give not_found("session not found in this workspace")
241
+ let active be webchat.status(params.id)
242
+ let run be nothing
235
243
  let visible be where(doc["messages"], (m) => m["role"] != "system")
236
- give {"id": doc["id"], "updated": doc["updated"], "meta": doc["meta"], "messages": visible}
244
+ when active != nothing
245
+ set run to {"id": active["id"], "active": active["active"], "pending": active["pending"]}
246
+ when active["active"]
247
+ set visible to active["base"]
248
+ give {"id": doc["id"], "updated": doc["updated"], "meta": doc["meta"], "messages": visible, "run": run}
237
249
 
238
250
  route "GET /w/:slug/api/config" requires auth
239
251
  private
240
252
  let cfg be provider.config()
241
- give {"provider": cfg["provider"], "model": cfg["model"], "wire": cfg["wire"], "vision": provider.supports_vision(cfg), "providers": provider.providers(), "configured": provider.configured(), "permission": lower(env("LAMPSON_PERMISSION", "ask")), "agents": agents.names(), "workspace": env("LAMPSON_WORKSPACE", "./workspace"), "profiles": agents.PROFILES}
253
+ give {"provider": cfg["provider"], "model": cfg["model"], "wire": cfg["wire"], "vision": provider.supports_vision(cfg), "providers": provider.providers(), "configured": provider.configured(), "permission": lower(env("LAMPSON_PERMISSION", "ask")), "agents": agents.names(), "workspace": env("LAMPSON_WORKSPACE", "./workspace"), "project": memo.slug(), "profiles": agents.PROFILES}
242
254
 
243
255
  -- proveedor/modelo por defecto y API keys → .lampson/config.json (local). La key nunca vuelve al cliente.
244
256
  route "POST /w/:slug/api/settings" requires auth
@@ -259,6 +271,8 @@ serve on 8080
259
271
  private
260
272
  expect body {id: text}
261
273
  let b be json of request
274
+ when not webchat.forget(text(b["id"]))
275
+ give fail(409, "stop this conversation before deleting it")
262
276
  give {"result": session.delete(text(b["id"]))}
263
277
 
264
278
  route "GET /w/:slug/api/tree" requires auth
@@ -719,73 +733,97 @@ serve on 8080
719
733
  let n be when contains(query, "tail") then floor(number(query.tail)) otherwise 300
720
734
  give {"id": query.id, "log": schedule.log_tail(query.id, n), "task": schedule.get(query.id)}
721
735
 
736
+ route "POST /w/:slug/api/chat/input" requires auth
737
+ private
738
+ expect body {session: text, message: text, id: text}
739
+ let b be json of request
740
+ when not matches(b["id"], "[A-Za-z0-9_-]{1,96}")
741
+ give fail(400, "invalid input id")
742
+ let images be []
743
+ let total be 0
744
+ each im in get(b, "images", [])
745
+ when contains(im, "data") and contains(im, "media_type")
746
+ set total to total + length(im["data"])
747
+ when total <= 5000000
748
+ set images to append(images, {"media_type": text(im["media_type"]), "data": text(im["data"])})
749
+ when not webchat.enqueue(b["session"], {"kind": "input", "id": b["id"], "text": b["message"], "images": images})
750
+ give fail(409, "conversation is idle; send this message through /api/chat")
751
+ give respond(json_encode({"ok": true, "id": b["id"], "status": "queued"}), "application/json", 202)
752
+
753
+ route "POST /w/:slug/api/chat/stop" requires auth
754
+ private
755
+ expect body {session: text}
756
+ let b be json of request
757
+ let active be webchat.enqueue(b["session"], {"kind": "stop"})
758
+ give {"ok": true, "active": active}
759
+
760
+ route "POST /w/:slug/api/chat/start" requires auth
761
+ private
762
+ expect body {message: text}
763
+ state_set("lampson:last_used", now())
764
+ let started be webchat.begin(json of request)
765
+ when not started["ok"]
766
+ give fail(409, started["error"])
767
+ give respond(json_encode(started), "application/json", 202)
768
+
769
+ route "GET /w/:slug/api/chat/events" requires auth
770
+ private
771
+ let sid be get(query, "session", "")
772
+ let run_id be get(query, "run", "")
773
+ let info be webchat.run_info(run_id)
774
+ let valid be false
775
+ when info != nothing
776
+ set valid to info["session"] == sid and session.exists(sid)
777
+ let cursor be max(0, floor(number(get(query, "after", "0"))))
778
+ stream
779
+ when not valid
780
+ send {"kind": "run_missing", "data": sid} as "event"
781
+ otherwise
782
+ let deadline be now() + 900
783
+ let finished be false
784
+ while not finished and now() < deadline
785
+ let ev be webchat.event_at(run_id, cursor + 1)
786
+ when ev != nothing
787
+ set cursor to cursor + 1
788
+ send ev as "event"
789
+ when ev["kind"] == "done"
790
+ set finished to true
791
+ otherwise
792
+ let current be webchat.run_info(run_id)
793
+ let alive be when current == nothing then false otherwise current["active"]
794
+ when not alive
795
+ set finished to true
796
+ otherwise
797
+ sleep(0.1)
798
+
722
799
  route "POST /w/:slug/api/chat" requires auth
723
800
  private
724
801
  expect body {message: text}
725
- let b be json of request
726
- let message be b["message"]
727
- let sid be when contains(b, "session") then text(b["session"]) otherwise ""
728
- let want be when contains(b, "agent") then lower(text(b["agent"])) otherwise "build"
729
- let mode be when contains(b, "permission") then lower(text(b["permission"])) otherwise lower(env("LAMPSON_PERMISSION", "ask"))
730
- when mode != "ask" and mode != "yolo" and mode != "strict"
731
- set mode to "ask"
732
- let pname be when contains(b, "provider") then lower(text(b["provider"])) otherwise ""
733
- let pmodel be when contains(b, "model") then text(b["model"]) otherwise ""
734
802
  state_set("lampson:last_used", now())
803
+ let started be webchat.begin(json of request)
735
804
  stream
736
- -- el runtime (lib/runtime.syn) ya traza cada evento en .lampson/trace/<sid>.log: acá solo se reenvían por SSE
737
- task emit(kind, data, tag)
738
- send {"kind": kind, "data": data, "tag": tag} as "event"
739
- -- aprobación humana: la cola de lib/approvals.syn (id + token) — la UI responde por SSE/POST /api/approve,
740
- -- y si hay webhook/LAMPSON_PUBLIC_URL también llega un link al canal del usuario (aprobar desde el móvil)
741
- task ask_web(name, args, why)
742
- let id be approvals.open("chat", permission.describe_call(name, args), why, APPROVAL_TIMEOUT)
743
- send {"kind": "approval_request", "data": {"id": id, "name": name, "args": args, "why": why, "timeout": APPROVAL_TIMEOUT}} as "event"
744
- let t0 be now()
745
- let ok be approvals.wait(id, APPROVAL_TIMEOUT)
746
- send {"kind": "approval_result", "data": {"id": id, "approved": ok, "timeout": (not ok) and now() - t0 >= APPROVAL_TIMEOUT - 1}} as "event"
747
- give ok
748
- task on_start(info)
749
- set sid to info["session"]
750
- send {"kind": "session", "data": sid} as "event"
751
- send {"kind": "mode", "data": {"agent": info["agent"], "permission": info["mode"], "provider": info["provider"], "model": info["model"], "has_key": info["has_key"]}} as "event"
752
- -- worker es interno de delegate: por la API tampoco se elige como agente de sesión
753
- when not contains(runtime.names(), want)
754
- set want to "build"
755
- let sobre be {"to": want, "session": sid, "from": {"id": "", "name": "", "kind": "human"}, "text": message, "images": [], "channel": "web", "meta": {}}
756
- let hooks be {"mode": mode, "provider": pname, "model": pmodel, "ask_fn": ask_web, "on_event": emit, "on_start": on_start}
757
- when starts_with(trim(message), "!")
758
- -- comando del USUARIO: sin política de permisos, salida al contexto; el modelo no interviene
759
- let o be runtime.open(sobre, hooks)
760
- let cfg be o["ctx"]["cfg"]
761
- on_start({"session": o["session"], "agent": o["ctx"]["agent"], "thread": o["thread"], "mode": o["mode"], "provider": cfg["provider"], "model": cfg["model"], "has_key": cfg["has_key"]})
762
- when o["note"] != ""
763
- trace.event(sid, "inbox", o["note"], "")
764
- send {"kind": "inbox", "data": o["note"], "tag": ""} as "event"
765
- let cmd be trim(slice(trim(message), 1, length(trim(message))))
766
- let bash_tool be agents.registry_for("build")["bash"]
767
- send {"kind": "tool_call", "data": {"id": "user", "name": "bash", "args": {"command": cmd}}} as "event"
768
- let out be call_tool(bash_tool, {"command": cmd, "timeout": 600})
769
- send {"kind": "tool_result", "data": {"call": {"id": "user", "name": "bash", "args": {"command": cmd}}, "output": out}} as "event"
770
- let messages be append(o["messages"], {"role": "user", "content": "[The user ran this command in the shell themselves]\n$ " + cmd + "\n" + tools.truncate(out, 6000)})
771
- runtime.save(o, messages)
772
- send {"kind": "done", "data": {"text": "", "steps": 0, "usage": {"input": 0, "output": 0}, "stopped": "user_command", "session": sid}} as "event"
805
+ when not started["ok"]
806
+ send {"kind": "error", "data": started["error"]} as "event"
807
+ send {"kind": "done", "data": {"session": started["session"], "text": "", "steps": 0, "usage": {"input": 0, "output": 0}, "stopped": "busy"}} as "event"
773
808
  otherwise
774
- -- imágenes pegadas en la UI: [{media_type, data(base64)}] — el cliente ya las redujo; tope 5 MB por mensaje
775
- let images be []
776
- when contains(b, "images")
777
- let total be 0
778
- each im in b["images"]
779
- when contains(im, "data") and contains(im, "media_type")
780
- set total to total + length(im["data"])
781
- when total <= 5000000
782
- let entry be {"media_type": text(im["media_type"]), "data": text(im["data"])}
783
- when contains(im, "w") and contains(im, "h")
784
- set entry to {"media_type": text(im["media_type"]), "data": text(im["data"]), "w": floor(number(im["w"])), "h": floor(number(im["h"]))}
785
- set images to append(images, entry)
786
- set sobre["images"] to images
787
- let result be runtime.deliver(sobre, hooks)
788
- send {"kind": "done", "data": {"text": result["text"], "steps": result["steps"], "usage": result["usage"], "stopped": result["stopped"], "session": result["session"]}} as "event"
809
+ let run_id be started["run"]
810
+ let cursor be 0
811
+ let finished be false
812
+ let deadline be now() + 900
813
+ while not finished and now() < deadline
814
+ let ev be webchat.event_at(run_id, cursor + 1)
815
+ when ev != nothing
816
+ set cursor to cursor + 1
817
+ send ev as "event"
818
+ when ev["kind"] == "done"
819
+ set finished to true
820
+ otherwise
821
+ let current be webchat.run_info(run_id)
822
+ let alive be when current == nothing then false otherwise current["active"]
823
+ when not alive
824
+ set finished to true
825
+ otherwise
826
+ sleep(0.1)
789
827
 
790
828
  -- ---------- API /v1 para apps (lib/api.syn · spec/engine.md fase 2) ----------
791
829
  -- Sin `requires auth`: bajo el hub todo llega por loopback y check_client lo daría por bueno. La API exige SIEMPRE