lampson 0.2.10 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ // engine.js — Lampson como motor, en la UI: secciones «API» (keys de la API /v1 y del MCP) y «Canales» (Telegram,
2
+ // Chatwoot…) en el panel lateral, cada una con su vista browse del Panel. Backend: /api/keys* y /api/channels*
3
+ // (web.syn), sobre lib/apikeys.syn y lib/channels.syn — lo mismo que `lampson key …` y `lampson channel …`.
4
+ let keysData = { keys: [], api_url: '', mcp_url: '', public: false, agents: [] };
5
+ let channelsData = { channels: [], public: false };
6
+ const KEY_NEW = { id: '__new' };
7
+ // la key en claro existe solo en la respuesta de crearla: se guarda acá para mostrarla en su detalle mientras el panel
8
+ // siga abierto (al cerrar se olvida; no hay otra forma de volver a verla)
9
+ let justCreated = null;
10
+
11
+ // un 404 acá = la página es nueva pero el proceso del workspace arrancó con código anterior (no conoce estas rutas)
12
+ const STALE_MSG = 'este workspace corre una versión anterior de Lampson — reinicialo: lampson --hub restart';
13
+ async function fetchKeys() {
14
+ try {
15
+ const r = await fetch(BASE + '/api/keys');
16
+ if (r.status === 404) keysData = { keys: [], stale: true }; else if (r.ok) keysData = await r.json();
17
+ } catch (e) {}
18
+ keysData.keys = keysData.keys || [];
19
+ return keysData;
20
+ }
21
+ async function loadKeys() {
22
+ const d = await fetchKeys();
23
+ const box = $('#keysBox'); if (!box) return;
24
+ box.innerHTML = '';
25
+ $('#keysCount').textContent = d.keys.length || '';
26
+ if (d.stale) { const e = document.createElement('div'); e.className = 'p none'; e.style.cursor = 'default'; e.textContent = STALE_MSG; box.appendChild(e); return; }
27
+ for (const k of d.keys) {
28
+ const row = document.createElement('div'); row.className = 'p' + (k.last_used ? ' run' : '');
29
+ row.title = `agentes: ${k.agents.join(', ')}\nlímite: ${k.rate ? k.rate + '/min' : 'sin límite'}${k.callbacks.length ? '\ncallbacks: ' + k.callbacks.join(', ') : ''}\núltimo uso: ${k.last_used || 'nunca'}`;
30
+ row.innerHTML = `<span class="st"></span><span class="nm">${esc(k.name || k.id)}</span><span class="cm">${esc(k.agents.join(', '))} · ${k.rate ? k.rate + '/min' : '∞'}</span>`;
31
+ row.onclick = () => openKeys(k.id);
32
+ box.appendChild(row);
33
+ }
34
+ const add = document.createElement('div'); add.className = 'p';
35
+ add.innerHTML = `<span class="nm" style="color:var(--accent)">+ crear una API key…</span>`;
36
+ add.title = 'para que una app, un bot o un agente use los agentes de este workspace por HTTP o MCP';
37
+ add.onclick = () => openKeys('__new');
38
+ box.appendChild(add);
39
+ if (Panel.is('keys')) await Panel.refresh();
40
+ }
41
+ function keyForm() {
42
+ const opts = (keysData.agents || []).map(a => `<label class="chk"><input type="checkbox" value="${esc(a)}"> ${esc(a)}</label>`).join(' ');
43
+ return `<div class="dhead"><span class="nm serif">Crear una API key</span></div><div class="dform">
44
+ <p class="lead">Una key deja que una app, un bot o <b>otro agente</b> use agentes de este workspace: por HTTP (<code>${esc(keysData.api_url)}</code>) o como herramienta MCP (<code>${esc(keysData.mcp_url)}</code>). Se muestra <b>una sola vez</b>.</p>
45
+ <label>nombre <input name="name" spellcheck="false" autocomplete="off" placeholder="bot de whatsapp"></label>
46
+ <div class="lf"><span class="lk">agentes que puede usar</span><div>${opts}</div><span class="ds">ninguno marcado = todos</span></div>
47
+ <label>pedidos por minuto <input name="rate" type="number" min="0" placeholder="120 (0 = sin límite)"></label>
48
+ <label>callbacks solo a <input name="callbacks" spellcheck="false" autocomplete="off" placeholder="opcional: https://hooks.mi-app.com/ · separá con espacios"></label>
49
+ <div class="pfoot"><button class="primary" data-go>Crear</button><span class="derr"></span></div>
50
+ </div>`;
51
+ }
52
+ function openKeys(selectId) {
53
+ Panel.open({
54
+ id: 'keys', eyebrow: 'api', title: 'API keys', onClose: () => { justCreated = null; }, sub: keysData.public ? 'URL pública configurada' : 'solo desde esta PC (sin URL pública)', layout: 'browse', select: selectId || null,
55
+ browse: {
56
+ placeholder: 'buscar key o agente…', listWidth: '260px', key: k => k.id,
57
+ load: async (q) => { const d = await fetchKeys(); const list = d.keys.filter(k => !q || (k.name + ' ' + k.id + ' ' + k.agents.join(' ')).toLowerCase().includes(q.toLowerCase())); return q ? list : [...list, KEY_NEW]; },
58
+ render: (k) => k === KEY_NEW ? `<span class="dot">+</span><div><div class="nm" style="color:var(--accent);font-weight:400">crear una API key…</div><div class="meta">para apps, bots y agentes</div></div>`
59
+ : `<span class="dot">${k.last_used ? '●' : '○'}</span><div><div class="nm">${esc(k.name || k.id)}</div><div class="meta">${esc(k.agents.join(', '))} · ${k.rate ? k.rate + '/min' : 'sin límite'}</div></div>`,
60
+ count: (rows) => { const n = rows.filter(r => r !== KEY_NEW).length; return `${n} key${n === 1 ? '' : 's'}`; },
61
+ emptyHtml: 'nada coincide',
62
+ detail: (k) => k === KEY_NEW ? keyForm() : `<div class="dhead"><span class="nm">${esc(k.name || k.id)}</span><span class="meta">${esc(k.id)}</span></div>
63
+ <div class="ddesc">Agentes: ${k.agents.map(a => `<code>${esc(a)}</code>`).join(' ')}</div>
64
+ <div class="dcap">límite: ${k.rate ? k.rate + ' pedidos por minuto' : 'sin límite'}${k.callbacks.length ? ' · callbacks solo a ' + k.callbacks.map(esc).join(', ') : ' · callbacks a cualquier URL'}</div>
65
+ ${justCreated && justCreated.id === k.id ? `<div class="dnote"><b>Guardala ahora: no se vuelve a mostrar.</b></div><pre class="out">${esc(justCreated.key)}\n\nAPI: ${esc(keysData.api_url)}\nMCP: ${esc(keysData.mcp_url)}\nHeader: Authorization: Bearer ${esc(justCreated.key)}</pre>` : ''}
66
+ <div class="dnote">API: <code>${esc(keysData.api_url)}</code><br>MCP: <code>${esc(keysData.mcp_url)}</code><br>creada ${esc(k.created)} · último uso ${esc(k.last_used || 'nunca')}</div>
67
+ <div class="dfoot"><span>la key en claro no se guarda: si se perdió, creá otra</span><span class="del">revocar</span></div><div class="derr"></div>`,
68
+ wire: (k, box) => {
69
+ const err = (t) => { const e = box.querySelector('.derr'); if (e) e.textContent = t || ''; };
70
+ if (k === KEY_NEW) {
71
+ const f = n => box.querySelector(`[name="${n}"]`);
72
+ box.querySelector('[data-go]').onclick = async () => {
73
+ const agents = [...box.querySelectorAll('.chk input:checked')].map(i => i.value);
74
+ const callbacks = f('callbacks').value.trim().split(/\s+/).filter(Boolean);
75
+ err('creando…');
76
+ const r = await api(BASE + '/api/keys/add', { name: f('name').value.trim(), agents, rate: f('rate').value, callbacks });
77
+ if (!r.ok) { err(r.data.error || ('error ' + r.status)); return; }
78
+ err('');
79
+ justCreated = { id: r.data.id, key: r.data.key };
80
+ await loadKeys();
81
+ Panel.selectKey(r.data.id);
82
+ };
83
+ f('name').focus();
84
+ return;
85
+ }
86
+ const del = box.querySelector('.dfoot .del');
87
+ del.onclick = () => inlineConfirm(del, `¿revocar ${k.name || k.id}? Las apps que la usan dejan de entrar`, async () => {
88
+ const r = await api(BASE + '/api/keys/remove', { id: k.id }); if (!r.ok) { err(r.data.error || 'error'); return; } loadKeys();
89
+ });
90
+ }
91
+ }
92
+ });
93
+ }
94
+
95
+ async function fetchChannels() {
96
+ try {
97
+ const r = await fetch(BASE + '/api/channels');
98
+ if (r.status === 404) channelsData = { channels: [], stale: true }; else if (r.ok) channelsData = await r.json();
99
+ } catch (e) {}
100
+ channelsData.channels = channelsData.channels || [];
101
+ return channelsData;
102
+ }
103
+ async function loadChannels() {
104
+ const d = await fetchChannels();
105
+ const box = $('#channelsBox'); if (!box) return;
106
+ box.innerHTML = '';
107
+ const on = d.channels.filter(c => c.enabled).length;
108
+ $('#channelsCount').textContent = d.channels.length ? (on ? `${on} ● · ${d.channels.length}` : `${d.channels.length}`) : '';
109
+ if (!d.channels.length) { const e = document.createElement('div'); e.className = 'p none'; e.style.cursor = 'default'; e.textContent = d.stale ? STALE_MSG : 'sin canales instalados'; box.appendChild(e); }
110
+ for (const c of d.channels) {
111
+ const row = document.createElement('div'); row.className = 'p' + (c.enabled ? ' run' : '');
112
+ row.title = c.description || '';
113
+ row.innerHTML = `<span class="st"></span><span class="nm">${esc(c.name)}</span><span class="cm">${c.error ? 'roto' : (c.enabled ? esc(c.agent) + ' · ' + (c.mode === 'poll' ? 'sin URL pública' : 'webhook') : 'apagado')}</span>`;
114
+ row.onclick = () => openChannels(c.name);
115
+ box.appendChild(row);
116
+ }
117
+ if (Panel.is('channels')) await Panel.refresh();
118
+ }
119
+ function openChannels(selectName) {
120
+ Panel.open({
121
+ id: 'channels', eyebrow: 'canales', title: 'Canales', sub: channelsData.public ? 'URL pública configurada' : 'sin URL pública: los que lo permiten piden los mensajes solos', layout: 'browse', select: selectName || null,
122
+ browse: {
123
+ placeholder: 'buscar canal…', listWidth: '240px', key: c => c.name,
124
+ load: async (q) => { const d = await fetchChannels(); return d.channels.filter(c => !q || (c.name + ' ' + (c.description || '')).toLowerCase().includes(q.toLowerCase())); },
125
+ render: (c) => `<span class="dot">${c.error ? '!' : (c.enabled ? '●' : '○')}</span><div><div class="nm">${esc(c.name)}</div><div class="meta">${c.enabled ? esc(c.agent) + ' · ' + (c.mode === 'poll' ? 'sin URL pública' : 'webhook') : 'apagado'}</div></div>`,
126
+ count: (rows) => `${rows.length} canal${rows.length === 1 ? '' : 'es'}`,
127
+ emptyHtml: 'sin canales instalados',
128
+ detail: (c) => `<div class="dhead"><span class="nm">${esc(c.name)}</span><span class="meta">${esc(c.scope)}</span><label class="sw ${c.enabled ? 'on' : ''}" title="${c.error ? 'no se puede encender: está roto' : (c.enabled ? 'apagar' : 'encender')}"><input type="checkbox" ${c.enabled ? 'checked' : ''} ${c.error ? 'disabled' : ''}>${c.enabled ? 'encendido' : 'apagado'}</label></div>`
129
+ + (c.description ? `<div class="ddesc">${esc(c.description)}</div>` : '')
130
+ + (c.error ? `<div class="dcap err">roto: ${esc(c.error)}</div>` : `<div class="dcap">agente: <code>${esc(c.agent)}</code> · modo: ${c.mode === 'poll' ? 'sin URL pública (Lampson le pide los mensajes a la plataforma)' : 'webhook'}</div>`)
131
+ + `<div class="dnote">${c.mode === 'poll' ? 'No hace falta URL pública: el workspace pide los mensajes mientras esté encendido.' : `URL del webhook: <code>${esc(c.webhook_url)}</code>${c.public ? '' : '<br><b>Sin URL pública</b>: la plataforma no llega a esta PC.' + (c.poll ? ' «Configurar» pasa este canal a modo sin URL pública.' : ' Usá <code>lampson --domain …</code> o un túnel.')}`}<br>El agente que atiende se cambia con <code>LAMPSON_CHANNEL_${esc(c.name.toUpperCase().replace(/-/g, '_'))}_AGENT</code> en el <code>.env</code>.</div>`
132
+ + (c.enabled ? `<div class="go"><button class="primary" data-setup>configurar</button><span class="st"></span></div><pre class="out" data-out style="display:none"></pre>` : '')
133
+ + `<div class="lf" style="margin-top:16px"><span class="lk">últimos eventos</span><pre class="out">${c.log.length ? esc(c.log.join('\n')) : 'nada todavía'}</pre></div><div class="derr"></div>`,
134
+ wire: (c, box) => {
135
+ const err = (t) => { const e = box.querySelector('.derr'); if (e) e.textContent = t || ''; };
136
+ const sw = box.querySelector('.sw input');
137
+ if (sw) sw.onchange = async () => { const r = await api(BASE + '/api/channels/toggle', { name: c.name, on: sw.checked }); if (!r.ok) { err(r.data.error || 'error'); sw.checked = !sw.checked; return; } loadChannels(); };
138
+ const su = box.querySelector('[data-setup]');
139
+ if (su) su.onclick = async () => {
140
+ const st = box.querySelector('.go .st'); st.textContent = 'configurando…'; su.disabled = true;
141
+ const r = await api(BASE + '/api/channels/setup', { name: c.name });
142
+ su.disabled = false; st.textContent = r.ok && r.data.code === 0 ? 'listo' : 'falló';
143
+ const out = box.querySelector('[data-out]'); out.style.display = ''; out.textContent = r.ok ? r.data.out : (r.data.error || 'error ' + r.status);
144
+ loadChannels();
145
+ };
146
+ }
147
+ }
148
+ });
149
+ }
@@ -2,6 +2,8 @@
2
2
  // títulos y contenido (GET /api/sessions/search?q=) y una previsualización de la conversación; traza.
3
3
  function forgetSession(id) { if (id === session) { session = ''; localStorage.removeItem('lampson.session'); log.innerHTML = ''; showPane('log'); empty(); } }
4
4
  async function deleteSession(id) { await api(BASE + '/api/sessions/delete', { id }); forgetSession(id); loadSessions(); }
5
+ // etiqueta corta de una sesión: la hora HHMMSS de su id (YYYYMMDD-HHMMSS, o YYYYMMDD-HHMMSS-NNNN las del runtime)
6
+ function sessionLabel(id) { const m = /^\d{8}-(\d{6})/.exec(id); return m ? m[1] : id.slice(-6); }
5
7
  async function loadSessions() {
6
8
  let r; try { r = await (await fetch(BASE + '/api/sessions')).json(); } catch (e) { return; }
7
9
  const box = $('#sessions'); box.innerHTML = '';
@@ -9,7 +11,7 @@ async function loadSessions() {
9
11
  if (!r.sessions.length) { box.innerHTML = '<div class="s none">todavía ninguna</div>'; return; }
10
12
  const shown = r.sessions.slice(0, 4);
11
13
  for (const s of shown) {
12
- const d = document.createElement('div'); d.className = 's' + (s.id === session ? ' active' : ''); d.innerHTML = '<span class="id">' + esc(s.id.slice(-6)) + '</span><span class="title">' + esc(s.title || '') + '</span><span class="del tr" title="traza: qué hizo el agente en esta sesión (pasos, tools, tiempos, tokens)">≡</span><span class="del" title="borrar esta sesión">✕</span>'; d.title = s.id; d.onclick = () => openSession(s.id);
14
+ const d = document.createElement('div'); d.className = 's' + (s.id === session ? ' active' : ''); d.innerHTML = '<span class="id">' + esc(sessionLabel(s.id)) + '</span><span class="title">' + esc(s.title || '') + '</span><span class="del tr" title="traza: qué hizo el agente en esta sesión (pasos, tools, tiempos, tokens)">≡</span><span class="del" title="borrar esta sesión">✕</span>'; d.title = s.id; d.onclick = () => openSession(s.id);
13
15
  d.querySelector('.tr').onclick = (ev) => { ev.stopPropagation(); openTrace(s.id); };
14
16
  d.querySelector('.del:not(.tr)').onclick = (ev) => { ev.stopPropagation(); inlineConfirm(d.querySelector('.del:not(.tr)'), '¿borrar?', () => deleteSession(s.id)); };
15
17
  box.appendChild(d);
package/run.syn ADDED
@@ -0,0 +1,394 @@
1
+ -- run.syn — Lampson sin interfaz: un mensaje entra, el agente trabaja, la respuesta sale (spec/engine.md, fase 1)
2
+ --
3
+ -- lampson run "resumí los cambios de hoy" -- texto final por stdout
4
+ -- echo "hola" | lampson run --agent soporte --thread whatsapp:+54911… --json
5
+ --
6
+ -- Corre como chat.syn: cwd = .lampson/ws/<slug> con la junction `workspace` (los launchers lo preparan).
7
+ -- Entrada por entorno (los launchers la arman desde los flags):
8
+ -- LAMPSON_MESSAGE el mensaje; vacío → se lee stdin hasta EOF
9
+ -- LAMPSON_AGENT el agente (integrado o workspace/.lampson/agents/<id>.agent.json); default build
10
+ -- LAMPSON_THREAD identidad externa de la conversación (cliente, canal, tarea): misma → misma sesión
11
+ -- LAMPSON_SESSION o el id de una sesión ya existente
12
+ -- LAMPSON_RUN_JSON=1 eventos JSONL por stdout (uno por línea) y al final {"kind":"done",…}
13
+ -- LAMPSON_RUN_PERMISSION ask|strict|yolo; vacío → el del agente, y si no dice → strict
14
+ -- Sin humano delante: lo que pida aprobación se DENIEGA (no hay ask_fn); el modelo lo ve y lo informa.
15
+ -- Código de salida: 0 ok · 1 el turno terminó en error · 2 uso inválido (agente inexistente, mensaje vacío).
16
+
17
+ intent: "Headless Lampson: deliver one message to an agent and print its answer (or the event stream as JSONL)"
18
+
19
+ require net
20
+ require time
21
+ require stdin
22
+ require exec
23
+ require random
24
+ require env("LAMPSON_*")
25
+ require env("OS")
26
+ require secret("LAMPSON_*")
27
+ require judge
28
+ require file("workspace")
29
+ require file("workspace/*")
30
+ require file.read("skills")
31
+ require file.read("skills/*")
32
+ require file.read("plugins")
33
+ require file.read("plugins/*")
34
+ require file.read("agents")
35
+ require file.read("agents/*")
36
+ require file("memory")
37
+ require file("memory/*")
38
+ require file(".lampson")
39
+ require file(".lampson/*")
40
+
41
+ use "./lib/runtime.syn" as runtime
42
+ use "./lib/agents.syn" as agents
43
+ use "./lib/mcp.syn" as mcp
44
+ use "./lib/apikeys.syn" as apikeys
45
+ use "./lib/mcp_server.syn" as mcp_server
46
+ use "./lib/approvals.syn" as approvals
47
+ use "./lib/plugins.syn" as plugins
48
+ use "./lib/channels.syn" as channels
49
+
50
+ -- `lampson key add|list|remove`: API keys de la API /v1 de este workspace (lib/apikeys.syn, lib/api.syn)
51
+ -- LAMPSON_KEY_CMD=add [LAMPSON_KEY_NAME] [LAMPSON_KEY_AGENTS=tienda,soporte] [LAMPSON_KEY_RATE=60]
52
+ -- [LAMPSON_KEY_CALLBACKS=https://a/,https://b/] · list · remove LAMPSON_KEY_ID
53
+ let key_cmd be env("LAMPSON_KEY_CMD", "")
54
+ when key_cmd != ""
55
+ let ws_path be "/w/" + env("LAMPSON_WS", "<slug>") + "/v1"
56
+ -- la URL pública de este lampson (--domain, túnel o LAMPSON_PUBLIC_URL), si hay: la que se pega en otra app o agente
57
+ let pub be approvals.public_url()
58
+ let api_base be when pub != "" then pub + ws_path otherwise "http://127.0.0.1:8080" + ws_path
59
+ when key_cmd == "add"
60
+ let ag be where(apply((x) => lower(trim(x)), split(env("LAMPSON_KEY_AGENTS", ""), ",")), (x) => x != "")
61
+ each a in ag
62
+ when a != "*" and not contains(runtime.names(), a)
63
+ print("lampson key: no agent named '" + a + "' · available: " + join(runtime.names(), ", "))
64
+ exit(2)
65
+ let rate_s be trim(env("LAMPSON_KEY_RATE", ""))
66
+ let cbs be where(apply((x) => trim(x), split(env("LAMPSON_KEY_CALLBACKS", ""), ",")), (x) => x != "")
67
+ each cb in cbs
68
+ when not (starts_with(cb, "https://") or starts_with(cb, "http://"))
69
+ print("lampson key: --callback must be an http(s) URL prefix, got '" + cb + "'")
70
+ exit(2)
71
+ let kopts be {"callbacks": cbs}
72
+ when rate_s != ""
73
+ when not matches(rate_s, "[0-9]{1,6}")
74
+ print("lampson key: --rate must be a number of requests per minute (0 = no limit)")
75
+ exit(2)
76
+ set kopts["rate"] to int(rate_s)
77
+ let k be apikeys.create_with(env("LAMPSON_KEY_NAME", ""), ag, kopts)
78
+ print("API key creada (" + k["id"] + ") para " + (when contains(k["agents"], "*") then "todos los agentes" otherwise join(k["agents"], ", ")) + " · " + (when k["rate"] == 0 then "sin límite" otherwise text(k["rate"]) + " pedidos/min") + (when length(k["callbacks"]) > 0 then " · callbacks solo a " + join(k["callbacks"], ", ") otherwise "") + ". Guardala ahora: no se vuelve a mostrar.")
79
+ print("")
80
+ print(" " + k["key"])
81
+ print("")
82
+ print(" API (apps, bots): " + api_base + "/messages")
83
+ print(" MCP (otros agentes): " + api_base + "/mcp con el header Authorization: Bearer <la key>")
84
+ when pub == ""
85
+ print(" (solo desde esta PC: para usarla desde afuera, `lampson --domain …` o un túnel; ver lampson.org/docs/phone)")
86
+ print("")
87
+ print(" curl -X POST " + api_base + "/messages -H \"Authorization: Bearer " + k["key"] + "\" -H \"Content-Type: application/json\" -d '{\"to\": \"" + (when contains(k["agents"], "*") then runtime.default_agent() otherwise k["agents"][0]) + "\", \"thread\": \"cliente-1\", \"text\": \"hola\"}'")
88
+ otherwise when key_cmd == "list"
89
+ let ks be apikeys.list()
90
+ when length(ks) == 0
91
+ print("sin API keys en este workspace (lampson key add [--agent ID] [--name NOMBRE])")
92
+ each k in ks
93
+ print(" " + k["id"] + " " + (when k["name"] == "" then "(sin nombre)" otherwise k["name"]) + " agentes: " + join(k["agents"], ", ") + " " + (when k["rate"] == 0 then "sin límite" otherwise text(k["rate"]) + "/min") + (when length(k["callbacks"]) > 0 then " callbacks: " + join(k["callbacks"], ", ") otherwise "") + " creada " + k["created"] + " último uso " + (when k["last_used"] == nothing then "nunca" otherwise text(k["last_used"])))
94
+ print(" API: " + api_base + "/messages · MCP: " + api_base + "/mcp")
95
+ otherwise when key_cmd == "remove"
96
+ let kid be env("LAMPSON_KEY_ID", "")
97
+ when apikeys.remove(kid)
98
+ print("API key " + kid + " revocada")
99
+ otherwise
100
+ print("lampson key: no existe la key '" + kid + "' (lampson key list)")
101
+ exit(2)
102
+ otherwise
103
+ print("uso: lampson key add [--agent ID[,ID]] [--name NOMBRE] · lampson key list · lampson key remove <id>")
104
+ exit(2)
105
+ exit(0)
106
+
107
+ -- `lampson channel list|on|off|setup [canal]`: los canales (plugins con "channel", lib/channels.syn)
108
+ let ch_cmd be env("LAMPSON_CHANNEL_CMD", "")
109
+ when ch_cmd != ""
110
+ let ch_name be lower(env("LAMPSON_CHANNEL_NAME", ""))
111
+ let pub_ch be approvals.public_url()
112
+ let slug be env("LAMPSON_WS", "")
113
+ task hook_url(n)
114
+ give channels.webhook_url(n, pub_ch, slug)
115
+ let chs be where(plugins.all(), (l) => l["channel"] != nothing)
116
+ when ch_cmd == "list"
117
+ when length(chs) == 0
118
+ print("no hay canales instalados (un canal es un plugin con \"channel\" en su plugin.json)")
119
+ each l in chs
120
+ let ag be when l["error"] == nothing then channels.agent_for(l["name"], l, {}) otherwise "?"
121
+ let md be channels.mode_of(l["name"])
122
+ print(" " + (when l["enabled"] then "● " otherwise "○ ") + l["name"] + " " + (when l["error"] != nothing then "roto: " + text(l["error"]) otherwise "agente: " + ag + " " + (when md == "poll" then "modo: sin URL pública (poll)" otherwise "webhook: " + hook_url(l["name"]))))
123
+ when pub_ch == ""
124
+ print(" (sin URL pública: las plataformas no llegan a esta PC. `lampson --domain …` o un túnel; ver lampson.org/docs/phone)")
125
+ exit(0)
126
+ let found be where(chs, (l) => l["name"] == ch_name)
127
+ when length(found) == 0
128
+ print("lampson channel: no hay un canal '" + ch_name + "' · instalados: " + join(apply((l) => l["name"], chs), ", "))
129
+ exit(2)
130
+ let l be found[0]
131
+ when ch_cmd == "on" or ch_cmd == "off"
132
+ plugins.set_enabled(ch_name, ch_cmd == "on")
133
+ print("canal " + ch_name + (when ch_cmd == "on" then " encendido · webhook: " + hook_url(ch_name) otherwise " apagado"))
134
+ exit(0)
135
+ when ch_cmd == "setup"
136
+ when not l["enabled"]
137
+ print("lampson channel: el canal " + ch_name + " está apagado — `lampson channel on " + ch_name + "` primero")
138
+ exit(2)
139
+ let su be channels.setup_channel(ch_name, pub_ch, slug)
140
+ print(su["out"])
141
+ exit(su["code"])
142
+ print("uso: lampson channel list · channel on|off <canal> · channel setup <canal>")
143
+ exit(2)
144
+
145
+ -- `lampson mcp serve`: Lampson como servidor MCP por stdio (lib/mcp_server.syn); stdout queda SOLO para JSON-RPC
146
+ when env("LAMPSON_MCP_SERVE", "") == "1"
147
+ let offered be mcp_server.offered()
148
+ when length(offered) == 0
149
+ print(json_encode({"jsonrpc": "2.0", "id": nothing, "error": {"code": -32603, "message": "no agents match LAMPSON_MCP_AGENTS"}}))
150
+ exit(2)
151
+ share {"id": text(now())} as "lampson:run"
152
+ share {"kind": "mcp"} as "lampson:ui"
153
+ -- servers MCP propios de Lampson solo si algún agente ofrecido puede usarlos
154
+ let uses_mcp be false
155
+ each n in offered
156
+ let ts be runtime.get(n)["tools"]
157
+ when contains(ts, "mcp") or length(where(ts, (t) => starts_with(t, "mcp_"))) > 0
158
+ set uses_mcp to true
159
+ when uses_mcp
160
+ mcp.start_all(8)
161
+ mcp_server.serve()
162
+ exit(0)
163
+
164
+ -- Subagente en background: `agent Child` (lib/agents.syn) solo llama tasks TOP-LEVEL del programa de entrada
165
+ task lampson_subagent(spec_json)
166
+ give agents.run_child_json(spec_json)
167
+
168
+ -- `lampson run --stdio`: MODO LOCAL (lo usa el SDK). Un proceso abierto, un pedido JSON por línea en stdin:
169
+ -- {"id": "r1", "op": "ask", "to"?, "thread"?, "session"?, "text", "images"?, "meta"?, "mode"?: "strict"|"yolo"}
170
+ -- {"id": "r2", "op": "agents"} · {"id": "r3", "op": "ping"}
171
+ -- y por stdout, una línea JSON por evento con ese id: los mismos que `--json` (session, assistant, tool_call…) y
172
+ -- {"id", "kind": "done", "data": {agent, thread, session, text, steps, usage, stopped}} al terminar cada ask. Al
173
+ -- arrancar, {"kind": "ready", "data": {"agents": […], "protocol": 2}}.
174
+ -- CONCURRENCIA (protocolo 2): cada ask corre en su propio agente de Synsema; conversaciones distintas van en
175
+ -- paralelo, dos asks de la MISMA conversación (agente + thread) esperan en fila. Un agente que imprime sale con
176
+ -- prefijo "[Agente_N]" (rompería el JSON): por eso los trabajos publican en el bus y SOLO el hilo principal escribe.
177
+ -- Sin humano: lo que pida aprobación se deniega; "mode" lo puede fijar quien llama (es su programa, en su máquina).
178
+ task stdio_out(m)
179
+ print(json_encode(m))
180
+ flush()
181
+
182
+ -- un ask, dentro de un agente StdioJob (los agentes solo ven tasks TOP-LEVEL del entry)
183
+ task lampson_stdio_job(req_json)
184
+ let req be json_decode(req_json)
185
+ let rid be req["id"]
186
+ let agent_id be req["to"]
187
+ let th be req["thread"]
188
+ task out(m)
189
+ bus_publish("stdio.out", m)
190
+ task on_event(kind, data, tag)
191
+ when kind != "busy" and kind != "idle"
192
+ out({"id": rid, "kind": kind, "data": data, "tag": tag, "agent": agent_id, "thread": th})
193
+ task on_start(info)
194
+ set th to info["thread"]
195
+ out({"id": rid, "kind": "session", "data": info, "tag": "", "agent": info["agent"], "thread": info["thread"]})
196
+ let r be nothing
197
+ try
198
+ set r to runtime.deliver(req["sobre"], {"mode": req["mode"], "ask_fn": nothing, "on_event": on_event, "on_start": on_start})
199
+ recover err
200
+ set r to {"agent": agent_id, "thread": th, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
201
+ out({"id": rid, "kind": "done", "data": r, "tag": "", "agent": r["agent"], "thread": r["thread"]})
202
+ bus_publish("stdio.done", {"key": req["key"]})
203
+ give true
204
+
205
+ agent StdioReader
206
+ require stdin
207
+ let l be read_line("")
208
+ while l != nothing
209
+ bus_publish("stdio.line", l)
210
+ set l to read_line("")
211
+ bus_publish("stdio.eof", true)
212
+
213
+ agent StdioJob
214
+ require net
215
+ require exec
216
+ require time
217
+ require random
218
+ require env("LAMPSON_*")
219
+ require env("OS")
220
+ require secret("LAMPSON_*")
221
+ require file("workspace")
222
+ require file("workspace/*")
223
+ require file.read("skills")
224
+ require file.read("skills/*")
225
+ require file.read("plugins")
226
+ require file.read("plugins/*")
227
+ require file.read("agents")
228
+ require file.read("agents/*")
229
+ require file("memory")
230
+ require file("memory/*")
231
+ require file(".lampson")
232
+ require file(".lampson/*")
233
+ lampson_stdio_job(spec_json)
234
+
235
+ -- un pedido ask ya leído → {ok, job, error}: el spec del trabajo (o por qué no)
236
+ task stdio_ask(req, rid)
237
+ let agent_id be lower(text(when contains(req, "to") and req["to"] != nothing and text(req["to"]) != "" then req["to"] otherwise runtime.default_agent()))
238
+ let th be when contains(req, "thread") and req["thread"] != nothing then text(req["thread"]) otherwise ""
239
+ let msg be when contains(req, "text") and req["text"] != nothing then text(req["text"]) otherwise ""
240
+ let spec be runtime.get(agent_id)
241
+ let fail_r be {"agent": agent_id, "thread": th, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": ""}
242
+ when spec == nothing
243
+ set fail_r["stopped"] to "error: no agent named '" + agent_id + "' · available: " + join(runtime.names(), ", ")
244
+ give {"ok": false, "done": fail_r}
245
+ when trim(msg) == ""
246
+ set fail_r["stopped"] to "error: text is required"
247
+ give {"ok": false, "done": fail_r}
248
+ let want be when contains(req, "mode") and req["mode"] != nothing then lower(text(req["mode"])) otherwise ""
249
+ let mode be when want == "strict" or want == "yolo" then want otherwise (when spec["permission"] == "" then "strict" otherwise "")
250
+ let ss be when contains(req, "session") and req["session"] != nothing then text(req["session"]) otherwise ""
251
+ -- la fila es por conversación: (agente, thread), o la sesión; sin ninguno, el pedido solo (va en paralelo)
252
+ let key be when th != "" then agent_id + "\n" + th otherwise (when ss != "" then agent_id + "\nsession:" + ss otherwise "req:" + rid)
253
+ let sobre be {"to": agent_id, "thread": th, "session": ss, "from": {"id": "", "name": "", "kind": "human"}, "text": msg, "images": when contains(req, "images") and type_of(req["images"]) == "list" then req["images"] otherwise [], "channel": "sdk", "meta": when contains(req, "meta") and type_of(req["meta"]) == "map" then req["meta"] otherwise {}}
254
+ give {"ok": true, "key": key, "job": {"id": rid, "to": agent_id, "thread": th, "mode": mode, "key": key, "sobre": sobre}}
255
+
256
+ when env("LAMPSON_RUN_STDIO", "") == "1"
257
+ share {"id": text(now())} as "lampson:run"
258
+ share {"kind": "sdk"} as "lampson:ui"
259
+ let all_names be runtime.names()
260
+ let any_mcp be false
261
+ each n in all_names
262
+ let ts be runtime.get(n)["tools"]
263
+ when contains(ts, "mcp") or length(where(ts, (t) => starts_with(t, "mcp_"))) > 0
264
+ set any_mcp to true
265
+ when any_mcp
266
+ mcp.start_all(8)
267
+ let sub be bus_subscribe(["stdio.line", "stdio.out", "stdio.done", "stdio.eof"], {"max_queue": 100000, "on_full": "error"})
268
+ spawn StdioReader
269
+ stdio_out({"kind": "ready", "data": {"agents": all_names, "protocol": 2}})
270
+ let busy be {}
271
+ let waiting be {}
272
+ let running be 0
273
+ let eof be false
274
+ let open be true
275
+ while open
276
+ let ev be bus_recv(sub, 3600)
277
+ when ev == nothing
278
+ set open to running > 0 or not eof
279
+ otherwise when ev["topic"] == "stdio.out"
280
+ stdio_out(ev["data"])
281
+ otherwise when ev["topic"] == "stdio.done"
282
+ let k be ev["data"]["key"]
283
+ set running to running - 1
284
+ let q be when contains(waiting, k) then waiting[k] otherwise []
285
+ when length(q) > 0
286
+ set waiting[k] to slice(q, 1, length(q))
287
+ set running to running + 1
288
+ spawn StdioJob with spec_json = json_encode(q[0])
289
+ otherwise
290
+ set busy[k] to false
291
+ when eof and running == 0
292
+ set open to false
293
+ otherwise when ev["topic"] == "stdio.eof"
294
+ set eof to true
295
+ when running == 0
296
+ set open to false
297
+ otherwise when ev["topic"] == "stdio.line"
298
+ let line be ev["data"]
299
+ when trim(line) != ""
300
+ let req be nothing
301
+ try
302
+ set req to json_decode(line)
303
+ recover err
304
+ set req to nothing
305
+ when req == nothing or type_of(req) != "map"
306
+ stdio_out({"id": "", "kind": "error", "data": "each line must be a JSON object"})
307
+ otherwise
308
+ let rid be when contains(req, "id") and req["id"] != nothing then text(req["id"]) otherwise ""
309
+ let op be when contains(req, "op") and req["op"] != nothing then lower(text(req["op"])) otherwise "ask"
310
+ when op == "ping"
311
+ stdio_out({"id": rid, "kind": "pong"})
312
+ otherwise when op == "agents"
313
+ stdio_out({"id": rid, "kind": "agents", "data": apply((n) => {"id": n, "description": runtime.get(n)["description"]}, runtime.names())})
314
+ otherwise when op == "ask"
315
+ let a be stdio_ask(req, rid)
316
+ when not a["ok"]
317
+ stdio_out({"id": rid, "kind": "done", "data": a["done"], "tag": "", "agent": a["done"]["agent"], "thread": a["done"]["thread"]})
318
+ otherwise when contains(busy, a["key"]) and busy[a["key"]]
319
+ let wq be when contains(waiting, a["key"]) then waiting[a["key"]] otherwise []
320
+ set waiting[a["key"]] to append(wq, a["job"])
321
+ otherwise
322
+ set busy[a["key"]] to true
323
+ set running to running + 1
324
+ spawn StdioJob with spec_json = json_encode(a["job"])
325
+ otherwise
326
+ stdio_out({"id": rid, "kind": "error", "data": "unknown op '" + op + "' (ask, agents, ping)"})
327
+ exit(0)
328
+
329
+ let json_out be env("LAMPSON_RUN_JSON", "") == "1"
330
+ let agent_id be runtime.default_agent()
331
+ let thread be env("LAMPSON_THREAD", "")
332
+
333
+ task fail_usage(msg)
334
+ when json_out
335
+ print(json_encode({"kind": "error", "data": msg, "tag": "", "agent": agent_id, "thread": thread}))
336
+ otherwise
337
+ print("lampson run: " + msg)
338
+ exit(2)
339
+
340
+ let spec be runtime.get(agent_id)
341
+ when spec == nothing
342
+ fail_usage("no agent named '" + agent_id + "' · available: " + join(runtime.names(), ", "))
343
+
344
+ let message be env("LAMPSON_MESSAGE", "")
345
+ when message == ""
346
+ let lines be []
347
+ let l be read_line("")
348
+ while l != nothing
349
+ set lines to append(lines, l)
350
+ set l to read_line("")
351
+ set message to join(lines, "\n")
352
+ when trim(message) == ""
353
+ fail_usage("empty message (pass it as an argument or on stdin)")
354
+
355
+ let mode be lower(env("LAMPSON_RUN_PERMISSION", ""))
356
+ when mode == "" and spec["permission"] == ""
357
+ set mode to "strict"
358
+
359
+ -- servers MCP solo si el agente puede usarlos (arrancarlos cuesta hasta unos segundos)
360
+ when contains(spec["tools"], "mcp") or length(where(spec["tools"], (t) => starts_with(t, "mcp_"))) > 0
361
+ mcp.start_all(8)
362
+
363
+ share {"id": text(now())} as "lampson:run"
364
+ share {"kind": "cli"} as "lampson:ui"
365
+
366
+ task emit_json(kind, data, tag)
367
+ when kind != "busy" and kind != "idle"
368
+ print(json_encode({"kind": kind, "data": data, "tag": tag, "agent": agent_id, "thread": thread}))
369
+ flush()
370
+
371
+ task on_start(info)
372
+ set thread to info["thread"]
373
+ when json_out
374
+ print(json_encode({"kind": "session", "data": info, "tag": "", "agent": info["agent"], "thread": info["thread"]}))
375
+ flush()
376
+
377
+ let sobre be {"to": agent_id, "thread": thread, "session": env("LAMPSON_SESSION", ""), "from": {"id": "", "name": "", "kind": "human"}, "text": message, "channel": "cli", "meta": {}}
378
+ let hooks be {"mode": mode, "ask_fn": nothing, "on_start": on_start, "on_event": when json_out then emit_json otherwise nothing}
379
+ let result be nothing
380
+ try
381
+ set result to runtime.deliver(sobre, hooks)
382
+ recover err
383
+ set result to {"agent": agent_id, "thread": thread, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
384
+
385
+ when json_out
386
+ print(json_encode({"kind": "done", "data": result, "tag": "", "agent": result["agent"], "thread": result["thread"]}))
387
+ otherwise
388
+ when starts_with(result["stopped"], "error")
389
+ print("lampson run: " + result["stopped"])
390
+ otherwise
391
+ print(result["text"])
392
+ flush()
393
+ when starts_with(result["stopped"], "error")
394
+ exit(1)