lampson 0.2.10 → 0.4.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,440 @@
1
+ -- lib/mailbox.syn — el buzón de cada conversación: fila, espera de silencio y mensajes a mitad de turno
2
+ -- (spec/engine.md, "buffer"). Lo usan las puertas que reciben mensajes de afuera (la API /v1 y sus canales).
3
+ --
4
+ -- Problema: un cliente escribe "hola" / "¿precio de X?" / "¿hay stock?" en ráfaga, o con mala señal. Sin esto,
5
+ -- tres turnos en paralelo sobre la misma sesión (el último en guardar pisa a los otros) y tres respuestas sueltas.
6
+ --
7
+ -- 1. FILA por (agente, thread) — siempre, no se apaga: nunca dos turnos a la vez sobre la misma conversación.
8
+ -- 2. ESPERA DE SILENCIO — el turno arranca cuando pasan `quiet_s` sin mensajes nuevos, o al cumplirse `max_s`
9
+ -- desde el primero de la ráfaga. Todos van en UN turno, ordenados por `sent_at` (la hora en que el cliente
10
+ -- escribió, si el canal la manda) y si no por llegada. Por agente: "buffer": {"quiet_s": 3, "max_s": 15} (el
11
+ -- default de la API) o "buffer": false (sin espera; la fila sigue).
12
+ -- 3. A MITAD DE TURNO — lo que llega mientras el agente trabaja entra por el buzón del loop (opts.inbox_fn, el
13
+ -- mismo de los subagentes) antes de la siguiente llamada al modelo: lo ve antes de responder.
14
+ --
15
+ -- Mecánica (estado de `serve`, compartido por handlers y agentes; no existe bajo `run`):
16
+ -- mb:lock:<k> lock por conteo con state_incr (se toma si el incremento da 1; se suelta con -1)
17
+ -- mb:q:<k> la fila · mb:first:<k> / mb:last:<k> llegada del primero y del último de la ráfaga
18
+ -- mb:w:<k> hay un worker vivo para esta conversación
19
+ -- mb:res:<id> el resultado de cada mensaje (lo levanta quien lo mandó)
20
+ -- El primer mensaje que encuentra la fila sin worker lanza uno (`agent MailboxWorker`); el worker junta, corre el
21
+ -- turno con runtime.turn, publica los eventos en el bus ("lampson.mb.<k>", para las respuestas SSE), deja los
22
+ -- resultados, entrega los callbacks (uno por lote y por URL) y se va cuando la fila queda vacía. Tomar la fila y
23
+ -- soltar el worker ocurren bajo el mismo lock: un mensaje que llega en ese instante nunca queda huérfano.
24
+
25
+ use "./teams.syn" as teams
26
+ use "./runtime.syn" as runtime
27
+ use "./loop.syn" as loop
28
+ use "./agents.syn" as agents
29
+ use "./approvals.syn" as approvals
30
+ use "./permission.syn" as permission
31
+ use "./plugins.syn" as plugins
32
+
33
+ export let DEFAULT_BUFFER be {"quiet_s": 3, "max_s": 15}
34
+ export let JOBS_DIR be ".lampson/api/jobs"
35
+ export let APPROVAL_TIMEOUT be 180
36
+ export let WAIT_TIMEOUT be 900
37
+ export let CHANNEL_LOG_DIR be ".lampson/channels"
38
+
39
+ -- ¿hay estado de serve? (bajo `synsema run` no: ahí cada proceso es un solo mensaje y no hace falta fila)
40
+ export task available()
41
+ try
42
+ state_get("mb:probe", nothing)
43
+ give true
44
+ recover err
45
+ give false
46
+
47
+ -- la conversación: (agente, thread); sin thread, la sesión; sin nada, el propio mensaje (nada que ordenar)
48
+ export task key_of(sobre, id)
49
+ let th be text(sobre["thread"])
50
+ when th != ""
51
+ give runtime.thread_key(sobre["to"], th)
52
+ let ss be text(sobre["session"])
53
+ when ss != ""
54
+ give runtime.thread_key(sobre["to"], "session:" + ss)
55
+ give runtime.thread_key(sobre["to"], "msg:" + id)
56
+
57
+ -- la espera de un agente: la suya, o la de la puerta (DEFAULT_BUFFER para la API); false → {0, 0}
58
+ export task buffer_of(spec, fallback)
59
+ let b be fallback
60
+ when spec != nothing and contains(spec, "buffer") and spec["buffer"] != nothing
61
+ set b to spec["buffer"]
62
+ when b == false or b == nothing
63
+ give {"quiet_s": 0, "max_s": 0}
64
+ give b
65
+
66
+ export task new_id()
67
+ require time
68
+ require random
69
+ give "m" + slice(text(floor(now() * 1000)), 5, 13) + slice(token(16), 0, 4)
70
+
71
+ -- ---------- lock y fila ----------
72
+
73
+ task lock(k)
74
+ require time
75
+ let lk be "mb:lock:" + k
76
+ let tries be 0
77
+ while state_incr(lk, 1) != 1
78
+ state_incr(lk, -1)
79
+ set tries to tries + 1
80
+ sleep(when tries < 50 then 0.005 otherwise 0.05)
81
+ give true
82
+
83
+ task unlock(k)
84
+ state_incr("mb:lock:" + k, -1)
85
+
86
+ -- encola; true si este mensaje tiene que lanzar el worker (la fila no tenía)
87
+ export task post(k, item)
88
+ require time
89
+ lock(k)
90
+ let q be state_get("mb:q:" + k, [])
91
+ state_set("mb:q:" + k, append(q, item))
92
+ state_set("mb:last:" + k, now())
93
+ when state_get("mb:first:" + k, nothing) == nothing
94
+ state_set("mb:first:" + k, now())
95
+ let claim be not state_get("mb:w:" + k, false)
96
+ when claim
97
+ state_set("mb:w:" + k, true)
98
+ unlock(k)
99
+ give claim
100
+
101
+ -- ¿hay un worker atendiendo la conversación (agente, thread)? (la pantalla de equipos lo muestra en vivo)
102
+ export task working(agent, thread)
103
+ try
104
+ give state_get("mb:w:" + runtime.thread_key(agent, thread), false) == true
105
+ recover err
106
+ give false
107
+
108
+ -- saca todo lo encolado
109
+ task take(k)
110
+ lock(k)
111
+ let q be state_get("mb:q:" + k, [])
112
+ state_set("mb:q:" + k, [])
113
+ state_set("mb:first:" + k, nothing)
114
+ unlock(k)
115
+ give q
116
+
117
+ -- el worker se va solo si la fila está vacía (bajo el lock: nadie encola en el medio)
118
+ task release(k)
119
+ lock(k)
120
+ let q be state_get("mb:q:" + k, [])
121
+ let gone be length(q) == 0
122
+ when gone
123
+ state_set("mb:w:" + k, false)
124
+ unlock(k)
125
+ give gone
126
+
127
+ -- espera de silencio: quiet_s sin mensajes nuevos, o max_s desde el primero
128
+ task settle(k, buf)
129
+ require time
130
+ while true
131
+ let first be state_get("mb:first:" + k, nothing)
132
+ when first == nothing
133
+ give true
134
+ let last be state_get("mb:last:" + k, first)
135
+ when now() - last >= buf["quiet_s"] or now() - first >= buf["max_s"]
136
+ give true
137
+ sleep(0.1)
138
+
139
+ -- espera el resultado de un mensaje (lo deja el worker)
140
+ export task wait(id)
141
+ require time
142
+ let deadline be now() + WAIT_TIMEOUT
143
+ while now() < deadline
144
+ let r be state_get("mb:res:" + id, nothing)
145
+ when r != nothing
146
+ state_delete("mb:res:" + id)
147
+ give r
148
+ sleep(0.1)
149
+ give {"agent": "", "thread": "", "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: timed out waiting for the conversation's worker", "batch": [id], "lead": id}
150
+
151
+ -- ---------- trabajos (callback) ----------
152
+
153
+ task job_path(id)
154
+ give JOBS_DIR + "/" + id + ".json"
155
+
156
+ export task job(id)
157
+ require file.read(".lampson")
158
+ require file.read(".lampson/*")
159
+ when not matches(id, "m[0-9a-zA-Z_-]{4,40}")
160
+ give nothing
161
+ try
162
+ give json_decode(read_file(job_path(id)))
163
+ recover err
164
+ give nothing
165
+
166
+ export task save_job(j)
167
+ require file(".lampson")
168
+ require file(".lampson/*")
169
+ write_file(job_path(j["job"]), json_encode(j))
170
+
171
+ task post_callback(url, payload)
172
+ require net
173
+ require env("LAMPSON_*")
174
+ let body be json_encode(payload)
175
+ let headers be {"Content-Type": "application/json", "User-Agent": "lampson"}
176
+ let sec be env("LAMPSON_WEBHOOK_SECRET", "")
177
+ when sec != ""
178
+ set headers["X-Lampson-Signature"] to "sha256=" + decode(hmac(body, sec), "hex")
179
+ -- dos intentos: un receptor que parpadea no pierde la respuesta
180
+ let tries be 0
181
+ while tries < 2
182
+ set tries to tries + 1
183
+ try
184
+ let r be http_post(url, body, headers, 15)
185
+ when r["ok"]
186
+ give true
187
+ print("[lampson mailbox] callback " + url + " respondió " + text(r["status"]))
188
+ recover err
189
+ print("[lampson mailbox] callback falló: " + text(err))
190
+ give false
191
+
192
+ -- aprobación sin nadie en la request: la cola de lib/approvals.syn (UI, link firmado, terminal); vence → denegado
193
+ export task approve_queue(name, args, why)
194
+ require time
195
+ require random
196
+ require net
197
+ require env("LAMPSON_*")
198
+ require file.read(".lampson")
199
+ require file.read(".lampson/*")
200
+ -- tocar la historia compartida (merge a main desde la copia de un agente): la persona tiene 30 min, no 3
201
+ let tmo be when contains(text(why), "shared history") then 1800 otherwise APPROVAL_TIMEOUT
202
+ let id be approvals.open("api", permission.describe_call(name, args), why, tmo)
203
+ give approvals.wait_detail(id, tmo)
204
+
205
+ -- ---------- el worker ----------
206
+
207
+ task sort_key(it)
208
+ when contains(it, "sent_at") and it["sent_at"] != nothing
209
+ try
210
+ give number(it["sent_at"])
211
+ recover err
212
+ give it["arrived"]
213
+ give it["arrived"]
214
+
215
+ task user_msg(it)
216
+ when length(it["images"]) > 0
217
+ give {"role": "user", "content": it["text"], "images": it["images"]}
218
+ give {"role": "user", "content": it["text"]}
219
+
220
+ -- un lote: un turno con todos los mensajes (y los que lleguen mientras), resultados, callbacks, jobs
221
+ task run_batch(k, spec, items)
222
+ require db(".lampson/teams.db")
223
+ require net
224
+ require exec
225
+ require time
226
+ require random
227
+ require file(".lampson")
228
+ require file(".lampson/*")
229
+ require file("workspace")
230
+ require file("workspace/*")
231
+ require file.read("skills")
232
+ require file.read("skills/*")
233
+ require file.read("plugins")
234
+ require file.read("plugins/*")
235
+ require file.read("agents")
236
+ require file.read("agents/*")
237
+ require file.read("memory")
238
+ require file.read("memory/*")
239
+ require env("LAMPSON_*")
240
+ require env("OS")
241
+ require secret("LAMPSON_*")
242
+ let ordered be sort_by(items, (it) => sort_key(it))
243
+ let lead be ordered[0]
244
+ let topic be "lampson.mb." + k
245
+ let all be ordered
246
+ -- "escribiendo…" del canal (acción `typing`, si el plugin la declara): al empezar y cada ~4,5 s mientras trabaja
247
+ let typing_pl be nothing
248
+ when lead["reply_channel"] != ""
249
+ let tp be plugins.channel(lead["reply_channel"])
250
+ when tp != nothing and tp["channel"]["typing"]
251
+ set typing_pl to tp
252
+ let typing_at be 0
253
+ task typing()
254
+ when typing_pl != nothing and now() - typing_at >= 4.5
255
+ set typing_at to now()
256
+ try
257
+ plugins.invoke(typing_pl, "typing", {"thread": lead["reply_thread"], "meta": ordered[length(ordered) - 1]["meta"]})
258
+ recover err
259
+ set typing_at to typing_at
260
+ typing()
261
+ task publish(kind, data, tag)
262
+ when kind == "busy"
263
+ typing()
264
+ when kind != "busy" and kind != "idle"
265
+ bus_publish(topic, {"kind": kind, "data": data, "tag": tag, "agent": lead["to"], "thread": lead["thread"]})
266
+ let hooks be {"mode": spec["mode"], "ask_fn": approve_queue, "on_event": publish}
267
+ let result be nothing
268
+ try
269
+ let o be runtime.open({"to": lead["to"], "thread": lead["thread"], "session": lead["session"], "text": "", "channel": lead["channel"], "meta": lead["meta"]}, hooks)
270
+ bus_publish(topic, {"kind": "session", "data": {"session": o["session"], "agent": o["ctx"]["agent"], "thread": o["thread"], "batch": apply((it) => it["id"], ordered)}, "tag": "", "agent": lead["to"], "thread": lead["thread"]})
271
+ when o["note"] != ""
272
+ publish("inbox", o["note"], "")
273
+ -- a mitad de turno: lo que llegó mientras el agente trabajaba entra antes de la próxima llamada al modelo
274
+ let prev be o["ctx"]["opts"]["inbox_fn"]
275
+ task mid(step, tag)
276
+ let msgs be []
277
+ let halt be false
278
+ when prev != nothing
279
+ let pi be call(prev, {"step": step, "tag": tag})
280
+ when pi != nothing
281
+ set msgs to pi["messages"]
282
+ set halt to pi["stop"]
283
+ each it in sort_by(take(k), (x) => sort_key(x))
284
+ set all to append(all, it)
285
+ let extra be when length(it["images"]) > 0 then " [+" + text(length(it["images"])) + " image(s), visible next turn]" otherwise ""
286
+ set msgs to append(msgs, it["text"] + extra)
287
+ when length(msgs) == 0 and not halt
288
+ give nothing
289
+ give {"messages": msgs, "stop": halt}
290
+ let ctx be o["ctx"]
291
+ set ctx["opts"] to loop.with_final_inbox(loop.with_inbox(ctx["opts"], mid, ""))
292
+ set o["ctx"] to ctx
293
+ let msgs be o["messages"]
294
+ each it in ordered
295
+ set msgs to append(msgs, user_msg(it))
296
+ let label be join(apply((it) => it["text"], ordered), " ⏎ ")
297
+ let r be runtime.turn(o, msgs, label, hooks)
298
+ set result to {"agent": o["ctx"]["agent"], "thread": o["thread"], "session": o["session"], "text": r["text"], "steps": r["steps"], "usage": r["usage"], "stopped": r["stopped"]}
299
+ recover err
300
+ set result to {"agent": lead["to"], "thread": lead["thread"], "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
301
+ -- equipos y objetivos: un turno que falló (proveedor caído, error del runtime) queda en el registro del equipo —
302
+ -- lo ven el líder en su próximo turno y la pantalla; si no, el equipo esperaría en silencio
303
+ when starts_with(text(result["stopped"]), "error") and (starts_with(text(lead["thread"]), "team:") or starts_with(text(lead["thread"]), "objective:"))
304
+ try
305
+ teams.log(lead["thread"], result["agent"], "error", "", "turn failed: " + slice(text(result["stopped"]), 0, 300))
306
+ recover err
307
+ set err to err
308
+ let ids be apply((it) => it["id"], all)
309
+ set result["batch"] to ids
310
+ set result["lead"] to lead["id"]
311
+ each it in all
312
+ state_set("mb:res:" + it["id"], result)
313
+ bus_publish(topic, {"kind": "done", "data": result, "tag": "", "agent": result["agent"], "thread": result["thread"]})
314
+ -- callbacks: uno por URL distinta del lote; cada job queda done (el que encabeza) o merged (los demás)
315
+ let urls be []
316
+ each it in all
317
+ when it["callback"] != "" and not contains(urls, it["callback"])
318
+ set urls to append(urls, it["callback"])
319
+ each u in urls
320
+ let mine be where(all, (it) => it["callback"] == u)
321
+ let payload be {"job": mine[0]["id"], "jobs": apply((it) => it["id"], mine), "batch": ids, "status": when starts_with(result["stopped"], "error") then "error" otherwise "done", "agent": result["agent"], "thread": result["thread"], "session": result["session"], "text": result["text"], "steps": result["steps"], "usage": result["usage"], "stopped": result["stopped"], "meta": mine[0]["meta"]}
322
+ let ok be post_callback(u, payload)
323
+ each it in mine
324
+ when it["job"]
325
+ let j be job(it["id"])
326
+ when j != nothing
327
+ set j["status"] to when it["id"] == mine[0]["id"] then payload["status"] otherwise "merged"
328
+ set j["merged_into"] to when it["id"] == mine[0]["id"] then nothing otherwise mine[0]["id"]
329
+ set j["result"] to result
330
+ set j["delivered"] to ok
331
+ set j["finished"] to format_time(now())
332
+ save_job(j)
333
+ -- canales (lib/channels.syn): UNA respuesta por lote y canal, por la acción `send` del plugin. El meta del último
334
+ -- mensaje (ids de la plataforma más recientes). Un error del agente no se le manda al cliente: queda en el log.
335
+ let chans be []
336
+ each it in all
337
+ when it["reply_channel"] != "" and not contains(chans, it["reply_channel"])
338
+ set chans to append(chans, it["reply_channel"])
339
+ each ch in chans
340
+ let mine be where(all, (it) => it["reply_channel"] == ch)
341
+ let last be mine[length(mine) - 1]
342
+ let sent be {"channel": ch, "ok": false, "output": ""}
343
+ when starts_with(result["stopped"], "error") or trim(result["text"]) == ""
344
+ set sent["output"] to "not sent: " + (when trim(result["text"]) == "" then "empty answer" otherwise result["stopped"])
345
+ otherwise
346
+ let pl be plugins.channel(ch)
347
+ when pl == nothing
348
+ set sent["output"] to "not sent: channel '" + ch + "' is not enabled anymore"
349
+ otherwise
350
+ let out be text(plugins.invoke(pl, "send", {"thread": last["reply_thread"], "text": result["text"], "meta": last["meta"], "agent": result["agent"], "session": result["session"], "batch": ids}))
351
+ set sent["output"] to out
352
+ set sent["ok"] to not starts_with(out, "ERROR")
353
+ when not file_exists(CHANNEL_LOG_DIR + "/" + ch + ".log")
354
+ write_file(CHANNEL_LOG_DIR + "/" + ch + ".log", "")
355
+ append_file(CHANNEL_LOG_DIR + "/" + ch + ".log", format_time(now()) + " " + (when sent["ok"] then "SENT " otherwise "FAIL ") + last["reply_thread"] + " batch=" + text(length(ids)) + " " + replace(slice(sent["output"], 0, 200), "\n", " ") + "\n")
356
+ bus_publish(topic, {"kind": "channel_sent", "data": sent, "tag": "", "agent": result["agent"], "thread": result["thread"]})
357
+ give result
358
+
359
+ export task work(spec_json)
360
+ require db(".lampson/teams.db")
361
+ require net
362
+ require exec
363
+ require time
364
+ require random
365
+ require file(".lampson")
366
+ require file(".lampson/*")
367
+ require file("workspace")
368
+ require file("workspace/*")
369
+ require file.read("skills")
370
+ require file.read("skills/*")
371
+ require file.read("plugins")
372
+ require file.read("plugins/*")
373
+ require file.read("agents")
374
+ require file.read("agents/*")
375
+ require file.read("memory")
376
+ require file.read("memory/*")
377
+ require env("LAMPSON_*")
378
+ require env("OS")
379
+ require secret("LAMPSON_*")
380
+ let spec be json_decode(spec_json)
381
+ let k be spec["key"]
382
+ let running be true
383
+ while running
384
+ settle(k, spec["buffer"])
385
+ let items be take(k)
386
+ when length(items) == 0
387
+ when release(k)
388
+ set running to false
389
+ otherwise
390
+ run_batch(k, spec, items)
391
+ give true
392
+
393
+ -- MIGA runtime (igual que agents.Child): un `agent` solo ve sus parámetros, las builtins y las tasks TOP-LEVEL del
394
+ -- entry. web.syn define `task lampson_mailbox_worker(spec_json) give mailbox.work(spec_json)`.
395
+ agent MailboxWorker
396
+ require db(".lampson/teams.db")
397
+ require net
398
+ require exec
399
+ require time
400
+ require random
401
+ require file(".lampson")
402
+ require file(".lampson/*")
403
+ require file("workspace")
404
+ require file("workspace/*")
405
+ require file.read("skills")
406
+ require file.read("skills/*")
407
+ require file.read("plugins")
408
+ require file.read("plugins/*")
409
+ require file.read("agents")
410
+ require file.read("agents/*")
411
+ require file("memory")
412
+ require file("memory/*")
413
+ require env("LAMPSON_*")
414
+ require env("OS")
415
+ require secret("LAMPSON_*")
416
+ lampson_mailbox_worker(spec_json)
417
+
418
+ -- ---------- lo que llama la puerta ----------
419
+
420
+ -- arma el item y lo encola; lanza el worker si hace falta. → {id, key}
421
+ -- opts: {mode, buffer, callback, job, reply_channel, reply_thread}
422
+ export task submit(sobre, opts)
423
+ require time
424
+ require random
425
+ require file.read("workspace")
426
+ require file.read("workspace/*")
427
+ require file.read("agents")
428
+ require file.read("agents/*")
429
+ let id be when contains(opts, "id") then opts["id"] otherwise new_id()
430
+ let k be key_of(sobre, id)
431
+ let sent be nothing
432
+ when contains(sobre["meta"], "sent_at")
433
+ set sent to sobre["meta"]["sent_at"]
434
+ let item be {"id": id, "to": sobre["to"], "thread": sobre["thread"], "session": sobre["session"], "text": sobre["text"], "images": sobre["images"], "channel": sobre["channel"], "meta": sobre["meta"], "from": sobre["from"], "sent_at": sent, "arrived": now(), "callback": when contains(opts, "callback") then opts["callback"] otherwise "", "job": contains(opts, "job") and opts["job"] == true, "reply_channel": when contains(opts, "reply_channel") then opts["reply_channel"] otherwise "", "reply_thread": when contains(opts, "reply_thread") then opts["reply_thread"] otherwise ""}
435
+ when post(k, item)
436
+ -- el worker espera {quiet_s, max_s}: false/nothing (sin espera) se normaliza acá — con `false` el worker
437
+ -- moría al primer settle y la conversación quedaba trabada (visto 2026-10-16)
438
+ let buf be when contains(opts, "buffer") and type_of(opts["buffer"]) == "map" then opts["buffer"] otherwise buffer_of(nothing, false)
439
+ spawn MailboxWorker with spec_json = json_encode({"key": k, "mode": opts["mode"], "buffer": buf})
440
+ give {"id": id, "key": k}
package/lib/mcp.syn CHANGED
@@ -19,7 +19,12 @@
19
19
  -- loop.execute las despacha acá (no son tasks Synsema: los args son libres). permission.syn: ask por
20
20
  -- defecto (una tool de terceros con efectos fuera del workspace), yolo permite, strict deniega; las
21
21
  -- de solo lectura (annotations.readOnlyHint) están también en plan/review/explore.
22
- -- Sin HTTP/SSE por ahora (stdio cubre casi todos los servers publicados); es el siguiente paso natural.
22
+ -- HTTP ("Streamable HTTP", 2026-10-16): {"mcpServers": {"proveedor": {"url": "https://…/w/x/v1/mcp",
23
+ -- "headers": {"Authorization": "Bearer ${LAMPSON_PROVEEDOR_KEY}"}}}} — el formato de Claude Code. ${LAMPSON_*} se
24
+ -- expande desde el entorno/.env (la key no queda escrita en el mcp.json). Sin supervisor: start_all hace el
25
+ -- handshake por HTTP (guarda Mcp-Session-Id si el server lo da) y cada llamada es un POST; la respuesta puede venir
26
+ -- como JSON o como SSE (text/event-stream: se busca el mensaje con ese id). Así un Lampson usa los agentes de otro
27
+ -- Lampson (agente ↔ agente) como tools: mcp_proveedor_ask.
23
28
 
24
29
  use "./tools/common.syn" as c
25
30
 
@@ -52,7 +57,9 @@ task read_config(path, scope)
52
57
  when contains(s, "disabled")
53
58
  set disabled to s["disabled"] == true
54
59
  when valid_name(name) and contains(s, "command") and not disabled
55
- set out to append(out, {"name": name, "command": text(s["command"]), "args": when contains(s, "args") then s["args"] otherwise [], "env": when contains(s, "env") then s["env"] otherwise {}, "cwd": when contains(s, "cwd") then text(s["cwd"]) otherwise "workspace", "scope": scope})
60
+ set out to append(out, {"name": name, "command": text(s["command"]), "args": when contains(s, "args") then s["args"] otherwise [], "env": when contains(s, "env") then s["env"] otherwise {}, "cwd": when contains(s, "cwd") then text(s["cwd"]) otherwise "workspace", "scope": scope, "url": ""})
61
+ otherwise when valid_name(name) and contains(s, "url") and not disabled
62
+ set out to append(out, {"name": name, "command": "", "args": [], "env": {}, "cwd": "", "scope": scope, "url": text(s["url"]), "headers": when contains(s, "headers") and type_of(s["headers"]) == "map" then s["headers"] otherwise {}})
56
63
  recover err
57
64
  give out
58
65
  give out
@@ -77,6 +84,96 @@ export task servers()
77
84
  set out to append(out, by_name[n])
78
85
  give out
79
86
 
87
+ -- ---------- transporte HTTP ----------
88
+
89
+ -- "${LAMPSON_X}" → el valor de LAMPSON_X (solo LAMPSON_*: lo que el programa puede leer)
90
+ export task expand(v)
91
+ require env("LAMPSON_*")
92
+ let out be text(v)
93
+ let guard be 0
94
+ while contains(out, "${") and guard < 20
95
+ set guard to guard + 1
96
+ let a be length(split(out, "${")[0])
97
+ let rest be slice(out, a + 2, length(out))
98
+ when not contains(rest, "}")
99
+ give out
100
+ let nm be split(rest, "}")[0]
101
+ let val be when starts_with(nm, "LAMPSON_") then env(nm, "") otherwise ""
102
+ set out to slice(out, 0, a) + val + slice(rest, length(nm) + 1, length(rest))
103
+ give out
104
+
105
+ task header_of(h, name)
106
+ each k in keys(h)
107
+ when lower(k) == name
108
+ give text(h[k])
109
+ give ""
110
+
111
+ -- un request JSON-RPC por HTTP → {msg, session} (msg = la respuesta con ese id, o {error})
112
+ export task http_rpc(s, session, id, method, params, timeout)
113
+ require net
114
+ require env("LAMPSON_*")
115
+ let hs be {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18"}
116
+ each k in keys(s["headers"])
117
+ set hs[k] to expand(s["headers"][k])
118
+ when session != ""
119
+ set hs["Mcp-Session-Id"] to session
120
+ let body be {"jsonrpc": "2.0", "method": method, "params": params}
121
+ when id != nothing
122
+ set body["id"] to id
123
+ let r be nothing
124
+ try
125
+ set r to http_post(s["url"], json_encode(body), hs, timeout)
126
+ recover err
127
+ give {"msg": {"error": "cannot reach " + s["url"] + ": " + text(err)}, "session": session}
128
+ let rh be when contains(r, "headers") then r["headers"] otherwise {}
129
+ let sid be header_of(rh, "mcp-session-id")
130
+ let new_session be when sid != "" then sid otherwise session
131
+ when id == nothing
132
+ give {"msg": {"result": {}}, "session": new_session}
133
+ when not r["ok"]
134
+ give {"msg": {"error": "HTTP " + text(r["status"]) + ": " + slice(text(when contains(r, "body") then r["body"] otherwise ""), 0, 200)}, "session": new_session}
135
+ let raw be text(when contains(r, "body") then r["body"] otherwise "")
136
+ -- SSE: "data: {…}" por evento; el que tiene nuestro id es la respuesta
137
+ when contains(lower(header_of(rh, "content-type")), "text/event-stream")
138
+ each l in split(replace(raw, "\r", ""), "\n")
139
+ when starts_with(l, "data:")
140
+ try
141
+ let m be json_decode(trim(slice(l, 5, length(l))))
142
+ when contains(m, "id") and m["id"] == id
143
+ give {"msg": m, "session": new_session}
144
+ recover err
145
+ set raw to raw
146
+ give {"msg": {"error": "no response with id " + text(id) + " in the event stream"}, "session": new_session}
147
+ try
148
+ give {"msg": json_decode(raw), "session": new_session}
149
+ recover err
150
+ give {"msg": {"error": "not JSON: " + slice(raw, 0, 200)}, "session": new_session}
151
+
152
+ -- handshake + tools/list de un server HTTP; deja el estado en el blackboard como el supervisor stdio
153
+ task connect_http(s)
154
+ require net
155
+ require time
156
+ require env("LAMPSON_*")
157
+ let key be "mcp:" + s["name"]
158
+ share {"status": "starting", "tools": [], "error": nothing, "started": now(), "transport": "http", "session": ""} as key
159
+ let a be http_rpc(s, "", 1, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "lampson", "version": "0.2"}}, 30)
160
+ when contains(a["msg"], "error")
161
+ share {"status": "error", "tools": [], "error": "initialize failed: " + text(a["msg"]["error"]), "started": now(), "transport": "http", "session": ""} as key
162
+ give false
163
+ let sess be a["session"]
164
+ http_rpc(s, sess, nothing, "notifications/initialized", {}, 15)
165
+ let l be http_rpc(s, sess, 2, "tools/list", {}, 30)
166
+ let tools be []
167
+ when contains(l["msg"], "result") and contains(l["msg"]["result"], "tools")
168
+ each t in l["msg"]["result"]["tools"]
169
+ let ro be false
170
+ when contains(t, "annotations") and contains(t["annotations"], "readOnlyHint")
171
+ set ro to t["annotations"]["readOnlyHint"] == true
172
+ set tools to append(tools, {"name": t["name"], "description": when contains(t, "description") then t["description"] otherwise "", "inputSchema": when contains(t, "inputSchema") then t["inputSchema"] otherwise {"type": "object", "properties": {}}, "readonly": ro})
173
+ share {"status": "ready", "tools": tools, "error": nothing, "started": now(), "transport": "http", "session": sess} as key
174
+ bus_publish("mcp." + s["name"], {"name": s["name"], "status": "ready", "tools": length(tools)})
175
+ give true
176
+
80
177
  -- ---------- supervisor: un agente por server ----------
81
178
  -- Parámetros del spawn: name, command, args_json, env_json, cwd (un agente no ve el módulo: todo va por spawn,
82
179
  -- y las constantes PROTOCOL/timeouts van como literales acá adentro).
@@ -203,11 +300,15 @@ export task start_all(wait_s)
203
300
  require file(".lampson/*")
204
301
  require file("workspace")
205
302
  require file("workspace/*")
303
+ require net
206
304
  let list be servers()
207
305
  each s in list
208
306
  let st be state(s["name"])
209
307
  when st == nothing or (st["status"] != "ready" and st["status"] != "starting")
210
- spawn McpSup with name = s["name"], command = s["command"], args_json = json_encode(s["args"]), env_json = json_encode(s["env"]), cwd = s["cwd"]
308
+ when s["url"] != ""
309
+ connect_http(s)
310
+ otherwise
311
+ spawn McpSup with name = s["name"], command = s["command"], args_json = json_encode(s["args"]), env_json = json_encode(s["env"]), cwd = s["cwd"]
211
312
  let waited be 0
212
313
  while waited < wait_s * 10 and length(where(list, (s) => state(s["name"]) == nothing or state(s["name"])["status"] == "starting")) > 0
213
314
  sleep(0.1)
@@ -265,8 +366,9 @@ export task add_server(name, command_line, env_map, scope)
265
366
  require file("workspace/*")
266
367
  when not valid_name(name)
267
368
  raise("invalid server name '" + text(name) + "' (letters, digits, - or _, max 32)")
268
- let parsed be parse_command(command_line)
269
- when parsed["command"] == ""
369
+ let is_url be starts_with(trim(text(command_line)), "https://") or starts_with(trim(text(command_line)), "http://")
370
+ let parsed be when is_url then {"command": "", "args": []} otherwise parse_command(command_line)
371
+ when parsed["command"] == "" and not is_url
270
372
  raise("empty command")
271
373
  let sc be when scope == "project" then "project" otherwise "global"
272
374
  let path be config_path(sc)
@@ -278,16 +380,24 @@ export task add_server(name, command_line, env_map, scope)
278
380
  when not contains(doc, "mcpServers")
279
381
  set doc["mcpServers"] to {}
280
382
  let entry be {"command": parsed["command"], "args": parsed["args"]}
281
- when env_map != nothing
383
+ when is_url
384
+ -- un server HTTP: env_map son sus headers (p. ej. {"Authorization": "Bearer ${LAMPSON_PROVEEDOR_KEY}"})
385
+ set entry to {"url": trim(text(command_line))}
386
+ when env_map != nothing and length(keys(env_map)) > 0
387
+ set entry["headers"] to env_map
388
+ otherwise when env_map != nothing
282
389
  when length(keys(env_map)) > 0
283
390
  set entry["env"] to env_map
284
391
  let servers_map be doc["mcpServers"]
285
392
  set servers_map[name] to entry
286
393
  set doc["mcpServers"] to servers_map
287
394
  write_file(path, json_encode(doc))
288
- -- reconexión: si ya había un supervisor con este nombre, apagarlo antes de arrancar el nuevo
395
+ -- reconexión: si ya había un supervisor con este nombre, apagarlo antes de arrancar el nuevo (uno HTTP no tiene
396
+ -- proceso: se olvida su estado y start_all reconecta)
289
397
  let st be state(name)
290
- when st != nothing
398
+ when is_url
399
+ share nothing as "mcp:" + name
400
+ otherwise when st != nothing
291
401
  when st["status"] == "ready" or st["status"] == "starting"
292
402
  bus_publish("mcp.stop." + name, {})
293
403
  let w be 0
@@ -342,7 +452,7 @@ export task summary()
342
452
  let out be []
343
453
  each s in servers()
344
454
  let st be state(s["name"])
345
- set out to append(out, {"name": s["name"], "scope": s["scope"], "command": s["command"] + " " + join(apply((a) => text(a), s["args"]), " "), "status": when st == nothing then "off" otherwise st["status"], "error": when st == nothing then nothing otherwise st["error"], "tools": when st == nothing then [] otherwise apply((t) => t["name"], st["tools"])})
455
+ set out to append(out, {"name": s["name"], "scope": s["scope"], "command": when s["url"] != "" then s["url"] otherwise s["command"] + " " + join(apply((a) => text(a), s["args"]), " "), "status": when st == nothing then "off" otherwise st["status"], "error": when st == nothing then nothing otherwise st["error"], "tools": when st == nothing then [] otherwise apply((t) => t["name"], st["tools"])})
346
456
  give out
347
457
 
348
458
  -- ---------- tools para el modelo ----------
@@ -383,6 +493,7 @@ task split_name(full)
383
493
 
384
494
  -- llamada: request por bus al supervisor, respuesta por bus; el contenido vuelve como texto para el modelo
385
495
  export task call(full_name, args)
496
+ require net
386
497
  require time
387
498
  require file(".lampson")
388
499
  require file(".lampson/*")
@@ -394,6 +505,14 @@ export task call(full_name, args)
394
505
  let st be state(parts["server"])
395
506
  when st == nothing or st["status"] != "ready"
396
507
  raise("MCP server '" + parts["server"] + "' is not ready (" + (when st == nothing then "off" otherwise st["status"]) + ")")
508
+ when contains(st, "transport") and st["transport"] == "http"
509
+ let srv be where(servers(), (x) => x["name"] == parts["server"])
510
+ when length(srv) == 0
511
+ raise("MCP server '" + parts["server"] + "' is not configured anymore")
512
+ let hr be http_rpc(srv[0], st["session"], floor(now() * 1000), "tools/call", {"name": parts["tool"], "arguments": when args == nothing then {} otherwise args}, CALL_TIMEOUT)
513
+ when contains(hr["msg"], "error")
514
+ raise("MCP error: " + text(hr["msg"]["error"]))
515
+ give render(hr["msg"]["result"])
397
516
  let id be text(floor(now() * 1000000))
398
517
  let sub be bus_subscribe("mcp.res." + parts["server"] + "." + id)
399
518
  bus_publish("mcp.req." + parts["server"], {"id": id, "method": "tools/call", "params": {"name": parts["tool"], "arguments": when args == nothing then {} otherwise args}})