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.
- package/README.md +16 -0
- package/bin/lampson.js +2 -2
- package/chat.syn +39 -24
- package/cli.syn +6 -3
- package/hub.tpl.syn +4 -0
- package/lampson.ps1 +48 -6
- package/lampson.sh +69 -24
- package/lib/api.syn +153 -0
- package/lib/apikeys.syn +115 -0
- package/lib/channels.syn +340 -0
- package/lib/loop.syn +27 -1
- package/lib/mailbox.syn +418 -0
- package/lib/mcp.syn +128 -9
- package/lib/mcp_server.syn +235 -0
- package/lib/plugins.syn +62 -7
- package/lib/runtime.syn +572 -0
- package/lib/scope.syn +62 -0
- package/lib/session.syn +11 -1
- package/lib/tools.syn +1 -1
- package/lib/workspaces.syn +29 -3
- package/package.json +16 -2
- package/plugins/chatwoot/plugin.json +11 -0
- package/plugins/chatwoot/plugin.syn +143 -0
- package/plugins/telegram/plugin.json +11 -0
- package/plugins/telegram/plugin.syn +272 -0
- package/public/css/panel.css +2 -0
- package/public/index.html +9 -0
- package/public/js/app.js +1 -1
- package/public/js/engine.js +149 -0
- package/public/js/sessions.js +3 -1
- package/run.syn +394 -0
- package/sdk/index.d.ts +94 -0
- package/sdk/index.js +250 -0
- package/sdk/index.mjs +4 -0
- package/web.syn +315 -47
package/lib/mailbox.syn
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
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 "./runtime.syn" as runtime
|
|
26
|
+
use "./loop.syn" as loop
|
|
27
|
+
use "./agents.syn" as agents
|
|
28
|
+
use "./approvals.syn" as approvals
|
|
29
|
+
use "./permission.syn" as permission
|
|
30
|
+
use "./plugins.syn" as plugins
|
|
31
|
+
|
|
32
|
+
export let DEFAULT_BUFFER be {"quiet_s": 3, "max_s": 15}
|
|
33
|
+
export let JOBS_DIR be ".lampson/api/jobs"
|
|
34
|
+
export let APPROVAL_TIMEOUT be 180
|
|
35
|
+
export let WAIT_TIMEOUT be 900
|
|
36
|
+
export let CHANNEL_LOG_DIR be ".lampson/channels"
|
|
37
|
+
|
|
38
|
+
-- ¿hay estado de serve? (bajo `synsema run` no: ahí cada proceso es un solo mensaje y no hace falta fila)
|
|
39
|
+
export task available()
|
|
40
|
+
try
|
|
41
|
+
state_get("mb:probe", nothing)
|
|
42
|
+
give true
|
|
43
|
+
recover err
|
|
44
|
+
give false
|
|
45
|
+
|
|
46
|
+
-- la conversación: (agente, thread); sin thread, la sesión; sin nada, el propio mensaje (nada que ordenar)
|
|
47
|
+
export task key_of(sobre, id)
|
|
48
|
+
let th be text(sobre["thread"])
|
|
49
|
+
when th != ""
|
|
50
|
+
give runtime.thread_key(sobre["to"], th)
|
|
51
|
+
let ss be text(sobre["session"])
|
|
52
|
+
when ss != ""
|
|
53
|
+
give runtime.thread_key(sobre["to"], "session:" + ss)
|
|
54
|
+
give runtime.thread_key(sobre["to"], "msg:" + id)
|
|
55
|
+
|
|
56
|
+
-- la espera de un agente: la suya, o la de la puerta (DEFAULT_BUFFER para la API); false → {0, 0}
|
|
57
|
+
export task buffer_of(spec, fallback)
|
|
58
|
+
let b be fallback
|
|
59
|
+
when spec != nothing and contains(spec, "buffer") and spec["buffer"] != nothing
|
|
60
|
+
set b to spec["buffer"]
|
|
61
|
+
when b == false or b == nothing
|
|
62
|
+
give {"quiet_s": 0, "max_s": 0}
|
|
63
|
+
give b
|
|
64
|
+
|
|
65
|
+
export task new_id()
|
|
66
|
+
require time
|
|
67
|
+
require random
|
|
68
|
+
give "m" + slice(text(floor(now() * 1000)), 5, 13) + slice(token(16), 0, 4)
|
|
69
|
+
|
|
70
|
+
-- ---------- lock y fila ----------
|
|
71
|
+
|
|
72
|
+
task lock(k)
|
|
73
|
+
require time
|
|
74
|
+
let lk be "mb:lock:" + k
|
|
75
|
+
let tries be 0
|
|
76
|
+
while state_incr(lk, 1) != 1
|
|
77
|
+
state_incr(lk, -1)
|
|
78
|
+
set tries to tries + 1
|
|
79
|
+
sleep(when tries < 50 then 0.005 otherwise 0.05)
|
|
80
|
+
give true
|
|
81
|
+
|
|
82
|
+
task unlock(k)
|
|
83
|
+
state_incr("mb:lock:" + k, -1)
|
|
84
|
+
|
|
85
|
+
-- encola; true si este mensaje tiene que lanzar el worker (la fila no tenía)
|
|
86
|
+
export task post(k, item)
|
|
87
|
+
require time
|
|
88
|
+
lock(k)
|
|
89
|
+
let q be state_get("mb:q:" + k, [])
|
|
90
|
+
state_set("mb:q:" + k, append(q, item))
|
|
91
|
+
state_set("mb:last:" + k, now())
|
|
92
|
+
when state_get("mb:first:" + k, nothing) == nothing
|
|
93
|
+
state_set("mb:first:" + k, now())
|
|
94
|
+
let claim be not state_get("mb:w:" + k, false)
|
|
95
|
+
when claim
|
|
96
|
+
state_set("mb:w:" + k, true)
|
|
97
|
+
unlock(k)
|
|
98
|
+
give claim
|
|
99
|
+
|
|
100
|
+
-- saca todo lo encolado
|
|
101
|
+
task take(k)
|
|
102
|
+
lock(k)
|
|
103
|
+
let q be state_get("mb:q:" + k, [])
|
|
104
|
+
state_set("mb:q:" + k, [])
|
|
105
|
+
state_set("mb:first:" + k, nothing)
|
|
106
|
+
unlock(k)
|
|
107
|
+
give q
|
|
108
|
+
|
|
109
|
+
-- el worker se va solo si la fila está vacía (bajo el lock: nadie encola en el medio)
|
|
110
|
+
task release(k)
|
|
111
|
+
lock(k)
|
|
112
|
+
let q be state_get("mb:q:" + k, [])
|
|
113
|
+
let gone be length(q) == 0
|
|
114
|
+
when gone
|
|
115
|
+
state_set("mb:w:" + k, false)
|
|
116
|
+
unlock(k)
|
|
117
|
+
give gone
|
|
118
|
+
|
|
119
|
+
-- espera de silencio: quiet_s sin mensajes nuevos, o max_s desde el primero
|
|
120
|
+
task settle(k, buf)
|
|
121
|
+
require time
|
|
122
|
+
while true
|
|
123
|
+
let first be state_get("mb:first:" + k, nothing)
|
|
124
|
+
when first == nothing
|
|
125
|
+
give true
|
|
126
|
+
let last be state_get("mb:last:" + k, first)
|
|
127
|
+
when now() - last >= buf["quiet_s"] or now() - first >= buf["max_s"]
|
|
128
|
+
give true
|
|
129
|
+
sleep(0.1)
|
|
130
|
+
|
|
131
|
+
-- espera el resultado de un mensaje (lo deja el worker)
|
|
132
|
+
export task wait(id)
|
|
133
|
+
require time
|
|
134
|
+
let deadline be now() + WAIT_TIMEOUT
|
|
135
|
+
while now() < deadline
|
|
136
|
+
let r be state_get("mb:res:" + id, nothing)
|
|
137
|
+
when r != nothing
|
|
138
|
+
state_delete("mb:res:" + id)
|
|
139
|
+
give r
|
|
140
|
+
sleep(0.1)
|
|
141
|
+
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}
|
|
142
|
+
|
|
143
|
+
-- ---------- trabajos (callback) ----------
|
|
144
|
+
|
|
145
|
+
task job_path(id)
|
|
146
|
+
give JOBS_DIR + "/" + id + ".json"
|
|
147
|
+
|
|
148
|
+
export task job(id)
|
|
149
|
+
require file.read(".lampson")
|
|
150
|
+
require file.read(".lampson/*")
|
|
151
|
+
when not matches(id, "m[0-9a-zA-Z_-]{4,40}")
|
|
152
|
+
give nothing
|
|
153
|
+
try
|
|
154
|
+
give json_decode(read_file(job_path(id)))
|
|
155
|
+
recover err
|
|
156
|
+
give nothing
|
|
157
|
+
|
|
158
|
+
export task save_job(j)
|
|
159
|
+
require file(".lampson")
|
|
160
|
+
require file(".lampson/*")
|
|
161
|
+
write_file(job_path(j["job"]), json_encode(j))
|
|
162
|
+
|
|
163
|
+
task post_callback(url, payload)
|
|
164
|
+
require net
|
|
165
|
+
require env("LAMPSON_*")
|
|
166
|
+
let body be json_encode(payload)
|
|
167
|
+
let headers be {"Content-Type": "application/json", "User-Agent": "lampson"}
|
|
168
|
+
let sec be env("LAMPSON_WEBHOOK_SECRET", "")
|
|
169
|
+
when sec != ""
|
|
170
|
+
set headers["X-Lampson-Signature"] to "sha256=" + decode(hmac(body, sec), "hex")
|
|
171
|
+
-- dos intentos: un receptor que parpadea no pierde la respuesta
|
|
172
|
+
let tries be 0
|
|
173
|
+
while tries < 2
|
|
174
|
+
set tries to tries + 1
|
|
175
|
+
try
|
|
176
|
+
let r be http_post(url, body, headers, 15)
|
|
177
|
+
when r["ok"]
|
|
178
|
+
give true
|
|
179
|
+
print("[lampson mailbox] callback " + url + " respondió " + text(r["status"]))
|
|
180
|
+
recover err
|
|
181
|
+
print("[lampson mailbox] callback falló: " + text(err))
|
|
182
|
+
give false
|
|
183
|
+
|
|
184
|
+
-- aprobación sin nadie en la request: la cola de lib/approvals.syn (UI, link firmado, terminal); vence → denegado
|
|
185
|
+
export task approve_queue(name, args, why)
|
|
186
|
+
require time
|
|
187
|
+
require random
|
|
188
|
+
require net
|
|
189
|
+
require env("LAMPSON_*")
|
|
190
|
+
require file.read(".lampson")
|
|
191
|
+
require file.read(".lampson/*")
|
|
192
|
+
let id be approvals.open("api", permission.describe_call(name, args), why, APPROVAL_TIMEOUT)
|
|
193
|
+
give approvals.wait(id, APPROVAL_TIMEOUT)
|
|
194
|
+
|
|
195
|
+
-- ---------- el worker ----------
|
|
196
|
+
|
|
197
|
+
task sort_key(it)
|
|
198
|
+
when contains(it, "sent_at") and it["sent_at"] != nothing
|
|
199
|
+
try
|
|
200
|
+
give number(it["sent_at"])
|
|
201
|
+
recover err
|
|
202
|
+
give it["arrived"]
|
|
203
|
+
give it["arrived"]
|
|
204
|
+
|
|
205
|
+
task user_msg(it)
|
|
206
|
+
when length(it["images"]) > 0
|
|
207
|
+
give {"role": "user", "content": it["text"], "images": it["images"]}
|
|
208
|
+
give {"role": "user", "content": it["text"]}
|
|
209
|
+
|
|
210
|
+
-- un lote: un turno con todos los mensajes (y los que lleguen mientras), resultados, callbacks, jobs
|
|
211
|
+
task run_batch(k, spec, items)
|
|
212
|
+
require net
|
|
213
|
+
require exec
|
|
214
|
+
require time
|
|
215
|
+
require random
|
|
216
|
+
require file(".lampson")
|
|
217
|
+
require file(".lampson/*")
|
|
218
|
+
require file("workspace")
|
|
219
|
+
require file("workspace/*")
|
|
220
|
+
require file.read("skills")
|
|
221
|
+
require file.read("skills/*")
|
|
222
|
+
require file.read("plugins")
|
|
223
|
+
require file.read("plugins/*")
|
|
224
|
+
require file.read("agents")
|
|
225
|
+
require file.read("agents/*")
|
|
226
|
+
require file.read("memory")
|
|
227
|
+
require file.read("memory/*")
|
|
228
|
+
require env("LAMPSON_*")
|
|
229
|
+
require env("OS")
|
|
230
|
+
require secret("LAMPSON_*")
|
|
231
|
+
let ordered be sort_by(items, (it) => sort_key(it))
|
|
232
|
+
let lead be ordered[0]
|
|
233
|
+
let topic be "lampson.mb." + k
|
|
234
|
+
let all be ordered
|
|
235
|
+
-- "escribiendo…" del canal (acción `typing`, si el plugin la declara): al empezar y cada ~4,5 s mientras trabaja
|
|
236
|
+
let typing_pl be nothing
|
|
237
|
+
when lead["reply_channel"] != ""
|
|
238
|
+
let tp be plugins.channel(lead["reply_channel"])
|
|
239
|
+
when tp != nothing and tp["channel"]["typing"]
|
|
240
|
+
set typing_pl to tp
|
|
241
|
+
let typing_at be 0
|
|
242
|
+
task typing()
|
|
243
|
+
when typing_pl != nothing and now() - typing_at >= 4.5
|
|
244
|
+
set typing_at to now()
|
|
245
|
+
try
|
|
246
|
+
plugins.invoke(typing_pl, "typing", {"thread": lead["reply_thread"], "meta": ordered[length(ordered) - 1]["meta"]})
|
|
247
|
+
recover err
|
|
248
|
+
set typing_at to typing_at
|
|
249
|
+
typing()
|
|
250
|
+
task publish(kind, data, tag)
|
|
251
|
+
when kind == "busy"
|
|
252
|
+
typing()
|
|
253
|
+
when kind != "busy" and kind != "idle"
|
|
254
|
+
bus_publish(topic, {"kind": kind, "data": data, "tag": tag, "agent": lead["to"], "thread": lead["thread"]})
|
|
255
|
+
let hooks be {"mode": spec["mode"], "ask_fn": approve_queue, "on_event": publish}
|
|
256
|
+
let result be nothing
|
|
257
|
+
try
|
|
258
|
+
let o be runtime.open({"to": lead["to"], "thread": lead["thread"], "session": lead["session"], "text": "", "channel": lead["channel"], "meta": lead["meta"]}, hooks)
|
|
259
|
+
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"]})
|
|
260
|
+
when o["note"] != ""
|
|
261
|
+
publish("inbox", o["note"], "")
|
|
262
|
+
-- a mitad de turno: lo que llegó mientras el agente trabajaba entra antes de la próxima llamada al modelo
|
|
263
|
+
let prev be o["ctx"]["opts"]["inbox_fn"]
|
|
264
|
+
task mid(step, tag)
|
|
265
|
+
let msgs be []
|
|
266
|
+
let halt be false
|
|
267
|
+
when prev != nothing
|
|
268
|
+
let pi be call(prev, {"step": step, "tag": tag})
|
|
269
|
+
when pi != nothing
|
|
270
|
+
set msgs to pi["messages"]
|
|
271
|
+
set halt to pi["stop"]
|
|
272
|
+
each it in sort_by(take(k), (x) => sort_key(x))
|
|
273
|
+
set all to append(all, it)
|
|
274
|
+
let extra be when length(it["images"]) > 0 then " [+" + text(length(it["images"])) + " image(s), visible next turn]" otherwise ""
|
|
275
|
+
set msgs to append(msgs, it["text"] + extra)
|
|
276
|
+
when length(msgs) == 0 and not halt
|
|
277
|
+
give nothing
|
|
278
|
+
give {"messages": msgs, "stop": halt}
|
|
279
|
+
let ctx be o["ctx"]
|
|
280
|
+
set ctx["opts"] to loop.with_inbox(ctx["opts"], mid, "")
|
|
281
|
+
set o["ctx"] to ctx
|
|
282
|
+
let msgs be o["messages"]
|
|
283
|
+
each it in ordered
|
|
284
|
+
set msgs to append(msgs, user_msg(it))
|
|
285
|
+
let label be join(apply((it) => it["text"], ordered), " ⏎ ")
|
|
286
|
+
let r be runtime.turn(o, msgs, label, hooks)
|
|
287
|
+
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"]}
|
|
288
|
+
recover err
|
|
289
|
+
set result to {"agent": lead["to"], "thread": lead["thread"], "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
|
|
290
|
+
let ids be apply((it) => it["id"], all)
|
|
291
|
+
set result["batch"] to ids
|
|
292
|
+
set result["lead"] to lead["id"]
|
|
293
|
+
each it in all
|
|
294
|
+
state_set("mb:res:" + it["id"], result)
|
|
295
|
+
bus_publish(topic, {"kind": "done", "data": result, "tag": "", "agent": result["agent"], "thread": result["thread"]})
|
|
296
|
+
-- callbacks: uno por URL distinta del lote; cada job queda done (el que encabeza) o merged (los demás)
|
|
297
|
+
let urls be []
|
|
298
|
+
each it in all
|
|
299
|
+
when it["callback"] != "" and not contains(urls, it["callback"])
|
|
300
|
+
set urls to append(urls, it["callback"])
|
|
301
|
+
each u in urls
|
|
302
|
+
let mine be where(all, (it) => it["callback"] == u)
|
|
303
|
+
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"]}
|
|
304
|
+
let ok be post_callback(u, payload)
|
|
305
|
+
each it in mine
|
|
306
|
+
when it["job"]
|
|
307
|
+
let j be job(it["id"])
|
|
308
|
+
when j != nothing
|
|
309
|
+
set j["status"] to when it["id"] == mine[0]["id"] then payload["status"] otherwise "merged"
|
|
310
|
+
set j["merged_into"] to when it["id"] == mine[0]["id"] then nothing otherwise mine[0]["id"]
|
|
311
|
+
set j["result"] to result
|
|
312
|
+
set j["delivered"] to ok
|
|
313
|
+
set j["finished"] to format_time(now())
|
|
314
|
+
save_job(j)
|
|
315
|
+
-- canales (lib/channels.syn): UNA respuesta por lote y canal, por la acción `send` del plugin. El meta del último
|
|
316
|
+
-- mensaje (ids de la plataforma más recientes). Un error del agente no se le manda al cliente: queda en el log.
|
|
317
|
+
let chans be []
|
|
318
|
+
each it in all
|
|
319
|
+
when it["reply_channel"] != "" and not contains(chans, it["reply_channel"])
|
|
320
|
+
set chans to append(chans, it["reply_channel"])
|
|
321
|
+
each ch in chans
|
|
322
|
+
let mine be where(all, (it) => it["reply_channel"] == ch)
|
|
323
|
+
let last be mine[length(mine) - 1]
|
|
324
|
+
let sent be {"channel": ch, "ok": false, "output": ""}
|
|
325
|
+
when starts_with(result["stopped"], "error") or trim(result["text"]) == ""
|
|
326
|
+
set sent["output"] to "not sent: " + (when trim(result["text"]) == "" then "empty answer" otherwise result["stopped"])
|
|
327
|
+
otherwise
|
|
328
|
+
let pl be plugins.channel(ch)
|
|
329
|
+
when pl == nothing
|
|
330
|
+
set sent["output"] to "not sent: channel '" + ch + "' is not enabled anymore"
|
|
331
|
+
otherwise
|
|
332
|
+
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}))
|
|
333
|
+
set sent["output"] to out
|
|
334
|
+
set sent["ok"] to not starts_with(out, "ERROR")
|
|
335
|
+
when not file_exists(CHANNEL_LOG_DIR + "/" + ch + ".log")
|
|
336
|
+
write_file(CHANNEL_LOG_DIR + "/" + ch + ".log", "")
|
|
337
|
+
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")
|
|
338
|
+
bus_publish(topic, {"kind": "channel_sent", "data": sent, "tag": "", "agent": result["agent"], "thread": result["thread"]})
|
|
339
|
+
give result
|
|
340
|
+
|
|
341
|
+
export task work(spec_json)
|
|
342
|
+
require net
|
|
343
|
+
require exec
|
|
344
|
+
require time
|
|
345
|
+
require random
|
|
346
|
+
require file(".lampson")
|
|
347
|
+
require file(".lampson/*")
|
|
348
|
+
require file("workspace")
|
|
349
|
+
require file("workspace/*")
|
|
350
|
+
require file.read("skills")
|
|
351
|
+
require file.read("skills/*")
|
|
352
|
+
require file.read("plugins")
|
|
353
|
+
require file.read("plugins/*")
|
|
354
|
+
require file.read("agents")
|
|
355
|
+
require file.read("agents/*")
|
|
356
|
+
require file.read("memory")
|
|
357
|
+
require file.read("memory/*")
|
|
358
|
+
require env("LAMPSON_*")
|
|
359
|
+
require env("OS")
|
|
360
|
+
require secret("LAMPSON_*")
|
|
361
|
+
let spec be json_decode(spec_json)
|
|
362
|
+
let k be spec["key"]
|
|
363
|
+
let running be true
|
|
364
|
+
while running
|
|
365
|
+
settle(k, spec["buffer"])
|
|
366
|
+
let items be take(k)
|
|
367
|
+
when length(items) == 0
|
|
368
|
+
when release(k)
|
|
369
|
+
set running to false
|
|
370
|
+
otherwise
|
|
371
|
+
run_batch(k, spec, items)
|
|
372
|
+
give true
|
|
373
|
+
|
|
374
|
+
-- MIGA runtime (igual que agents.Child): un `agent` solo ve sus parámetros, las builtins y las tasks TOP-LEVEL del
|
|
375
|
+
-- entry. web.syn define `task lampson_mailbox_worker(spec_json) give mailbox.work(spec_json)`.
|
|
376
|
+
agent MailboxWorker
|
|
377
|
+
require net
|
|
378
|
+
require exec
|
|
379
|
+
require time
|
|
380
|
+
require random
|
|
381
|
+
require file(".lampson")
|
|
382
|
+
require file(".lampson/*")
|
|
383
|
+
require file("workspace")
|
|
384
|
+
require file("workspace/*")
|
|
385
|
+
require file.read("skills")
|
|
386
|
+
require file.read("skills/*")
|
|
387
|
+
require file.read("plugins")
|
|
388
|
+
require file.read("plugins/*")
|
|
389
|
+
require file.read("agents")
|
|
390
|
+
require file.read("agents/*")
|
|
391
|
+
require file("memory")
|
|
392
|
+
require file("memory/*")
|
|
393
|
+
require env("LAMPSON_*")
|
|
394
|
+
require env("OS")
|
|
395
|
+
require secret("LAMPSON_*")
|
|
396
|
+
lampson_mailbox_worker(spec_json)
|
|
397
|
+
|
|
398
|
+
-- ---------- lo que llama la puerta ----------
|
|
399
|
+
|
|
400
|
+
-- arma el item y lo encola; lanza el worker si hace falta. → {id, key}
|
|
401
|
+
-- opts: {mode, buffer, callback, job, reply_channel, reply_thread}
|
|
402
|
+
export task submit(sobre, opts)
|
|
403
|
+
require time
|
|
404
|
+
require random
|
|
405
|
+
require file.read("workspace")
|
|
406
|
+
require file.read("workspace/*")
|
|
407
|
+
require file.read("agents")
|
|
408
|
+
require file.read("agents/*")
|
|
409
|
+
let id be when contains(opts, "id") then opts["id"] otherwise new_id()
|
|
410
|
+
let k be key_of(sobre, id)
|
|
411
|
+
let sent be nothing
|
|
412
|
+
when contains(sobre["meta"], "sent_at")
|
|
413
|
+
set sent to sobre["meta"]["sent_at"]
|
|
414
|
+
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 ""}
|
|
415
|
+
when post(k, item)
|
|
416
|
+
let buf be opts["buffer"]
|
|
417
|
+
spawn MailboxWorker with spec_json = json_encode({"key": k, "mode": opts["mode"], "buffer": buf})
|
|
418
|
+
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
|
-
--
|
|
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
|
-
|
|
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
|
|
269
|
-
when
|
|
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
|
|
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
|
|
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}})
|