lampson 0.2.9 → 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/mobile.css +95 -0
- package/public/css/panel.css +2 -0
- package/public/index.html +12 -1
- package/public/js/app.js +1 -1
- package/public/js/engine.js +149 -0
- package/public/js/mobile.js +122 -0
- package/public/js/sessions.js +3 -1
- package/public/js/terminal.js +1 -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/api.syn
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
-- lib/api.syn — la API HTTP /v1 de un workspace (spec/engine.md, fase 2). Las rutas viven en web.syn; acá la lógica.
|
|
2
|
+
--
|
|
3
|
+
-- GET /w/<slug>/v1/agents los agentes que la key puede usar
|
|
4
|
+
-- POST /w/<slug>/v1/messages un sobre → respuesta. Tres formas:
|
|
5
|
+
-- {"to", "thread", "text", "images", "from", "meta"} → JSON con el resultado (espera el turno)
|
|
6
|
+
-- … + "stream": true → SSE: los mismos eventos que `lampson run --json`
|
|
7
|
+
-- … + "callback": "https://…" → 202 {job} enseguida; el resultado va por POST
|
|
8
|
+
-- al callback (canal `http`: WhatsApp, n8n…)
|
|
9
|
+
-- GET /w/<slug>/v1/jobs/<id> estado de un trabajo asíncrono
|
|
10
|
+
--
|
|
11
|
+
-- Auth: SIEMPRE `Authorization: Bearer lk_…` (lib/apikeys.syn), también por loopback: el hub reenvía /v1 sin pedir
|
|
12
|
+
-- passkey y este proceso confía en todo lo que le llega del hub, así que la key es la única puerta.
|
|
13
|
+
-- Todo mensaje pasa por el buzón de su conversación (lib/mailbox.syn): fila por (agente, thread), espera de silencio
|
|
14
|
+
-- ("buffer" del agente; default 3 s / tope 15 s) y lo que llega a mitad de turno entra al turno en curso. Los
|
|
15
|
+
-- mensajes de una ráfaga reciben la MISMA respuesta, con "batch" (ids del lote) y "lead" (el que lo encabeza).
|
|
16
|
+
-- Permisos: el modo del agente, o strict si no dice. En `ask`, la aprobación sale por la cola de lib/approvals.syn
|
|
17
|
+
-- (UI, link firmado al webhook, /approve en la terminal) y vence → denegado. Nunca se auto-aprueba.
|
|
18
|
+
-- Callback: UN POST por lote y URL: {job, jobs, batch, status, agent, thread, session, text, steps, usage, stopped,
|
|
19
|
+
-- meta}; con LAMPSON_WEBHOOK_SECRET va firmado (X-Lampson-Signature: sha256=<hmac hex>). Los demás jobs del lote
|
|
20
|
+
-- quedan "merged" (merged_into = el que encabeza).
|
|
21
|
+
|
|
22
|
+
use "./runtime.syn" as runtime
|
|
23
|
+
use "./apikeys.syn" as apikeys
|
|
24
|
+
use "./mailbox.syn" as mailbox
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
-- la key del header Authorization (o nothing)
|
|
28
|
+
export task bearer_of(h)
|
|
29
|
+
let a be ""
|
|
30
|
+
each k in keys(h)
|
|
31
|
+
when lower(k) == "authorization"
|
|
32
|
+
set a to text(h[k])
|
|
33
|
+
when starts_with(lower(a), "bearer ")
|
|
34
|
+
give trim(slice(a, 7, length(a)))
|
|
35
|
+
give nothing
|
|
36
|
+
|
|
37
|
+
-- {ok, key, status, error}: la key válida, o por qué no
|
|
38
|
+
export task authorize(h)
|
|
39
|
+
require time
|
|
40
|
+
require file(".lampson")
|
|
41
|
+
require file(".lampson/*")
|
|
42
|
+
let rec be apikeys.check(bearer_of(h))
|
|
43
|
+
when rec == nothing
|
|
44
|
+
give {"ok": false, "key": nothing, "status": 401, "error": "missing or invalid API key (Authorization: Bearer lk_…; create one with `lampson key add`)", "retry_after": 0}
|
|
45
|
+
-- rate limit por key: ventana de un minuto (estado de serve, compartido por todos los handlers)
|
|
46
|
+
when rec["rate"] > 0
|
|
47
|
+
let win be floor(now() / 60)
|
|
48
|
+
let n be state_incr("rl:" + rec["id"] + ":" + text(win), 1)
|
|
49
|
+
when n == 1
|
|
50
|
+
state_delete("rl:" + rec["id"] + ":" + text(win - 1))
|
|
51
|
+
when n > rec["rate"]
|
|
52
|
+
give {"ok": false, "key": rec, "status": 429, "error": "rate limit: " + text(rec["rate"]) + " requests per minute for this API key", "retry_after": 60 - floor(now() - win * 60)}
|
|
53
|
+
give {"ok": true, "key": rec, "status": 200, "error": "", "retry_after": 0}
|
|
54
|
+
|
|
55
|
+
-- la respuesta de error de authorize (429 con Retry-After)
|
|
56
|
+
export task refuse(a)
|
|
57
|
+
let r be fail(a["status"], a["error"])
|
|
58
|
+
when a["status"] == 429
|
|
59
|
+
give with_header(r, "Retry-After", text(a["retry_after"]))
|
|
60
|
+
give r
|
|
61
|
+
|
|
62
|
+
-- los agentes que esta key puede usar: [{id, description}]
|
|
63
|
+
export task agents_for(rec)
|
|
64
|
+
require file.read("workspace")
|
|
65
|
+
require file.read("workspace/*")
|
|
66
|
+
require file.read("agents")
|
|
67
|
+
require file.read("agents/*")
|
|
68
|
+
let out be []
|
|
69
|
+
each id in runtime.names()
|
|
70
|
+
when apikeys.allows(rec, id)
|
|
71
|
+
set out to append(out, {"id": id, "description": runtime.get(id)["description"]})
|
|
72
|
+
give out
|
|
73
|
+
|
|
74
|
+
task field(m, k, fallback)
|
|
75
|
+
when contains(m, k)
|
|
76
|
+
when m[k] != nothing
|
|
77
|
+
give m[k]
|
|
78
|
+
give fallback
|
|
79
|
+
|
|
80
|
+
-- {ok, sobre, callback, stream, status, error}: el body de POST /v1/messages ya validado contra la key
|
|
81
|
+
export task parse(body, rec)
|
|
82
|
+
require env("LAMPSON_*")
|
|
83
|
+
require file.read("workspace")
|
|
84
|
+
require file.read("workspace/*")
|
|
85
|
+
require file.read("agents")
|
|
86
|
+
require file.read("agents/*")
|
|
87
|
+
when body == nothing or type_of(body) != "map"
|
|
88
|
+
give {"ok": false, "status": 400, "error": "body must be a JSON object"}
|
|
89
|
+
let msg be text(field(body, "text", ""))
|
|
90
|
+
when trim(msg) == ""
|
|
91
|
+
give {"ok": false, "status": 400, "error": "text is required"}
|
|
92
|
+
let target be lower(text(field(body, "to", runtime.default_agent())))
|
|
93
|
+
when not contains(runtime.names(), target)
|
|
94
|
+
give {"ok": false, "status": 404, "error": "no agent named '" + target + "'"}
|
|
95
|
+
when not apikeys.allows(rec, target)
|
|
96
|
+
give {"ok": false, "status": 403, "error": "this API key cannot use agent '" + target + "'"}
|
|
97
|
+
let cb be text(field(body, "callback", ""))
|
|
98
|
+
when cb != "" and not (starts_with(cb, "https://") or starts_with(cb, "http://"))
|
|
99
|
+
give {"ok": false, "status": 400, "error": "callback must be an http(s) URL"}
|
|
100
|
+
when cb != "" and not apikeys.callback_allowed(rec, cb)
|
|
101
|
+
give {"ok": false, "status": 403, "error": "this API key cannot send callbacks to " + cb + " (allowed: " + join(rec["callbacks"], ", ") + ")"}
|
|
102
|
+
let images be field(body, "images", [])
|
|
103
|
+
when type_of(images) != "list"
|
|
104
|
+
set images to []
|
|
105
|
+
let from be field(body, "from", {})
|
|
106
|
+
when type_of(from) != "map"
|
|
107
|
+
set from to {}
|
|
108
|
+
let meta be field(body, "meta", {})
|
|
109
|
+
when type_of(meta) != "map"
|
|
110
|
+
set meta to {}
|
|
111
|
+
-- la hora en que el cliente escribió (unix s), si el canal la da: ordena una ráfaga que llegó desordenada
|
|
112
|
+
when contains(body, "sent_at") and body["sent_at"] != nothing
|
|
113
|
+
set meta["sent_at"] to body["sent_at"]
|
|
114
|
+
let sobre be {"to": target, "thread": text(field(body, "thread", "")), "session": text(field(body, "session", "")), "from": from, "text": msg, "images": images, "channel": text(field(body, "channel", "http")), "meta": meta}
|
|
115
|
+
give {"ok": true, "status": 200, "error": "", "sobre": sobre, "callback": cb, "stream": field(body, "stream", false) == true}
|
|
116
|
+
|
|
117
|
+
-- el modo de un agente por la API: el suyo, y si no dice → strict (nadie en la request para preguntarle)
|
|
118
|
+
export task mode_for(spec)
|
|
119
|
+
give when spec != nothing and spec["permission"] != "" then "" otherwise "strict"
|
|
120
|
+
|
|
121
|
+
-- opts del buzón (lib/mailbox.syn) para un sobre ya validado
|
|
122
|
+
export task mailbox_opts(sobre)
|
|
123
|
+
require file.read("workspace")
|
|
124
|
+
require file.read("workspace/*")
|
|
125
|
+
require file.read("agents")
|
|
126
|
+
require file.read("agents/*")
|
|
127
|
+
let spec be runtime.get(sobre["to"])
|
|
128
|
+
give {"mode": mode_for(spec), "buffer": mailbox.buffer_of(spec, mailbox.DEFAULT_BUFFER)}
|
|
129
|
+
|
|
130
|
+
-- registro de un trabajo con callback (lo completa el worker del buzón al entregar)
|
|
131
|
+
export task create_job(id, rec, sobre, callback)
|
|
132
|
+
require time
|
|
133
|
+
require file(".lampson")
|
|
134
|
+
require file(".lampson/*")
|
|
135
|
+
mailbox.save_job({"job": id, "status": "queued", "key": rec["id"], "agent": sobre["to"], "thread": sobre["thread"], "callback": callback, "created": format_time(now()), "result": nothing, "delivered": false, "merged_into": nothing})
|
|
136
|
+
|
|
137
|
+
export task job(id)
|
|
138
|
+
require file.read(".lampson")
|
|
139
|
+
require file.read(".lampson/*")
|
|
140
|
+
give mailbox.job(id)
|
|
141
|
+
|
|
142
|
+
-- MCP por HTTP (lib/mcp_server.syn): un `ask` pasa por el buzón de su conversación. Entre agentes no hay espera de
|
|
143
|
+
-- silencio salvo que el agente la configure (`buffer`): la fila sí, siempre.
|
|
144
|
+
export task mcp_deliver(sobre, mode)
|
|
145
|
+
require time
|
|
146
|
+
require random
|
|
147
|
+
require file.read("workspace")
|
|
148
|
+
require file.read("workspace/*")
|
|
149
|
+
require file.read("agents")
|
|
150
|
+
require file.read("agents/*")
|
|
151
|
+
let spec be runtime.get(sobre["to"])
|
|
152
|
+
let s be mailbox.submit(sobre, {"mode": mode, "buffer": mailbox.buffer_of(spec, false)})
|
|
153
|
+
give mailbox.wait(s["id"])
|
package/lib/apikeys.syn
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
-- lib/apikeys.syn — API keys de la API /v1 (spec/engine.md, fase 2)
|
|
2
|
+
--
|
|
3
|
+
-- Una key = acceso por HTTP a ciertos agentes de ESTE workspace. Se guarda solo su hash (sha256), en el estado del
|
|
4
|
+
-- workspace (.lampson/api_keys.json, al lado de las sesiones): nunca en la carpeta del proyecto, que puede ir a git.
|
|
5
|
+
-- La key en claro se muestra UNA vez, al crearla (`lampson key add`).
|
|
6
|
+
--
|
|
7
|
+
-- create(name, agents) → {id, key, name, agents} agents: ["tienda"] o ["*"] (todos los elegibles)
|
|
8
|
+
-- create_with(name, agents, {rate, callbacks}) rate = pedidos/minuto (default 120; 0 = sin límite);
|
|
9
|
+
-- callbacks = prefijos de URL permitidos ([] = cualquiera)
|
|
10
|
+
-- check(key) → registro sin hash | nothing (y anota last_used)
|
|
11
|
+
-- allows(rec, agent) → bool
|
|
12
|
+
-- list() / remove(id)
|
|
13
|
+
|
|
14
|
+
export let FILE be ".lampson/api_keys.json"
|
|
15
|
+
export let PREFIX be "lk_"
|
|
16
|
+
export let DEFAULT_RATE be 120
|
|
17
|
+
|
|
18
|
+
task hash_of(key)
|
|
19
|
+
give decode(sha256("lampson-api:" + key), "hex")
|
|
20
|
+
|
|
21
|
+
task load()
|
|
22
|
+
require file.read(".lampson")
|
|
23
|
+
require file.read(".lampson/*")
|
|
24
|
+
try
|
|
25
|
+
let d be json_decode(read_file(FILE))
|
|
26
|
+
when contains(d, "keys")
|
|
27
|
+
give d["keys"]
|
|
28
|
+
recover err
|
|
29
|
+
give []
|
|
30
|
+
give []
|
|
31
|
+
|
|
32
|
+
task store(keys_list)
|
|
33
|
+
require file(".lampson")
|
|
34
|
+
require file(".lampson/*")
|
|
35
|
+
write_file(FILE, json_encode({"keys": keys_list}))
|
|
36
|
+
|
|
37
|
+
task public(k)
|
|
38
|
+
give {"id": k["id"], "name": k["name"], "agents": k["agents"], "created": k["created"], "last_used": k["last_used"], "rate": when contains(k, "rate") then k["rate"] otherwise DEFAULT_RATE, "callbacks": when contains(k, "callbacks") then k["callbacks"] otherwise []}
|
|
39
|
+
|
|
40
|
+
export task create(name, agents)
|
|
41
|
+
require time
|
|
42
|
+
require random
|
|
43
|
+
require file(".lampson")
|
|
44
|
+
require file(".lampson/*")
|
|
45
|
+
give create_with(name, agents, {})
|
|
46
|
+
|
|
47
|
+
export task create_with(name, agents, opts)
|
|
48
|
+
require time
|
|
49
|
+
require random
|
|
50
|
+
require file(".lampson")
|
|
51
|
+
require file(".lampson/*")
|
|
52
|
+
let ag be when agents == nothing or length(agents) == 0 then ["*"] otherwise agents
|
|
53
|
+
let rate be when contains(opts, "rate") and opts["rate"] != nothing then floor(number(opts["rate"])) otherwise DEFAULT_RATE
|
|
54
|
+
let cbs be when contains(opts, "callbacks") and opts["callbacks"] != nothing then opts["callbacks"] otherwise []
|
|
55
|
+
let key be PREFIX + token(24)
|
|
56
|
+
let id be "k" + slice(token(16), 0, 8)
|
|
57
|
+
let rec be {"id": id, "name": text(name), "agents": ag, "hash": hash_of(key), "created": format_time(now()), "last_used": nothing, "rate": rate, "callbacks": cbs}
|
|
58
|
+
store(append(load(), rec))
|
|
59
|
+
give {"id": id, "key": key, "name": rec["name"], "agents": ag, "rate": rate, "callbacks": cbs}
|
|
60
|
+
|
|
61
|
+
-- ¿esta key puede pedir un callback a esta URL? sin lista = cualquiera; con lista = solo esos prefijos
|
|
62
|
+
export task callback_allowed(rec, url)
|
|
63
|
+
when not contains(rec, "callbacks") or length(rec["callbacks"]) == 0
|
|
64
|
+
give true
|
|
65
|
+
each pre in rec["callbacks"]
|
|
66
|
+
when starts_with(url, pre)
|
|
67
|
+
give true
|
|
68
|
+
give false
|
|
69
|
+
|
|
70
|
+
export task list()
|
|
71
|
+
require file.read(".lampson")
|
|
72
|
+
require file.read(".lampson/*")
|
|
73
|
+
give apply((k) => public(k), load())
|
|
74
|
+
|
|
75
|
+
export task remove(id)
|
|
76
|
+
require file(".lampson")
|
|
77
|
+
require file(".lampson/*")
|
|
78
|
+
let all be load()
|
|
79
|
+
let rest be where(all, (k) => k["id"] != id)
|
|
80
|
+
when length(rest) == length(all)
|
|
81
|
+
give false
|
|
82
|
+
store(rest)
|
|
83
|
+
give true
|
|
84
|
+
|
|
85
|
+
-- el registro de la key (sin hash) o nothing. Anota last_used como mucho una vez por minuto (no reescribir en cada request)
|
|
86
|
+
export task check(key)
|
|
87
|
+
require time
|
|
88
|
+
require file(".lampson")
|
|
89
|
+
require file(".lampson/*")
|
|
90
|
+
when key == nothing
|
|
91
|
+
give nothing
|
|
92
|
+
let k be text(key)
|
|
93
|
+
when not starts_with(k, PREFIX)
|
|
94
|
+
give nothing
|
|
95
|
+
let h be hash_of(k)
|
|
96
|
+
let all be load()
|
|
97
|
+
let found be nothing
|
|
98
|
+
let changed be false
|
|
99
|
+
let out be []
|
|
100
|
+
each r in all
|
|
101
|
+
when r["hash"] == h
|
|
102
|
+
set found to public(r)
|
|
103
|
+
let stamp be format_time(now(), "%Y-%m-%dT%H:%M")
|
|
104
|
+
when r["last_used"] == nothing or slice(text(r["last_used"]), 0, 16) != stamp
|
|
105
|
+
set r["last_used"] to format_time(now())
|
|
106
|
+
set changed to true
|
|
107
|
+
set out to append(out, r)
|
|
108
|
+
when changed
|
|
109
|
+
store(out)
|
|
110
|
+
give found
|
|
111
|
+
|
|
112
|
+
export task allows(rec, agent)
|
|
113
|
+
when rec == nothing
|
|
114
|
+
give false
|
|
115
|
+
give contains(rec["agents"], "*") or contains(rec["agents"], agent)
|
package/lib/channels.syn
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
-- lib/channels.syn — canales: WhatsApp, Telegram, Slack, Chatwoot… como PLUGINS (spec/engine.md, fase 4)
|
|
2
|
+
--
|
|
3
|
+
-- Lampson no sabe qué es ninguna plataforma. Define un contrato y cada canal es un plugin (cualquier lenguaje, o
|
|
4
|
+
-- Synsema con techo de capacidades) con "channel" en su plugin.json y dos acciones:
|
|
5
|
+
--
|
|
6
|
+
-- receive Lampson le pasa el webhook CRUDO de la plataforma (PLUGIN_ARGS):
|
|
7
|
+
-- {"method", "path", "query", "headers", "body"} body = el texto exacto (para verificar firmas)
|
|
8
|
+
-- y el plugin imprime por stdout UN JSON:
|
|
9
|
+
-- {"messages": [{"thread", "text", "sent_at"?, "from"?, "images"?, "meta"?, "agent"?}],
|
|
10
|
+
-- "http": {"status", "body", "content_type"}?} ← lo que Lampson le responde a la plataforma
|
|
11
|
+
-- Sin mensajes (un evento que no interesa, una verificación de webhook) → {"messages": []} o un "http".
|
|
12
|
+
-- send Lampson le pasa la respuesta del agente: {"thread", "text", "meta", "agent", "session", "batch"}
|
|
13
|
+
-- (thread y meta = los que devolvió receive para el último mensaje del lote) y el plugin la manda.
|
|
14
|
+
-- Imprime lo que quiera; una salida que empieza con "ERROR" cuenta como fallo (queda en el log).
|
|
15
|
+
-- typing (opcional, con "channel": {"typing": true}) el "escribiendo…" de la plataforma: {"thread", "meta"}.
|
|
16
|
+
-- Lampson la llama al empezar cada turno y la renueva cada ~4,5 s mientras el modelo trabaja.
|
|
17
|
+
-- setup (opcional) {"mode": "webhook", "webhook_url"} registra el webhook en la plataforma; {"mode": "poll"} lo
|
|
18
|
+
-- quita (los dos modos no conviven en Telegram). Lo llama `lampson channel setup <canal>`.
|
|
19
|
+
-- poll (opcional, con "channel": {"poll": true}) MODO SIN URL PÚBLICA: {"cursor"} → el plugin le pide a la
|
|
20
|
+
-- plataforma los mensajes nuevos (espera larga) e imprime {"messages": [...], "cursor": <el siguiente>}.
|
|
21
|
+
-- `lampson channel setup` lo elige solo cuando este Lampson no tiene URL pública; el proceso del
|
|
22
|
+
-- workspace mantiene un agente por canal pidiendo en bucle (cursor en .lampson/channels/<canal>.cursor).
|
|
23
|
+
-- Imágenes: un mensaje puede traer "images": [{"media_type": "image/jpeg", "data": "<base64>"}] — los modelos con
|
|
24
|
+
-- visión las ven; a los demás el proveedor les deja una nota.
|
|
25
|
+
--
|
|
26
|
+
-- Lampson pone todo lo demás: la ruta del webhook (POST/GET /w/<slug>/ch/<canal>, que el hub reenvía sin passkey:
|
|
27
|
+
-- la firma de la plataforma la verifica el plugin en receive), el buzón de cada conversación (lib/mailbox.syn:
|
|
28
|
+
-- fila, espera de silencio, mensajes a mitad de turno), las sesiones por cliente, los permisos y UNA respuesta por
|
|
29
|
+
-- lote. A la plataforma se le contesta enseguida (no espera al agente).
|
|
30
|
+
--
|
|
31
|
+
-- El thread de la sesión es "<canal>:<thread>" (un mismo id en dos canales no se mezcla). El agente: el que diga el
|
|
32
|
+
-- mensaje, si no LAMPSON_CHANNEL_<CANAL>_AGENT (.env), si no el del manifiesto ("channel": {"agent"}), si no el
|
|
33
|
+
-- agente por defecto. Secretos del canal: "config" en plugin.json (PLUGIN_<X> = LAMPSON_<X>).
|
|
34
|
+
-- Log por canal: .lampson/channels/<canal>.log (lo que entró y lo que salió).
|
|
35
|
+
|
|
36
|
+
use "./plugins.syn" as plugins
|
|
37
|
+
use "./mailbox.syn" as mailbox
|
|
38
|
+
use "./runtime.syn" as runtime
|
|
39
|
+
|
|
40
|
+
task log(name, line)
|
|
41
|
+
require time
|
|
42
|
+
require file(".lampson")
|
|
43
|
+
require file(".lampson/*")
|
|
44
|
+
let f be mailbox.CHANNEL_LOG_DIR + "/" + name + ".log"
|
|
45
|
+
when not file_exists(f)
|
|
46
|
+
write_file(f, "")
|
|
47
|
+
append_file(f, format_time(now()) + " " + replace(line, "\n", " ") + "\n")
|
|
48
|
+
|
|
49
|
+
task jresp(status, m)
|
|
50
|
+
give {"status": status, "body": json_encode(m), "ctype": "application/json", "accepted": 0}
|
|
51
|
+
|
|
52
|
+
-- la salida del plugin → {ok, data, error}: el stdout entero como JSON, o su última línea JSON (por si imprimió
|
|
53
|
+
-- algo antes)
|
|
54
|
+
export task parse_output(raw)
|
|
55
|
+
let t be trim(text(raw))
|
|
56
|
+
when starts_with(t, "ERROR")
|
|
57
|
+
give {"ok": false, "data": nothing, "error": slice(t, 0, 300)}
|
|
58
|
+
try
|
|
59
|
+
give {"ok": true, "data": json_decode(t), "error": ""}
|
|
60
|
+
recover err
|
|
61
|
+
let lines be where(split(replace(t, "\r", ""), "\n"), (l) => starts_with(trim(l), "{"))
|
|
62
|
+
when length(lines) > 0
|
|
63
|
+
try
|
|
64
|
+
give {"ok": true, "data": json_decode(trim(lines[length(lines) - 1])), "error": ""}
|
|
65
|
+
recover err2
|
|
66
|
+
give {"ok": false, "data": nothing, "error": "receive did not print JSON: " + slice(t, 0, 200)}
|
|
67
|
+
give {"ok": false, "data": nothing, "error": "receive did not print JSON: " + slice(t, 0, 200)}
|
|
68
|
+
|
|
69
|
+
export task agent_for(name, l, m)
|
|
70
|
+
require env("LAMPSON_*")
|
|
71
|
+
when contains(m, "agent") and m["agent"] != nothing and text(m["agent"]) != ""
|
|
72
|
+
give lower(text(m["agent"]))
|
|
73
|
+
let e be env("LAMPSON_CHANNEL_" + upper(replace(name, "-", "_")) + "_AGENT", "")
|
|
74
|
+
when e != ""
|
|
75
|
+
give lower(e)
|
|
76
|
+
when l["channel"]["agent"] != ""
|
|
77
|
+
give l["channel"]["agent"]
|
|
78
|
+
give runtime.default_agent()
|
|
79
|
+
|
|
80
|
+
-- un webhook entrante → {status, body, ctype, accepted}
|
|
81
|
+
export task handle(name, req)
|
|
82
|
+
require exec
|
|
83
|
+
require time
|
|
84
|
+
require random
|
|
85
|
+
require file(".lampson")
|
|
86
|
+
require file(".lampson/*")
|
|
87
|
+
require file.read("plugins")
|
|
88
|
+
require file.read("plugins/*")
|
|
89
|
+
require file.read("agents")
|
|
90
|
+
require file.read("agents/*")
|
|
91
|
+
require file("workspace")
|
|
92
|
+
require file("workspace/*")
|
|
93
|
+
require env("LAMPSON_*")
|
|
94
|
+
let l be plugins.channel(name)
|
|
95
|
+
when l == nothing
|
|
96
|
+
give jresp(404, {"error": "no enabled channel named '" + name + "' (turn it on: /plugins on " + name + ")"})
|
|
97
|
+
let p be parse_output(plugins.invoke(l, "receive", req))
|
|
98
|
+
when not p["ok"]
|
|
99
|
+
log(name, "RECV-ERROR " + p["error"])
|
|
100
|
+
give jresp(500, {"error": "the channel plugin failed: " + p["error"]})
|
|
101
|
+
let d be p["data"]
|
|
102
|
+
let msgs be when type_of(d) == "map" and contains(d, "messages") and type_of(d["messages"]) == "list" then d["messages"] otherwise []
|
|
103
|
+
let accepted be route_messages(name, l, msgs)
|
|
104
|
+
-- lo que el plugin quiere que se le responda a la plataforma (verificación de webhook, un 200 específico…)
|
|
105
|
+
when type_of(d) == "map" and contains(d, "http") and type_of(d["http"]) == "map"
|
|
106
|
+
let h be d["http"]
|
|
107
|
+
let body be when contains(h, "body") and h["body"] != nothing then (when type_of(h["body"]) == "text" then h["body"] otherwise json_encode(h["body"])) otherwise ""
|
|
108
|
+
give {"status": when contains(h, "status") then floor(number(h["status"])) otherwise 200, "body": body, "ctype": when contains(h, "content_type") then text(h["content_type"]) otherwise "text/plain", "accepted": accepted}
|
|
109
|
+
give {"status": 200, "body": json_encode({"ok": true, "accepted": accepted}), "ctype": "application/json", "accepted": accepted}
|
|
110
|
+
|
|
111
|
+
-- los mensajes que devolvió receive o poll → al buzón de cada conversación; cuántos entraron
|
|
112
|
+
export task route_messages(name, l, msgs)
|
|
113
|
+
require exec
|
|
114
|
+
require time
|
|
115
|
+
require random
|
|
116
|
+
require file(".lampson")
|
|
117
|
+
require file(".lampson/*")
|
|
118
|
+
require file.read("plugins")
|
|
119
|
+
require file.read("plugins/*")
|
|
120
|
+
require file.read("agents")
|
|
121
|
+
require file.read("agents/*")
|
|
122
|
+
require file("workspace")
|
|
123
|
+
require file("workspace/*")
|
|
124
|
+
require env("LAMPSON_*")
|
|
125
|
+
let names be runtime.names()
|
|
126
|
+
let accepted be 0
|
|
127
|
+
each m in msgs
|
|
128
|
+
let th be when contains(m, "thread") and m["thread"] != nothing then text(m["thread"]) otherwise ""
|
|
129
|
+
let tx be when contains(m, "text") and m["text"] != nothing then text(m["text"]) otherwise ""
|
|
130
|
+
let ag be agent_for(name, l, m)
|
|
131
|
+
when th == "" or trim(tx) == ""
|
|
132
|
+
log(name, "SKIP a message without thread or text")
|
|
133
|
+
otherwise when not contains(names, ag)
|
|
134
|
+
log(name, "SKIP no agent named '" + ag + "' (set LAMPSON_CHANNEL_" + upper(replace(name, "-", "_")) + "_AGENT or channel.agent)")
|
|
135
|
+
otherwise
|
|
136
|
+
let meta be when contains(m, "meta") and type_of(m["meta"]) == "map" then m["meta"] otherwise {}
|
|
137
|
+
when contains(m, "sent_at") and m["sent_at"] != nothing
|
|
138
|
+
set meta["sent_at"] to m["sent_at"]
|
|
139
|
+
let sobre be {"to": ag, "thread": name + ":" + th, "session": "", "from": when contains(m, "from") and type_of(m["from"]) == "map" then m["from"] otherwise {}, "text": tx, "images": when contains(m, "images") and type_of(m["images"]) == "list" then m["images"] otherwise [], "channel": name, "meta": meta}
|
|
140
|
+
let spec be runtime.get(ag)
|
|
141
|
+
mailbox.submit(sobre, {"mode": when spec["permission"] != "" then "" otherwise "strict", "buffer": mailbox.buffer_of(spec, mailbox.DEFAULT_BUFFER), "reply_channel": name, "reply_thread": th})
|
|
142
|
+
log(name, "RECV " + th + " → " + ag + " " + slice(tx, 0, 120))
|
|
143
|
+
set accepted to accepted + 1
|
|
144
|
+
give accepted
|
|
145
|
+
|
|
146
|
+
-- ---------- configuración (CLI `lampson channel …` y el panel Canales de la web) ----------
|
|
147
|
+
|
|
148
|
+
-- la URL del webhook de un canal: la pública si hay, si no la local del hub
|
|
149
|
+
export task webhook_url(name, pub, slug)
|
|
150
|
+
give (when pub != "" then pub otherwise "http://127.0.0.1:8080") + "/w/" + (when slug == "" then "local" otherwise slug) + "/ch/" + name
|
|
151
|
+
|
|
152
|
+
-- `setup`: con URL pública registra el webhook; sin ella, modo poll si el canal lo sabe hacer → {code, out}
|
|
153
|
+
export task setup_channel(name, pub, slug)
|
|
154
|
+
require exec
|
|
155
|
+
require time
|
|
156
|
+
require random
|
|
157
|
+
require file(".lampson")
|
|
158
|
+
require file(".lampson/*")
|
|
159
|
+
require file.read("plugins")
|
|
160
|
+
require file.read("plugins/*")
|
|
161
|
+
require file.read("agents")
|
|
162
|
+
require file.read("agents/*")
|
|
163
|
+
require file("workspace")
|
|
164
|
+
require file("workspace/*")
|
|
165
|
+
require env("LAMPSON_*")
|
|
166
|
+
let l be plugins.channel(name)
|
|
167
|
+
when l == nothing
|
|
168
|
+
give {"code": 2, "out": "the channel " + name + " is off (or is not a channel): turn it on first"}
|
|
169
|
+
when pub == "" and l["channel"]["poll"]
|
|
170
|
+
set_mode(name, "poll")
|
|
171
|
+
let pout be trim(text(plugins.invoke(l, "setup", {"mode": "poll"})))
|
|
172
|
+
give {"code": when starts_with(pout, "ERROR") then 1 otherwise 0, "out": pout + "\nmodo sin URL pública: el proceso del workspace le pide los mensajes a " + name + " (arranca solo con el workspace; `lampson --hub start` si está apagado)"}
|
|
173
|
+
when pub == ""
|
|
174
|
+
give {"code": 2, "out": "hace falta una URL pública (https) para que " + name + " llegue a este Lampson: `lampson --domain …`, un túnel, o LAMPSON_PUBLIC_URL en .env"}
|
|
175
|
+
set_mode(name, "webhook")
|
|
176
|
+
let out be trim(text(plugins.invoke(l, "setup", {"mode": "webhook", "webhook_url": webhook_url(name, pub, slug)})))
|
|
177
|
+
when contains(out, "unknown action 'setup'")
|
|
178
|
+
give {"code": 0, "out": "el canal " + name + " se configura desde la plataforma: pegá esta URL como webhook → " + webhook_url(name, pub, slug)}
|
|
179
|
+
give {"code": when starts_with(out, "ERROR") then 1 otherwise 0, "out": out}
|
|
180
|
+
|
|
181
|
+
-- cada canal instalado, para la UI: {name, description, enabled, error, agent, mode, webhook_url, poll, typing, log}
|
|
182
|
+
export task summary(pub, slug)
|
|
183
|
+
require exec
|
|
184
|
+
require time
|
|
185
|
+
require random
|
|
186
|
+
require file(".lampson")
|
|
187
|
+
require file(".lampson/*")
|
|
188
|
+
require file.read("plugins")
|
|
189
|
+
require file.read("plugins/*")
|
|
190
|
+
require file.read("agents")
|
|
191
|
+
require file.read("agents/*")
|
|
192
|
+
require file("workspace")
|
|
193
|
+
require file("workspace/*")
|
|
194
|
+
require env("LAMPSON_*")
|
|
195
|
+
let out be []
|
|
196
|
+
each l in where(plugins.all(), (x) => x["channel"] != nothing)
|
|
197
|
+
let lines be []
|
|
198
|
+
try
|
|
199
|
+
let raw be read_file(mailbox.CHANNEL_LOG_DIR + "/" + l["name"] + ".log")
|
|
200
|
+
let all_lines be where(split(replace(raw, "\r", ""), "\n"), (x) => trim(x) != "")
|
|
201
|
+
set lines to when length(all_lines) > 12 then slice(all_lines, length(all_lines) - 12, length(all_lines)) otherwise all_lines
|
|
202
|
+
recover err
|
|
203
|
+
set lines to []
|
|
204
|
+
set out to append(out, {"name": l["name"], "description": l["description"], "enabled": l["enabled"], "error": l["error"], "agent": when l["error"] == nothing then agent_for(l["name"], l, {}) otherwise "", "mode": mode_of(l["name"]), "webhook_url": webhook_url(l["name"], pub, slug), "public": pub != "", "poll": l["channel"]["poll"], "typing": l["channel"]["typing"], "scope": l["scope"], "log": lines})
|
|
205
|
+
give out
|
|
206
|
+
|
|
207
|
+
-- ---------- modo sin URL pública (poll) ----------
|
|
208
|
+
|
|
209
|
+
task modes_file()
|
|
210
|
+
give mailbox.CHANNEL_LOG_DIR + "/modes.json"
|
|
211
|
+
|
|
212
|
+
export task mode_of(name)
|
|
213
|
+
require file.read(".lampson")
|
|
214
|
+
require file.read(".lampson/*")
|
|
215
|
+
try
|
|
216
|
+
let d be json_decode(read_file(modes_file()))
|
|
217
|
+
when contains(d, name)
|
|
218
|
+
give text(d[name])
|
|
219
|
+
recover err
|
|
220
|
+
give "webhook"
|
|
221
|
+
give "webhook"
|
|
222
|
+
|
|
223
|
+
export task set_mode(name, mode)
|
|
224
|
+
require file(".lampson")
|
|
225
|
+
require file(".lampson/*")
|
|
226
|
+
let d be {}
|
|
227
|
+
try
|
|
228
|
+
set d to json_decode(read_file(modes_file()))
|
|
229
|
+
recover err
|
|
230
|
+
set d to {}
|
|
231
|
+
set d[name] to mode
|
|
232
|
+
write_file(modes_file(), json_encode(d))
|
|
233
|
+
give mode
|
|
234
|
+
|
|
235
|
+
task cursor_file(name)
|
|
236
|
+
give mailbox.CHANNEL_LOG_DIR + "/" + name + ".cursor"
|
|
237
|
+
|
|
238
|
+
-- una vuelta: pide los mensajes nuevos al plugin y los manda al buzón → {ok, n, error}
|
|
239
|
+
export task poll_once(name)
|
|
240
|
+
require exec
|
|
241
|
+
require time
|
|
242
|
+
require random
|
|
243
|
+
require file(".lampson")
|
|
244
|
+
require file(".lampson/*")
|
|
245
|
+
require file.read("plugins")
|
|
246
|
+
require file.read("plugins/*")
|
|
247
|
+
require file.read("agents")
|
|
248
|
+
require file.read("agents/*")
|
|
249
|
+
require file("workspace")
|
|
250
|
+
require file("workspace/*")
|
|
251
|
+
require env("LAMPSON_*")
|
|
252
|
+
let l be plugins.channel(name)
|
|
253
|
+
when l == nothing
|
|
254
|
+
give {"ok": false, "n": 0, "error": "channel off"}
|
|
255
|
+
let cursor be nothing
|
|
256
|
+
try
|
|
257
|
+
set cursor to json_decode(read_file(cursor_file(name)))["cursor"]
|
|
258
|
+
recover err
|
|
259
|
+
set cursor to nothing
|
|
260
|
+
let p be parse_output(plugins.invoke(l, "poll", {"cursor": cursor}))
|
|
261
|
+
when not p["ok"]
|
|
262
|
+
log(name, "POLL-ERROR " + p["error"])
|
|
263
|
+
give {"ok": false, "n": 0, "error": p["error"]}
|
|
264
|
+
let d be p["data"]
|
|
265
|
+
let msgs be when type_of(d) == "map" and contains(d, "messages") and type_of(d["messages"]) == "list" then d["messages"] otherwise []
|
|
266
|
+
-- el cursor se guarda ANTES de encolar: un mensaje nunca se procesa dos veces (si se cae acá, se pierde uno)
|
|
267
|
+
when type_of(d) == "map" and contains(d, "cursor") and d["cursor"] != nothing
|
|
268
|
+
write_file(cursor_file(name), json_encode({"cursor": d["cursor"]}))
|
|
269
|
+
give {"ok": true, "n": route_messages(name, l, msgs), "error": ""}
|
|
270
|
+
|
|
271
|
+
-- el bucle de un canal en modo poll (corre en un agente ChannelPoller del proceso del workspace)
|
|
272
|
+
export task poll_loop(name)
|
|
273
|
+
require exec
|
|
274
|
+
require time
|
|
275
|
+
require random
|
|
276
|
+
require file(".lampson")
|
|
277
|
+
require file(".lampson/*")
|
|
278
|
+
require file.read("plugins")
|
|
279
|
+
require file.read("plugins/*")
|
|
280
|
+
require file.read("agents")
|
|
281
|
+
require file.read("agents/*")
|
|
282
|
+
require file("workspace")
|
|
283
|
+
require file("workspace/*")
|
|
284
|
+
require env("LAMPSON_*")
|
|
285
|
+
log(name, "POLL start (no public URL: Lampson asks the platform for new messages)")
|
|
286
|
+
let going be true
|
|
287
|
+
while going
|
|
288
|
+
let l be plugins.channel(name)
|
|
289
|
+
when l == nothing or not l["channel"]["poll"] or mode_of(name) != "poll"
|
|
290
|
+
set going to false
|
|
291
|
+
otherwise
|
|
292
|
+
let r be poll_once(name)
|
|
293
|
+
when not r["ok"]
|
|
294
|
+
sleep(10)
|
|
295
|
+
otherwise when r["n"] == 0
|
|
296
|
+
sleep(1)
|
|
297
|
+
state_set("chpoll:" + name, false)
|
|
298
|
+
log(name, "POLL stop")
|
|
299
|
+
give true
|
|
300
|
+
|
|
301
|
+
-- MIGA runtime (igual que agents.Child): un agente solo llama tasks TOP-LEVEL del entry; web.syn define
|
|
302
|
+
-- `task lampson_channel_poller(name) give channels.poll_loop(name)`
|
|
303
|
+
agent ChannelPoller
|
|
304
|
+
require exec
|
|
305
|
+
require time
|
|
306
|
+
require random
|
|
307
|
+
require net
|
|
308
|
+
require file(".lampson")
|
|
309
|
+
require file(".lampson/*")
|
|
310
|
+
require file.read("plugins")
|
|
311
|
+
require file.read("plugins/*")
|
|
312
|
+
require file.read("agents")
|
|
313
|
+
require file.read("agents/*")
|
|
314
|
+
require file("workspace")
|
|
315
|
+
require file("workspace/*")
|
|
316
|
+
require file.read("skills")
|
|
317
|
+
require file.read("skills/*")
|
|
318
|
+
require file("memory")
|
|
319
|
+
require file("memory/*")
|
|
320
|
+
require env("LAMPSON_*")
|
|
321
|
+
require env("OS")
|
|
322
|
+
require secret("LAMPSON_*")
|
|
323
|
+
lampson_channel_poller(channel_name)
|
|
324
|
+
|
|
325
|
+
-- el tick (cron de web.syn): un poller vivo por cada canal encendido en modo poll
|
|
326
|
+
export task poll_tick()
|
|
327
|
+
require exec
|
|
328
|
+
require time
|
|
329
|
+
require file(".lampson")
|
|
330
|
+
require file(".lampson/*")
|
|
331
|
+
require file.read("plugins")
|
|
332
|
+
require file.read("plugins/*")
|
|
333
|
+
require file("workspace")
|
|
334
|
+
require file("workspace/*")
|
|
335
|
+
require env("LAMPSON_*")
|
|
336
|
+
each l in plugins.channels()
|
|
337
|
+
when l["channel"]["poll"] and mode_of(l["name"]) == "poll" and state_get("chpoll:" + l["name"], false) != true
|
|
338
|
+
state_set("chpoll:" + l["name"], true)
|
|
339
|
+
spawn ChannelPoller with channel_name = l["name"]
|
|
340
|
+
give true
|
package/lib/loop.syn
CHANGED
|
@@ -25,6 +25,7 @@ use "./permission.syn" as permission
|
|
|
25
25
|
use "./mcp.syn" as mcp
|
|
26
26
|
use "./plugins.syn" as plugins
|
|
27
27
|
use "./tools/todo.syn" as todo
|
|
28
|
+
use "./scope.syn" as scope
|
|
28
29
|
|
|
29
30
|
let MAX_ERRORS_PER_TURN be 8
|
|
30
31
|
-- capturas de computer_use (lib/computer.syn): el driver las deja en el blackboard "computer:screenshot" y acá van al
|
|
@@ -275,6 +276,19 @@ task strip_raw_tool_calls(t)
|
|
|
275
276
|
task tool_result_msg(tc, content)
|
|
276
277
|
give {"role": "tool", "tool_call_id": tc["id"], "name": tc["name"], "content": content}
|
|
277
278
|
|
|
279
|
+
-- "auto" | "ask" | "" para una tool, según opts["approve"] (nombre exacto o prefijo con * al final)
|
|
280
|
+
export task approve_for(opts, name)
|
|
281
|
+
when not contains(opts, "approve")
|
|
282
|
+
give ""
|
|
283
|
+
let ap be opts["approve"]
|
|
284
|
+
when contains(ap, name)
|
|
285
|
+
give ap[name]
|
|
286
|
+
each k in keys(ap)
|
|
287
|
+
when ends_with(k, "*")
|
|
288
|
+
when starts_with(name, slice(k, 0, length(k) - 1))
|
|
289
|
+
give ap[k]
|
|
290
|
+
give ""
|
|
291
|
+
|
|
278
292
|
-- Ejecuta UNA tool call: permisos → allow-list → call_tool → resultado como texto.
|
|
279
293
|
task execute(tc, opts, on_event)
|
|
280
294
|
let tag be opts["tag"]
|
|
@@ -286,7 +300,19 @@ task execute(tc, opts, on_event)
|
|
|
286
300
|
give "ERROR: unknown tool '" + name + "'. Available: " + join(keys(registry), ", ")
|
|
287
301
|
when contains(args, "_parse_error")
|
|
288
302
|
give "ERROR: could not parse tool arguments as JSON: " + text(args["_parse_error"])
|
|
289
|
-
|
|
303
|
+
-- alcance por ruta (lib/scope.syn): solo agentes del proyecto que limitan una tool de archivos
|
|
304
|
+
when contains(opts, "scopes")
|
|
305
|
+
when contains(opts["scopes"], name)
|
|
306
|
+
let why be scope.violation(name, args, opts["scopes"][name])
|
|
307
|
+
when why != ""
|
|
308
|
+
emit(on_event, "tool_denied", {"call": tc, "reason": "out of scope (" + why + ")"}, tag)
|
|
309
|
+
give "DENIED by scope: " + why + ". Do not retry other paths outside it; work with what is in scope or tell the user."
|
|
310
|
+
-- permiso por tool (runtime: "approve" en el allow-list de un agente del proyecto): "auto" = esta tool se evalúa
|
|
311
|
+
-- como en yolo (lo prohibido en todos los modos sigue prohibido); "ask" = esta tool pide aprobación siempre
|
|
312
|
+
let forced be approve_for(opts, name)
|
|
313
|
+
let verdict be permission.evaluate(name, args, when forced == "auto" then "yolo" otherwise opts["permission_mode"])
|
|
314
|
+
when forced == "ask" and verdict["decision"] == "allow"
|
|
315
|
+
set verdict to {"decision": "ask", "reason": "this agent asks before every " + name + " call"}
|
|
290
316
|
when verdict["decision"] == "deny"
|
|
291
317
|
emit(on_event, "tool_denied", {"call": tc, "reason": verdict["reason"]}, tag)
|
|
292
318
|
give "DENIED by policy (" + verdict["reason"] + "). Do not retry this exact action; explain or propose an alternative."
|