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.
package/run.syn ADDED
@@ -0,0 +1,493 @@
1
+ -- run.syn — Lampson sin interfaz: un mensaje entra, el agente trabaja, la respuesta sale (spec/engine.md, fase 1)
2
+ --
3
+ -- lampson run "resumí los cambios de hoy" -- texto final por stdout
4
+ -- echo "hola" | lampson run --agent soporte --thread whatsapp:+54911… --json
5
+ --
6
+ -- Corre como chat.syn: cwd = .lampson/ws/<slug> con la junction `workspace` (los launchers lo preparan).
7
+ -- Entrada por entorno (los launchers la arman desde los flags):
8
+ -- LAMPSON_MESSAGE el mensaje; vacío → se lee stdin hasta EOF
9
+ -- LAMPSON_AGENT el agente (integrado o workspace/.lampson/agents/<id>.agent.json); default build
10
+ -- LAMPSON_THREAD identidad externa de la conversación (cliente, canal, tarea): misma → misma sesión
11
+ -- LAMPSON_SESSION o el id de una sesión ya existente
12
+ -- LAMPSON_RUN_JSON=1 eventos JSONL por stdout (uno por línea) y al final {"kind":"done",…}
13
+ -- LAMPSON_RUN_PERMISSION ask|strict|yolo; vacío → el del agente, y si no dice → strict
14
+ -- Sin humano delante: lo que pida aprobación se DENIEGA (no hay ask_fn); el modelo lo ve y lo informa.
15
+ -- Código de salida: 0 ok · 1 el turno terminó en error · 2 uso inválido (agente inexistente, mensaje vacío).
16
+
17
+ intent: "Headless Lampson: deliver one message to an agent and print its answer (or the event stream as JSONL)"
18
+
19
+ require net
20
+ require time
21
+ require stdin
22
+ require exec
23
+ require random
24
+ require env("LAMPSON_*")
25
+ require env("OS")
26
+ require secret("LAMPSON_*")
27
+ require db(".lampson/teams.db")
28
+ require judge
29
+ require file("workspace")
30
+ require file("workspace/*")
31
+ require file.read("skills")
32
+ require file.read("skills/*")
33
+ require file.read("plugins")
34
+ require file.read("plugins/*")
35
+ require file.read("agents")
36
+ require file.read("agents/*")
37
+ require file("memory")
38
+ require file("memory/*")
39
+ require file(".lampson")
40
+ require file(".lampson/*")
41
+
42
+ use "./lib/teams.syn" as teams
43
+ use "./lib/runtime.syn" as runtime
44
+ use "./lib/agents.syn" as agents
45
+ use "./lib/mcp.syn" as mcp
46
+ use "./lib/apikeys.syn" as apikeys
47
+ use "./lib/mcp_server.syn" as mcp_server
48
+ use "./lib/approvals.syn" as approvals
49
+ use "./lib/plugins.syn" as plugins
50
+ use "./lib/channels.syn" as channels
51
+
52
+ -- `lampson key add|list|remove`: API keys de la API /v1 de este workspace (lib/apikeys.syn, lib/api.syn)
53
+ -- LAMPSON_KEY_CMD=add [LAMPSON_KEY_NAME] [LAMPSON_KEY_AGENTS=tienda,soporte] [LAMPSON_KEY_RATE=60]
54
+ -- [LAMPSON_KEY_CALLBACKS=https://a/,https://b/] · list · remove LAMPSON_KEY_ID
55
+ let key_cmd be env("LAMPSON_KEY_CMD", "")
56
+ when key_cmd != ""
57
+ let ws_path be "/w/" + env("LAMPSON_WS", "<slug>") + "/v1"
58
+ -- la URL pública de este lampson (--domain, túnel o LAMPSON_PUBLIC_URL), si hay: la que se pega en otra app o agente
59
+ let pub be approvals.public_url()
60
+ let api_base be when pub != "" then pub + ws_path otherwise "http://127.0.0.1:8080" + ws_path
61
+ when key_cmd == "add"
62
+ let ag be where(apply((x) => lower(trim(x)), split(env("LAMPSON_KEY_AGENTS", ""), ",")), (x) => x != "")
63
+ each a in ag
64
+ when a != "*" and not contains(runtime.names(), a)
65
+ print("lampson key: no agent named '" + a + "' · available: " + join(runtime.names(), ", "))
66
+ exit(2)
67
+ let rate_s be trim(env("LAMPSON_KEY_RATE", ""))
68
+ let cbs be where(apply((x) => trim(x), split(env("LAMPSON_KEY_CALLBACKS", ""), ",")), (x) => x != "")
69
+ each cb in cbs
70
+ when not (starts_with(cb, "https://") or starts_with(cb, "http://"))
71
+ print("lampson key: --callback must be an http(s) URL prefix, got '" + cb + "'")
72
+ exit(2)
73
+ let kopts be {"callbacks": cbs}
74
+ when rate_s != ""
75
+ when not matches(rate_s, "[0-9]{1,6}")
76
+ print("lampson key: --rate must be a number of requests per minute (0 = no limit)")
77
+ exit(2)
78
+ set kopts["rate"] to int(rate_s)
79
+ let k be apikeys.create_with(env("LAMPSON_KEY_NAME", ""), ag, kopts)
80
+ print("API key creada (" + k["id"] + ") para " + (when contains(k["agents"], "*") then "todos los agentes" otherwise join(k["agents"], ", ")) + " · " + (when k["rate"] == 0 then "sin límite" otherwise text(k["rate"]) + " pedidos/min") + (when length(k["callbacks"]) > 0 then " · callbacks solo a " + join(k["callbacks"], ", ") otherwise "") + ". Guardala ahora: no se vuelve a mostrar.")
81
+ print("")
82
+ print(" " + k["key"])
83
+ print("")
84
+ print(" API (apps, bots): " + api_base + "/messages")
85
+ print(" MCP (otros agentes): " + api_base + "/mcp con el header Authorization: Bearer <la key>")
86
+ when pub == ""
87
+ print(" (solo desde esta PC: para usarla desde afuera, `lampson --domain …` o un túnel; ver lampson.org/docs/phone)")
88
+ print("")
89
+ print(" curl -X POST " + api_base + "/messages -H \"Authorization: Bearer " + k["key"] + "\" -H \"Content-Type: application/json\" -d '{\"to\": \"" + (when contains(k["agents"], "*") then runtime.default_agent() otherwise k["agents"][0]) + "\", \"thread\": \"cliente-1\", \"text\": \"hola\"}'")
90
+ otherwise when key_cmd == "list"
91
+ let ks be apikeys.list()
92
+ when length(ks) == 0
93
+ print("sin API keys en este workspace (lampson key add [--agent ID] [--name NOMBRE])")
94
+ each k in ks
95
+ print(" " + k["id"] + " " + (when k["name"] == "" then "(sin nombre)" otherwise k["name"]) + " agentes: " + join(k["agents"], ", ") + " " + (when k["rate"] == 0 then "sin límite" otherwise text(k["rate"]) + "/min") + (when length(k["callbacks"]) > 0 then " callbacks: " + join(k["callbacks"], ", ") otherwise "") + " creada " + k["created"] + " último uso " + (when k["last_used"] == nothing then "nunca" otherwise text(k["last_used"])))
96
+ print(" API: " + api_base + "/messages · MCP: " + api_base + "/mcp")
97
+ otherwise when key_cmd == "remove"
98
+ let kid be env("LAMPSON_KEY_ID", "")
99
+ when apikeys.remove(kid)
100
+ print("API key " + kid + " revocada")
101
+ otherwise
102
+ print("lampson key: no existe la key '" + kid + "' (lampson key list)")
103
+ exit(2)
104
+ otherwise
105
+ print("uso: lampson key add [--agent ID[,ID]] [--name NOMBRE] · lampson key list · lampson key remove <id>")
106
+ exit(2)
107
+ exit(0)
108
+
109
+ -- `lampson objective add|list|show|reply|cancel` y `lampson team list` (lib/teams.syn): sin servidor, directo a la base
110
+ -- del workspace; el pulso del proceso del workspace (lib/teamrun.syn) los hace avanzar
111
+ -- LAMPSON_OBJ_CMD=add LAMPSON_MESSAGE=<texto> [LAMPSON_OBJ_AGENT | LAMPSON_OBJ_TEAM] [LAMPSON_OBJ_BUDGET] [LAMPSON_OBJ_ROUND]
112
+ -- list · show/cancel LAMPSON_OBJ_ID · reply LAMPSON_OBJ_ID LAMPSON_MESSAGE [LAMPSON_OBJ_DECISION=approve|deny]
113
+ let obj_cmd be env("LAMPSON_OBJ_CMD", "")
114
+ task obj_line(o)
115
+ give " " + "O-" + text(o["id"]) + " " + o["status"] + " " + (when o["team"] != "" then "equipo " + o["team"] + " (" + o["agent"] + ")" otherwise o["agent"]) + " · " + slice(o["text"], 0, 70) + (when length(o["text"]) > 70 then "…" otherwise "")
116
+ when obj_cmd != ""
117
+ let oid be floor(number(when matches(env("LAMPSON_OBJ_ID", ""), "[Oo]?-?[0-9]+") then regex_replace(env("LAMPSON_OBJ_ID", ""), "[^0-9]", "") otherwise "0"))
118
+ when obj_cmd == "add"
119
+ let txt be trim(env("LAMPSON_MESSAGE", ""))
120
+ let tid be lower(trim(env("LAMPSON_OBJ_TEAM", "")))
121
+ let ag be lower(trim(env("LAMPSON_OBJ_AGENT", "")))
122
+ when txt == ""
123
+ print("uso: lampson objective add \"qué tiene que lograr\" --agent ID | --team ID [--budget TOKENS] [--round SEGUNDOS]")
124
+ exit(2)
125
+ when tid != ""
126
+ let tm be teams.get(tid)
127
+ when tm == nothing
128
+ print("lampson objective: no hay un equipo '" + tid + "' · equipos: " + join(apply(teams.all(), (t) => t["id"]), ", "))
129
+ exit(2)
130
+ when ag == ""
131
+ set ag to teams.lead_of(tm)
132
+ when teams.member(tm, ag) == nothing
133
+ print("lampson objective: " + ag + " no está en el equipo " + tid)
134
+ exit(2)
135
+ when ag == "" or runtime.get(ag) == nothing
136
+ print("lampson objective: decí qué agente (--agent ID) o qué equipo (--team ID) · agentes: " + join(runtime.names(), ", "))
137
+ exit(2)
138
+ let oopts be {"created_by": "cli", "team": tid}
139
+ when env("LAMPSON_OBJ_BUDGET", "") != ""
140
+ set oopts["budget_tokens"] to int(env("LAMPSON_OBJ_BUDGET", "0"))
141
+ when env("LAMPSON_OBJ_ROUND", "") != ""
142
+ set oopts["round_seconds"] to int(env("LAMPSON_OBJ_ROUND", "20"))
143
+ let nid be teams.obj_create(ag, txt, oopts)
144
+ print("objetivo O-" + text(nid) + " creado para " + (when tid != "" then "el equipo " + tid + " (lo lidera " + ag + ")" otherwise ag) + ". Arranca en segundos si el workspace está prendido (el hub lo mantiene) · lampson objective show " + text(nid) + " · pantalla: http://127.0.0.1:8080/w/" + env("LAMPSON_WS", "<slug>") + "/equipos?o=" + text(nid))
145
+ exit(0)
146
+ when obj_cmd == "list"
147
+ let all_o be teams.obj_list()
148
+ when length(all_o) == 0
149
+ print("sin objetivos en este workspace (lampson objective add \"…\" --agent ID | --team ID)")
150
+ each o in all_o
151
+ print(obj_line(o))
152
+ exit(0)
153
+ let o be teams.obj_get(oid)
154
+ when o == nothing
155
+ print("lampson objective: no existe O-" + text(oid) + " (lampson objective list)")
156
+ exit(2)
157
+ when obj_cmd == "show"
158
+ print(obj_line(o))
159
+ print(" turnos " + text(o["turns"]) + " · gastado " + text(o["spent"]) + (when o["budget_tokens"] > 0 then " de " + text(o["budget_tokens"]) otherwise "") + " tokens")
160
+ when o["question"] != ""
161
+ print(" " + (when o["question_kind"] == "approval" then "PIDE APROBACIÓN: " otherwise "PREGUNTA: ") + o["question"] + "\n → lampson objective reply " + text(oid) + (when o["question_kind"] == "approval" then " --approve | --deny [\"nota\"]" otherwise " \"tu respuesta\""))
162
+ when o["progress"] != ""
163
+ print(" último informe: " + o["progress"])
164
+ when o["result"] != ""
165
+ print(" resultado: " + o["result"])
166
+ let ts be teams.tasks(teams.obj_scope(o))
167
+ when length(ts) > 0
168
+ print(" tablero:")
169
+ each t in ts
170
+ print(" #" + text(t["id"]) + " [" + t["status"] + "] " + t["title"] + (when t["owner"] != "" then " — " + t["owner"] otherwise ""))
171
+ exit(0)
172
+ when obj_cmd == "reply"
173
+ let dec be lower(env("LAMPSON_OBJ_DECISION", ""))
174
+ when o["question_kind"] == "approval" and dec == ""
175
+ print("lampson objective: O-" + text(oid) + " pide aprobación — respondé con --approve o --deny (y una nota opcional)")
176
+ exit(2)
177
+ when o["question_kind"] != "approval" and trim(env("LAMPSON_MESSAGE", "")) == "" and dec == ""
178
+ print("lampson objective: escribí la respuesta: lampson objective reply " + text(oid) + " \"…\"")
179
+ exit(2)
180
+ try
181
+ teams.obj_reply(oid, env("LAMPSON_MESSAGE", ""), dec == "approve", "person")
182
+ print("respondido: O-" + text(oid) + " sigue trabajando")
183
+ recover err
184
+ print("lampson objective: " + regex_replace(text(err), "^.*?:\\d+:\\d+: ", ""))
185
+ exit(2)
186
+ exit(0)
187
+ when obj_cmd == "cancel"
188
+ teams.obj_cancel(oid, "person")
189
+ print("O-" + text(oid) + " cancelado")
190
+ exit(0)
191
+ print("uso: lampson objective add \"…\" --agent ID|--team ID · objective list · objective show <id> · objective reply <id> \"…\" [--approve|--deny] · objective cancel <id>")
192
+ exit(2)
193
+
194
+ when env("LAMPSON_TEAM_CMD", "") != ""
195
+ let sc be teams.scan()
196
+ when length(sc["teams"]) == 0
197
+ print("sin equipos en este workspace: un equipo es .lampson/teams/<id>.team.json (o creálo en la pantalla: lampson --web → equipos)")
198
+ each t in sc["teams"]
199
+ print(" " + t["id"] + (when t["description"] != "" then " — " + t["description"] otherwise "") + " · rondas " + (when t["round_minutes"] > 0 then "cada " + text(floor(t["round_minutes"])) + " min" otherwise "no") + " · tope " + (when t["budget_daily_tokens"] > 0 then text(t["budget_daily_tokens"]) + "/agente/día" otherwise "sin tope"))
200
+ each m in t["members"]
201
+ print(" " + m["agent"] + " " + m["role"] + (when m["reports_to"] != "" then " → reporta a " + m["reports_to"] otherwise " (lidera)") + (when runtime.get(m["agent"]) == nothing then " ⚠ sin archivo de agente" otherwise ""))
202
+ each e in sc["errors"]
203
+ print(" ✗ " + e)
204
+ exit(0)
205
+
206
+ -- `lampson channel list|on|off|setup [canal]`: los canales (plugins con "channel", lib/channels.syn)
207
+ let ch_cmd be env("LAMPSON_CHANNEL_CMD", "")
208
+ when ch_cmd != ""
209
+ let ch_name be lower(env("LAMPSON_CHANNEL_NAME", ""))
210
+ let pub_ch be approvals.public_url()
211
+ let slug be env("LAMPSON_WS", "")
212
+ task hook_url(n)
213
+ give channels.webhook_url(n, pub_ch, slug)
214
+ let chs be where(plugins.all(), (l) => l["channel"] != nothing)
215
+ when ch_cmd == "list"
216
+ when length(chs) == 0
217
+ print("no hay canales instalados (un canal es un plugin con \"channel\" en su plugin.json)")
218
+ each l in chs
219
+ let ag be when l["error"] == nothing then channels.agent_for(l["name"], l, {}) otherwise "?"
220
+ let md be channels.mode_of(l["name"])
221
+ print(" " + (when l["enabled"] then "● " otherwise "○ ") + l["name"] + " " + (when l["error"] != nothing then "roto: " + text(l["error"]) otherwise "agente: " + ag + " " + (when md == "poll" then "modo: sin URL pública (poll)" otherwise "webhook: " + hook_url(l["name"]))))
222
+ when pub_ch == ""
223
+ print(" (sin URL pública: las plataformas no llegan a esta PC. `lampson --domain …` o un túnel; ver lampson.org/docs/phone)")
224
+ exit(0)
225
+ let found be where(chs, (l) => l["name"] == ch_name)
226
+ when length(found) == 0
227
+ print("lampson channel: no hay un canal '" + ch_name + "' · instalados: " + join(apply((l) => l["name"], chs), ", "))
228
+ exit(2)
229
+ let l be found[0]
230
+ when ch_cmd == "on" or ch_cmd == "off"
231
+ plugins.set_enabled(ch_name, ch_cmd == "on")
232
+ print("canal " + ch_name + (when ch_cmd == "on" then " encendido · webhook: " + hook_url(ch_name) otherwise " apagado"))
233
+ exit(0)
234
+ when ch_cmd == "setup"
235
+ when not l["enabled"]
236
+ print("lampson channel: el canal " + ch_name + " está apagado — `lampson channel on " + ch_name + "` primero")
237
+ exit(2)
238
+ let su be channels.setup_channel(ch_name, pub_ch, slug)
239
+ print(su["out"])
240
+ exit(su["code"])
241
+ print("uso: lampson channel list · channel on|off <canal> · channel setup <canal>")
242
+ exit(2)
243
+
244
+ -- `lampson mcp serve`: Lampson como servidor MCP por stdio (lib/mcp_server.syn); stdout queda SOLO para JSON-RPC
245
+ when env("LAMPSON_MCP_SERVE", "") == "1"
246
+ let offered be mcp_server.offered()
247
+ when length(offered) == 0
248
+ print(json_encode({"jsonrpc": "2.0", "id": nothing, "error": {"code": -32603, "message": "no agents match LAMPSON_MCP_AGENTS"}}))
249
+ exit(2)
250
+ share {"id": text(now())} as "lampson:run"
251
+ share {"kind": "mcp"} as "lampson:ui"
252
+ -- servers MCP propios de Lampson solo si algún agente ofrecido puede usarlos
253
+ let uses_mcp be false
254
+ each n in offered
255
+ let ts be runtime.get(n)["tools"]
256
+ when contains(ts, "mcp") or length(where(ts, (t) => starts_with(t, "mcp_"))) > 0
257
+ set uses_mcp to true
258
+ when uses_mcp
259
+ mcp.start_all(8)
260
+ mcp_server.serve()
261
+ exit(0)
262
+
263
+ -- Subagente en background: `agent Child` (lib/agents.syn) solo llama tasks TOP-LEVEL del programa de entrada
264
+ task lampson_subagent(spec_json)
265
+ give agents.run_child_json(spec_json)
266
+
267
+ -- `lampson run --stdio`: MODO LOCAL (lo usa el SDK). Un proceso abierto, un pedido JSON por línea en stdin:
268
+ -- {"id": "r1", "op": "ask", "to"?, "thread"?, "session"?, "text", "images"?, "meta"?, "mode"?: "strict"|"yolo"}
269
+ -- {"id": "r2", "op": "agents"} · {"id": "r3", "op": "ping"}
270
+ -- y por stdout, una línea JSON por evento con ese id: los mismos que `--json` (session, assistant, tool_call…) y
271
+ -- {"id", "kind": "done", "data": {agent, thread, session, text, steps, usage, stopped}} al terminar cada ask. Al
272
+ -- arrancar, {"kind": "ready", "data": {"agents": […], "protocol": 2}}.
273
+ -- CONCURRENCIA (protocolo 2): cada ask corre en su propio agente de Synsema; conversaciones distintas van en
274
+ -- paralelo, dos asks de la MISMA conversación (agente + thread) esperan en fila. Un agente que imprime sale con
275
+ -- prefijo "[Agente_N]" (rompería el JSON): por eso los trabajos publican en el bus y SOLO el hilo principal escribe.
276
+ -- Sin humano: lo que pida aprobación se deniega; "mode" lo puede fijar quien llama (es su programa, en su máquina).
277
+ task stdio_out(m)
278
+ print(json_encode(m))
279
+ flush()
280
+
281
+ -- un ask, dentro de un agente StdioJob (los agentes solo ven tasks TOP-LEVEL del entry)
282
+ task lampson_stdio_job(req_json)
283
+ let req be json_decode(req_json)
284
+ let rid be req["id"]
285
+ let agent_id be req["to"]
286
+ let th be req["thread"]
287
+ task out(m)
288
+ bus_publish("stdio.out", m)
289
+ task on_event(kind, data, tag)
290
+ when kind != "busy" and kind != "idle"
291
+ out({"id": rid, "kind": kind, "data": data, "tag": tag, "agent": agent_id, "thread": th})
292
+ task on_start(info)
293
+ set th to info["thread"]
294
+ out({"id": rid, "kind": "session", "data": info, "tag": "", "agent": info["agent"], "thread": info["thread"]})
295
+ let r be nothing
296
+ try
297
+ set r to runtime.deliver(req["sobre"], {"mode": req["mode"], "ask_fn": nothing, "on_event": on_event, "on_start": on_start})
298
+ recover err
299
+ set r to {"agent": agent_id, "thread": th, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
300
+ out({"id": rid, "kind": "done", "data": r, "tag": "", "agent": r["agent"], "thread": r["thread"]})
301
+ bus_publish("stdio.done", {"key": req["key"]})
302
+ give true
303
+
304
+ agent StdioReader
305
+ require stdin
306
+ let l be read_line("")
307
+ while l != nothing
308
+ bus_publish("stdio.line", l)
309
+ set l to read_line("")
310
+ bus_publish("stdio.eof", true)
311
+
312
+ agent StdioJob
313
+ require net
314
+ require exec
315
+ require time
316
+ require random
317
+ require env("LAMPSON_*")
318
+ require env("OS")
319
+ require secret("LAMPSON_*")
320
+ require file("workspace")
321
+ require file("workspace/*")
322
+ require file.read("skills")
323
+ require file.read("skills/*")
324
+ require file.read("plugins")
325
+ require file.read("plugins/*")
326
+ require file.read("agents")
327
+ require file.read("agents/*")
328
+ require file("memory")
329
+ require file("memory/*")
330
+ require file(".lampson")
331
+ require file(".lampson/*")
332
+ lampson_stdio_job(spec_json)
333
+
334
+ -- un pedido ask ya leído → {ok, job, error}: el spec del trabajo (o por qué no)
335
+ task stdio_ask(req, rid)
336
+ let agent_id be lower(text(when contains(req, "to") and req["to"] != nothing and text(req["to"]) != "" then req["to"] otherwise runtime.default_agent()))
337
+ let th be when contains(req, "thread") and req["thread"] != nothing then text(req["thread"]) otherwise ""
338
+ let msg be when contains(req, "text") and req["text"] != nothing then text(req["text"]) otherwise ""
339
+ let spec be runtime.get(agent_id)
340
+ let fail_r be {"agent": agent_id, "thread": th, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": ""}
341
+ when spec == nothing
342
+ set fail_r["stopped"] to "error: no agent named '" + agent_id + "' · available: " + join(runtime.names(), ", ")
343
+ give {"ok": false, "done": fail_r}
344
+ when trim(msg) == ""
345
+ set fail_r["stopped"] to "error: text is required"
346
+ give {"ok": false, "done": fail_r}
347
+ let want be when contains(req, "mode") and req["mode"] != nothing then lower(text(req["mode"])) otherwise ""
348
+ let mode be when want == "strict" or want == "yolo" then want otherwise (when spec["permission"] == "" then "strict" otherwise "")
349
+ let ss be when contains(req, "session") and req["session"] != nothing then text(req["session"]) otherwise ""
350
+ -- la fila es por conversación: (agente, thread), o la sesión; sin ninguno, el pedido solo (va en paralelo)
351
+ let key be when th != "" then agent_id + "\n" + th otherwise (when ss != "" then agent_id + "\nsession:" + ss otherwise "req:" + rid)
352
+ let sobre be {"to": agent_id, "thread": th, "session": ss, "from": {"id": "", "name": "", "kind": "human"}, "text": msg, "images": when contains(req, "images") and type_of(req["images"]) == "list" then req["images"] otherwise [], "channel": "sdk", "meta": when contains(req, "meta") and type_of(req["meta"]) == "map" then req["meta"] otherwise {}}
353
+ give {"ok": true, "key": key, "job": {"id": rid, "to": agent_id, "thread": th, "mode": mode, "key": key, "sobre": sobre}}
354
+
355
+ when env("LAMPSON_RUN_STDIO", "") == "1"
356
+ share {"id": text(now())} as "lampson:run"
357
+ share {"kind": "sdk"} as "lampson:ui"
358
+ let all_names be runtime.names()
359
+ let any_mcp be false
360
+ each n in all_names
361
+ let ts be runtime.get(n)["tools"]
362
+ when contains(ts, "mcp") or length(where(ts, (t) => starts_with(t, "mcp_"))) > 0
363
+ set any_mcp to true
364
+ when any_mcp
365
+ mcp.start_all(8)
366
+ let sub be bus_subscribe(["stdio.line", "stdio.out", "stdio.done", "stdio.eof"], {"max_queue": 100000, "on_full": "error"})
367
+ spawn StdioReader
368
+ stdio_out({"kind": "ready", "data": {"agents": all_names, "protocol": 2}})
369
+ let busy be {}
370
+ let waiting be {}
371
+ let running be 0
372
+ let eof be false
373
+ let open be true
374
+ while open
375
+ let ev be bus_recv(sub, 3600)
376
+ when ev == nothing
377
+ set open to running > 0 or not eof
378
+ otherwise when ev["topic"] == "stdio.out"
379
+ stdio_out(ev["data"])
380
+ otherwise when ev["topic"] == "stdio.done"
381
+ let k be ev["data"]["key"]
382
+ set running to running - 1
383
+ let q be when contains(waiting, k) then waiting[k] otherwise []
384
+ when length(q) > 0
385
+ set waiting[k] to slice(q, 1, length(q))
386
+ set running to running + 1
387
+ spawn StdioJob with spec_json = json_encode(q[0])
388
+ otherwise
389
+ set busy[k] to false
390
+ when eof and running == 0
391
+ set open to false
392
+ otherwise when ev["topic"] == "stdio.eof"
393
+ set eof to true
394
+ when running == 0
395
+ set open to false
396
+ otherwise when ev["topic"] == "stdio.line"
397
+ let line be ev["data"]
398
+ when trim(line) != ""
399
+ let req be nothing
400
+ try
401
+ set req to json_decode(line)
402
+ recover err
403
+ set req to nothing
404
+ when req == nothing or type_of(req) != "map"
405
+ stdio_out({"id": "", "kind": "error", "data": "each line must be a JSON object"})
406
+ otherwise
407
+ let rid be when contains(req, "id") and req["id"] != nothing then text(req["id"]) otherwise ""
408
+ let op be when contains(req, "op") and req["op"] != nothing then lower(text(req["op"])) otherwise "ask"
409
+ when op == "ping"
410
+ stdio_out({"id": rid, "kind": "pong"})
411
+ otherwise when op == "agents"
412
+ stdio_out({"id": rid, "kind": "agents", "data": apply((n) => {"id": n, "description": runtime.get(n)["description"]}, runtime.names())})
413
+ otherwise when op == "ask"
414
+ let a be stdio_ask(req, rid)
415
+ when not a["ok"]
416
+ stdio_out({"id": rid, "kind": "done", "data": a["done"], "tag": "", "agent": a["done"]["agent"], "thread": a["done"]["thread"]})
417
+ otherwise when contains(busy, a["key"]) and busy[a["key"]]
418
+ let wq be when contains(waiting, a["key"]) then waiting[a["key"]] otherwise []
419
+ set waiting[a["key"]] to append(wq, a["job"])
420
+ otherwise
421
+ set busy[a["key"]] to true
422
+ set running to running + 1
423
+ spawn StdioJob with spec_json = json_encode(a["job"])
424
+ otherwise
425
+ stdio_out({"id": rid, "kind": "error", "data": "unknown op '" + op + "' (ask, agents, ping)"})
426
+ exit(0)
427
+
428
+ let json_out be env("LAMPSON_RUN_JSON", "") == "1"
429
+ let agent_id be runtime.default_agent()
430
+ let thread be env("LAMPSON_THREAD", "")
431
+
432
+ task fail_usage(msg)
433
+ when json_out
434
+ print(json_encode({"kind": "error", "data": msg, "tag": "", "agent": agent_id, "thread": thread}))
435
+ otherwise
436
+ print("lampson run: " + msg)
437
+ exit(2)
438
+
439
+ let spec be runtime.get(agent_id)
440
+ when spec == nothing
441
+ fail_usage("no agent named '" + agent_id + "' · available: " + join(runtime.names(), ", "))
442
+
443
+ let message be env("LAMPSON_MESSAGE", "")
444
+ when message == ""
445
+ let lines be []
446
+ let l be read_line("")
447
+ while l != nothing
448
+ set lines to append(lines, l)
449
+ set l to read_line("")
450
+ set message to join(lines, "\n")
451
+ when trim(message) == ""
452
+ fail_usage("empty message (pass it as an argument or on stdin)")
453
+
454
+ let mode be lower(env("LAMPSON_RUN_PERMISSION", ""))
455
+ when mode == "" and spec["permission"] == ""
456
+ set mode to "strict"
457
+
458
+ -- servers MCP solo si el agente puede usarlos (arrancarlos cuesta hasta unos segundos)
459
+ when contains(spec["tools"], "mcp") or length(where(spec["tools"], (t) => starts_with(t, "mcp_"))) > 0
460
+ mcp.start_all(8)
461
+
462
+ share {"id": text(now())} as "lampson:run"
463
+ share {"kind": "cli"} as "lampson:ui"
464
+
465
+ task emit_json(kind, data, tag)
466
+ when kind != "busy" and kind != "idle"
467
+ print(json_encode({"kind": kind, "data": data, "tag": tag, "agent": agent_id, "thread": thread}))
468
+ flush()
469
+
470
+ task on_start(info)
471
+ set thread to info["thread"]
472
+ when json_out
473
+ print(json_encode({"kind": "session", "data": info, "tag": "", "agent": info["agent"], "thread": info["thread"]}))
474
+ flush()
475
+
476
+ let sobre be {"to": agent_id, "thread": thread, "session": env("LAMPSON_SESSION", ""), "from": {"id": "", "name": "", "kind": "human"}, "text": message, "channel": "cli", "meta": {}}
477
+ let hooks be {"mode": mode, "ask_fn": nothing, "on_start": on_start, "on_event": when json_out then emit_json otherwise nothing}
478
+ let result be nothing
479
+ try
480
+ set result to runtime.deliver(sobre, hooks)
481
+ recover err
482
+ set result to {"agent": agent_id, "thread": thread, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
483
+
484
+ when json_out
485
+ print(json_encode({"kind": "done", "data": result, "tag": "", "agent": result["agent"], "thread": result["thread"]}))
486
+ otherwise
487
+ when starts_with(result["stopped"], "error")
488
+ print("lampson run: " + result["stopped"])
489
+ otherwise
490
+ print(result["text"])
491
+ flush()
492
+ when starts_with(result["stopped"], "error")
493
+ exit(1)
package/sdk/index.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ // sdk/index.d.ts — types for the Lampson SDK (sdk/index.js)
2
+
3
+ export interface ServerOptions {
4
+ /** The workspace base: "https://my-lampson.com/w/<workspace>" (a trailing /v1 is fine too). */
5
+ url: string;
6
+ /** An API key from `lampson key add`. */
7
+ key: string;
8
+ /** A fetch implementation (default: the global one, Node 18+). */
9
+ fetch?: typeof fetch;
10
+ /** Per-request timeout in ms (default 15 min: an agent can take a while). */
11
+ timeout?: number;
12
+ }
13
+
14
+ export interface LocalOptions {
15
+ local: {
16
+ /** The project folder the agents work in. */
17
+ workspace: string;
18
+ /** LAMPSON_HOME: where Lampson keeps its config, sessions and plugins (default ~/lampson). */
19
+ home?: string;
20
+ /** Extra environment for the Lampson process (e.g. provider keys). */
21
+ env?: Record<string, string>;
22
+ /** Advanced / tests: an exact command that speaks the `lampson run --stdio` protocol. */
23
+ spawn?: { command: string; args?: string[]; cwd?: string };
24
+ };
25
+ }
26
+
27
+ export interface Message {
28
+ /** The agent that answers (alias: `to`). Default: the workspace's default agent. */
29
+ agent?: string;
30
+ to?: string;
31
+ /** Who/what this conversation is (a customer, a ticket, "cto:task-17"): same thread = same conversation. */
32
+ thread?: string;
33
+ /** Or continue a known session id. */
34
+ session?: string;
35
+ text: string;
36
+ images?: { media_type: string; data: string }[];
37
+ meta?: Record<string, unknown>;
38
+ from?: { id?: string; name?: string; kind?: 'human' | 'agent' | 'system' };
39
+ /** When the user wrote it (unix seconds): orders a burst that arrived out of order (server mode). */
40
+ sentAt?: number;
41
+ /** Server mode: answer now with { job, status: "queued" } and POST the result here later. */
42
+ callback?: string;
43
+ /** Local mode: "strict" | "yolo" for this request (default: the agent's, else strict). */
44
+ mode?: 'strict' | 'yolo';
45
+ }
46
+
47
+ export interface Usage { input: number; output: number; cached: number }
48
+
49
+ export interface Result {
50
+ agent: string;
51
+ thread: string;
52
+ session: string;
53
+ text: string;
54
+ steps: number;
55
+ usage: Usage;
56
+ /** "done" | "max_steps" | "budget" | "error: …" */
57
+ stopped: string;
58
+ /** Server mode: ids of the messages answered together (a burst), and the one that leads it. */
59
+ batch?: string[];
60
+ lead?: string;
61
+ }
62
+
63
+ export interface Queued { job: string; status: 'queued' }
64
+
65
+ export interface LampsonEvent {
66
+ kind: 'session' | 'assistant' | 'tool_call' | 'tool_result' | 'tool_denied' | 'usage' | 'inbox' | 'error' | 'compact' | 'done' | string;
67
+ data: any;
68
+ tag?: string;
69
+ agent?: string;
70
+ thread?: string;
71
+ }
72
+
73
+ export interface AgentInfo { id: string; description: string }
74
+
75
+ export class LampsonError extends Error {
76
+ status?: number;
77
+ body?: unknown;
78
+ result?: Result;
79
+ code?: number | null;
80
+ stderr?: string[];
81
+ }
82
+
83
+ export class Lampson {
84
+ constructor(opts: ServerOptions | LocalOptions);
85
+ readonly mode: 'server' | 'local';
86
+ ask(msg: Message): Promise<Result | Queued>;
87
+ stream(msg: Omit<Message, 'callback'>): AsyncGenerator<LampsonEvent, void, unknown>;
88
+ agents(): Promise<AgentInfo[]>;
89
+ job(id: string): Promise<unknown>;
90
+ close(): Promise<void>;
91
+ static verifySignature(rawBody: string | Buffer, signature: string | undefined, secret: string): boolean;
92
+ }
93
+
94
+ export default Lampson;