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/web.syn CHANGED
@@ -37,6 +37,8 @@ require file.read("skills")
37
37
  require file.read("skills/*")
38
38
  require file.read("plugins")
39
39
  require file.read("plugins/*")
40
+ require file.read("agents")
41
+ require file.read("agents/*")
40
42
  require file("memory")
41
43
  require file("memory/*")
42
44
  require file(".lampson")
@@ -46,8 +48,6 @@ require file.read("public/*")
46
48
 
47
49
  use "./lib/provider.syn" as provider
48
50
  use "./lib/tools.syn" as tools
49
- use "./lib/prompt.syn" as prompt
50
- use "./lib/loop.syn" as loop
51
51
  use "./lib/session.syn" as session
52
52
  use "./lib/agents.syn" as agents
53
53
  use "./lib/tree.syn" as tree
@@ -71,6 +71,12 @@ use "./lib/computer.syn" as computer
71
71
  use "./lib/workspaces.syn" as workspaces
72
72
  use "./lib/judge.syn" as jdg
73
73
  use "./lib/origin.syn" as origin
74
+ use "./lib/runtime.syn" as runtime
75
+ use "./lib/api.syn" as api
76
+ use "./lib/apikeys.syn" as apikeys
77
+ use "./lib/mailbox.syn" as mailbox
78
+ use "./lib/channels.syn" as channels
79
+ use "./lib/mcp_server.syn" as mcp_server
74
80
 
75
81
  let APPROVAL_TIMEOUT be 180
76
82
 
@@ -93,6 +99,10 @@ task check_client(token, request)
93
99
  let want be env("LAMPSON_WEB_TOKEN", "")
94
100
  when want != "" and token == want
95
101
  give {"local": false}
102
+ -- API key de /v1 (lib/apikeys.syn): vale SOLO para /w/<slug>/v1/… — nunca para la UI, la terminal o el chat
103
+ when token != nothing and starts_with(text(token), apikeys.PREFIX) and contains(text(request.path), "/v1/")
104
+ when apikeys.check(token) != nothing
105
+ give {"local": false, "api_key": true}
96
106
  give nothing
97
107
 
98
108
  -- salida del pty como texto (la doc de 0.6.8 ya lo dice así; is_bytes por si cambia)
@@ -101,21 +111,22 @@ task as_text(x)
101
111
  give decode(x, "utf8_lossy")
102
112
  give x
103
113
 
104
- task boot(profile, mode, ask_fn, pname, model)
105
- let cfg be provider.config_for(pname, model)
106
- -- worker es interno de delegate: por la API tampoco se elige como perfil de sesión
107
- let p be when contains(agents.names(), profile) then profile otherwise "build"
108
- let opts be loop.default_opts(agents.registry_for(p), agents.catalog_for(p), ask_fn)
109
- set opts to loop.with_steps(opts, agents.steps_for(p))
110
- set opts to loop.with_inbox(opts, agents.parent_inbox, "")
111
- set opts to loop.with_mode(opts, mode)
112
- give {"cfg": cfg, "system": {"role": "system", "content": prompt.build(agents.env_info(cfg), agents.addendum_for(p))}, "opts": opts, "profile": p}
113
-
114
114
  -- Subagente en background: `agent Child` (lib/agents.syn) solo puede llamar tasks TOP-LEVEL de este
115
115
  -- programa; esta es su puerta de entrada. Bajo serve el agente sobrevive al request que lo lanzó.
116
116
  task lampson_subagent(spec_json)
117
117
  give agents.run_child_json(spec_json)
118
118
 
119
+ -- Worker del buzón de una conversación (lib/mailbox.syn): `agent MailboxWorker` solo llama tasks TOP-LEVEL; esta es su puerta
120
+ task lampson_mailbox_worker(spec_json)
121
+ give mailbox.work(spec_json)
122
+
123
+ -- Canales en modo sin URL pública (lib/channels.syn): un agente ChannelPoller por canal; el tick lo mantiene vivo
124
+ task lampson_channel_poller(name)
125
+ give channels.poll_loop(name)
126
+ task channel_poll_tick()
127
+ give channels.poll_tick()
128
+ cron_every(5, channel_poll_tick)
129
+
119
130
  -- TAREAS PROGRAMADAS (lib/schedule.syn): este proceso es el residente de lampson — con `lampson --daemon start`
120
131
  -- (synsema daemon) queda en background y ejecuta lo programado aunque no haya ninguna UI abierta. Un tick cada
121
132
  -- 30 s (cron_every de Synsema: intervalo puro; la hora de reloj la resuelve schedule.syn) corre lo vencido:
@@ -141,46 +152,62 @@ serve on 8080
141
152
  max_streams 50
142
153
  auth with check_client
143
154
  static "./public"
155
+ -- lo que publican /openapi.json, /llms.txt, /docs y la agent card: SOLO la API /v1 (todo lo demás lleva `private`)
156
+ describe
157
+ about: "Lampson API — agents of this workspace for your apps, channels and other agents"
158
+ version: "1.0.0"
159
+ api: ["POST /w/:slug/v1/messages -- send a message to an agent and get its answer (JSON); with \"callback\", 202 now and the answer POSTed later. Body: {to, thread, text, images?, from?, meta?, sent_at?, session?, callback?}", "POST /w/:slug/v1/messages/stream -- the same, as Server-Sent Events: session, the agent's steps, done", "GET /w/:slug/v1/agents -- the agents this API key can use", "GET /w/:slug/v1/jobs/:id -- status and result of a message sent with a callback", "POST /w/:slug/v1/mcp -- Model Context Protocol (Streamable HTTP, JSON responses): tools ask, agents and history, for other AI agents", "POST /w/:slug/v1/mcp/stream -- the same MCP server answering with Server-Sent Events: with params._meta.progressToken, each step of the agent arrives as notifications/progress before the result", "GET /w/:slug/v1/mcp -- 405: this MCP server opens no server-to-client stream"]
144
160
 
145
161
  -- la UI vive bajo /w/<slug> (BASE en js/core.js); si alguien entra por el puerto del proceso, es lo mismo
146
162
  -- Acceso DIRECTO por el puerto del proceso (sin X-Forwarded-Host, que solo agrega el hub al proxyear): la UI se
147
163
  -- usa siempre por el hub → redirigir a http://127.0.0.1:8080/w/<slug>. Standalone sin hub (docker) no hay
148
164
  -- LAMPSON_WS y se sirve acá mismo.
149
165
  route "GET /w/:slug"
166
+ private
150
167
  let h be headers of request
151
168
  when env("LAMPSON_WS", "") != "" and not contains(h, "x-forwarded-host")
152
169
  give redirect("http://127.0.0.1:8080/w/" + params.slug)
153
170
  give html(read_file("public/index.html"))
154
171
  route "GET /"
172
+ private
155
173
  when env("LAMPSON_WS", "") == ""
156
174
  give redirect("/w/local")
157
175
  give redirect("http://127.0.0.1:8080/w/" + env("LAMPSON_WS", ""))
158
176
  route "GET /api/hub"
177
+ private
159
178
  proxy to "http://127.0.0.1:8080"
160
179
  route "GET /api/workspaces"
180
+ private
161
181
  proxy to "http://127.0.0.1:8080"
162
182
  route "GET /api/workspaces/*path"
183
+ private
163
184
  proxy to "http://127.0.0.1:8080"
164
185
  route "POST /api/workspaces"
186
+ private
165
187
  proxy to "http://127.0.0.1:8080"
166
188
  route "POST /api/workspaces/*path"
189
+ private
167
190
  proxy to "http://127.0.0.1:8080"
168
191
 
169
192
  -- salud para el hub/supervisor y la terminal (último uso = chat, terminal, eventos o abrir la UI)
170
193
  route "GET /w/:slug/api/health"
194
+ private
171
195
  give {"alive": true, "slug": env("LAMPSON_WS", ""), "last_used": state_get("lampson:last_used", nothing), "schedules_on": length(where(schedule.all(), (t) => t["enabled"] == true)), "version": env("LAMPSON_VERSION", "")}
172
196
 
173
197
  route "GET /w/:slug/api/sessions" requires auth
198
+ private
174
199
  state_set("lampson:last_used", now())
175
200
  give {"sessions": session.list()}
176
201
 
177
202
  -- buscador de sesiones (modal «ver todas»): ?q=texto busca en títulos y mensajes de este proyecto
178
203
  route "GET /w/:slug/api/sessions/search" requires auth
204
+ private
179
205
  let q be when contains(query, "q") then text(query.q) otherwise ""
180
206
  let n be when contains(query, "limit") then floor(number(query.limit)) otherwise 200
181
207
  give {"q": q, "sessions": session.search(q, n)}
182
208
 
183
209
  route "GET /w/:slug/api/sessions/:id" requires auth
210
+ private
184
211
  when not session.exists(params.id)
185
212
  give not_found("session not found")
186
213
  let doc be session.load(params.id)
@@ -188,11 +215,13 @@ serve on 8080
188
215
  give {"id": doc["id"], "updated": doc["updated"], "meta": doc["meta"], "messages": visible}
189
216
 
190
217
  route "GET /w/:slug/api/config" requires auth
218
+ private
191
219
  let cfg be provider.config()
192
220
  give {"provider": cfg["provider"], "model": cfg["model"], "wire": cfg["wire"], "vision": provider.supports_vision(cfg), "providers": provider.providers(), "configured": provider.configured(), "permission": lower(env("LAMPSON_PERMISSION", "ask")), "agents": agents.names(), "workspace": env("LAMPSON_WORKSPACE", "./workspace"), "profiles": agents.PROFILES}
193
221
 
194
222
  -- proveedor/modelo por defecto y API keys → .lampson/config.json (local). La key nunca vuelve al cliente.
195
223
  route "POST /w/:slug/api/settings" requires auth
224
+ private
196
225
  expect body {provider: text}
197
226
  let b be json of request
198
227
  let name be lower(text(b["provider"]))
@@ -206,11 +235,13 @@ serve on 8080
206
235
  give {"ok": true, "providers": provider.providers(), "provider": name, "model": ncfg["model"], "vision": provider.supports_vision(ncfg), "configured": provider.configured()}
207
236
 
208
237
  route "POST /w/:slug/api/sessions/delete" requires auth
238
+ private
209
239
  expect body {id: text}
210
240
  let b be json of request
211
241
  give {"result": session.delete(text(b["id"]))}
212
242
 
213
243
  route "GET /w/:slug/api/tree" requires auth
244
+ private
214
245
  let t be tree.tree(6)
215
246
  -- ruta real del proyecto (lampson.ps1/.sh exportan LAMPSON_WORKSPACE): «copiar ruta absoluta» en el explorador
216
247
  set t["root"] to env("LAMPSON_WORKSPACE", "")
@@ -223,6 +254,7 @@ serve on 8080
223
254
  -- Servidor → navegador: "o" + salida cruda del pty | "c" + JSON de control (hello | exit).
224
255
  -- Sin ningún socket enganchado por 30 min, el supervisor recoge la shell; todo muere con lampson.
225
256
  route "GET /w/:slug/api/term" requires auth
257
+ private
226
258
  socket
227
259
  state_set("lampson:last_used", now())
228
260
  let id be when contains(query, "id") then text(query.id) otherwise ""
@@ -270,28 +302,35 @@ serve on 8080
270
302
 
271
303
  -- las terminales vivas: la UI las repinta como pestañas al cargar (después de un F5 siguen ahí)
272
304
  route "GET /w/:slug/api/terms" requires auth
305
+ private
273
306
  give {"terminals": term.list(), "max": term.MAX_TERMS}
274
307
 
275
308
  route "GET /w/:slug/api/update" requires auth
309
+ private
276
310
  give update.check()
277
311
 
278
312
  route "POST /w/:slug/api/update" requires auth
313
+ private
279
314
  give {"result": update.apply()}
280
315
 
281
316
  route "GET /w/:slug/api/git" requires auth
317
+ private
282
318
  give git.status()
283
319
 
284
320
  route "GET /w/:slug/api/memory" requires auth
321
+ private
285
322
  -- ok=false: el link memory/ del workspace está roto (la UI lo dice; el agente ya lo sabe por el prompt)
286
323
  give {"dir": memo.dir(), "ok": memo.available(), "notes": memo.list()}
287
324
 
288
325
  route "GET /w/:slug/api/memory/note" requires auth
326
+ private
289
327
  when not contains(query, "name")
290
328
  give fail(400, "name required")
291
329
  give {"name": query.name, "content": memo.note_read(query.name)}
292
330
 
293
331
  -- traza legible de una sesión (ver lib/trace.syn)
294
332
  route "GET /w/:slug/api/trace" requires auth
333
+ private
295
334
  when not contains(query, "session")
296
335
  give fail(400, "session required")
297
336
  when not matches(query.session, "[A-Za-z0-9_-]{1,40}")
@@ -301,21 +340,25 @@ serve on 8080
301
340
 
302
341
  -- modelos que declara la API del proveedor (para no tipear nombres a ciegas: DeepSeek es case-sensitive)
303
342
  route "GET /w/:slug/api/models" requires auth
343
+ private
304
344
  let pname be when contains(query, "provider") then lower(text(query.provider)) otherwise ""
305
345
  let cfg be provider.config_for(pname, "")
306
346
  give provider.list_models(cfg)
307
347
 
308
348
  route "GET /w/:slug/api/todo" requires auth
349
+ private
309
350
  -- ?session=<id> → la lista de esa sesión; sin query, la de la sesión en curso
310
351
  when contains(query, "session") and matches(query.session, "[A-Za-z0-9_-]{1,40}")
311
352
  give {"items": todo.load(query.session)}
312
353
  give {"items": todo.load(nothing)}
313
354
 
314
355
  route "GET /w/:slug/api/mcp" requires auth
356
+ private
315
357
  give {"servers": mcp.summary(), "global": mcp.GLOBAL_CONFIG, "project": mcp.PROJECT_CONFIG}
316
358
 
317
359
  -- conectar un server MCP desde la UI: se escribe en el mcp.json del scope y arranca su supervisor
318
360
  route "POST /w/:slug/api/mcp/add" requires auth
361
+ private
319
362
  expect body {name: text, command: text}
320
363
  let b be json of request
321
364
  let scope be when contains(b, "scope") then lower(text(b["scope"])) otherwise "global"
@@ -326,6 +369,7 @@ serve on 8080
326
369
  give fail(400, text(err))
327
370
 
328
371
  route "POST /w/:slug/api/mcp/remove" requires auth
372
+ private
329
373
  expect body {name: text}
330
374
  let b be json of request
331
375
  try
@@ -335,9 +379,11 @@ serve on 8080
335
379
 
336
380
  -- language servers (navegación semántica): listar, agregar (preset o comando propio), quitar
337
381
  route "GET /w/:slug/api/lsp" requires auth
382
+ private
338
383
  give {"servers": lsp.summary(), "presets": lsp.PRESETS, "global": lsp.GLOBAL_CONFIG, "project": lsp.PROJECT_CONFIG}
339
384
 
340
385
  route "POST /w/:slug/api/lsp/add" requires auth
386
+ private
341
387
  expect body {name: text}
342
388
  let b be json of request
343
389
  let scope be when contains(b, "scope") then lower(text(b["scope"])) otherwise "global"
@@ -349,6 +395,7 @@ serve on 8080
349
395
  give fail(400, text(err))
350
396
 
351
397
  route "POST /w/:slug/api/lsp/remove" requires auth
398
+ private
352
399
  expect body {name: text}
353
400
  let b be json of request
354
401
  try
@@ -358,10 +405,12 @@ serve on 8080
358
405
 
359
406
  -- plugins (tools propias): listar y encender/apagar desde la barra superior de la UI
360
407
  route "GET /w/:slug/api/plugins" requires auth
408
+ private
361
409
  give {"plugins": plugins.summary(), "global": plugins.GLOBAL_DIR, "project": plugins.PROJECT_DIR}
362
410
 
363
411
  -- el usuario corre una tool de un plugin encendido él mismo (sin pasar por el modelo)
364
412
  route "POST /w/:slug/api/plugins/run" requires auth
413
+ private
365
414
  expect body {tool: text}
366
415
  let b be json of request
367
416
  let args be when contains(b, "args") then b["args"] otherwise {}
@@ -371,6 +420,7 @@ serve on 8080
371
420
  give fail(400, text(err))
372
421
 
373
422
  route "POST /w/:slug/api/plugins/remove" requires auth
423
+ private
374
424
  expect body {name: text}
375
425
  let b be json of request
376
426
  try
@@ -379,6 +429,7 @@ serve on 8080
379
429
  give fail(400, text(err))
380
430
 
381
431
  route "POST /w/:slug/api/plugins/toggle" requires auth
432
+ private
382
433
  expect body {name: text}
383
434
  let b be json of request
384
435
  let on be contains(b, "enabled") and b["enabled"] == true
@@ -388,6 +439,7 @@ serve on 8080
388
439
  give fail(400, text(err))
389
440
 
390
441
  route "GET /w/:slug/api/agents" requires auth
442
+ private
391
443
  agents.prune(10, 1800)
392
444
  give {"agents": agents.list_children()}
393
445
 
@@ -395,6 +447,7 @@ serve on 8080
395
447
  -- cambios de estado) y los subagentes (subagent.started|done|<id>). Un bus por programa; cada cliente
396
448
  -- tiene su cola acotada (drop_oldest). Heartbeat cada 25 s para que el proxy/navegador no cierre.
397
449
  route "GET /w/:slug/api/events" requires auth
450
+ private
398
451
  stream
399
452
  state_set("lampson:last_used", now())
400
453
  let sub be bus_subscribe(["proc.*", "subagent.*", "mcp.*", "approval.*", "schedule.*"], {"max_queue": 512})
@@ -411,6 +464,7 @@ serve on 8080
411
464
  bus_unsubscribe(sub)
412
465
 
413
466
  route "GET /w/:slug/api/agents/log" requires auth
467
+ private
414
468
  when not contains(query, "id")
415
469
  give fail(400, "id required")
416
470
  when not matches(query.id, "[a-z]+-[0-9]+")
@@ -426,6 +480,7 @@ serve on 8080
426
480
  give fail(404, "no such sub-agent")
427
481
 
428
482
  route "POST /w/:slug/api/agents/stop" requires auth
483
+ private
429
484
  expect body {id: text}
430
485
  let b be json of request
431
486
  when not matches(b["id"], "[a-z]+-[0-9]+")
@@ -435,28 +490,34 @@ serve on 8080
435
490
  give {"result": "stop requested for " + b["id"]}
436
491
 
437
492
  route "GET /w/:slug/api/proc" requires auth
493
+ private
438
494
  give {"processes": proc.list()}
439
495
 
440
496
  route "GET /w/:slug/api/proc/log" requires auth
497
+ private
441
498
  when not contains(query, "name")
442
499
  give fail(400, "name required")
443
500
  let n be when contains(query, "tail") then number(query.tail) otherwise 200
444
501
  give {"name": query.name, "running": proc.alive(query.name), "log": proc.logs(query.name, n)}
445
502
 
446
503
  route "GET /w/:slug/api/ports" requires auth
504
+ private
447
505
  give {"ports": proc.listeners()}
448
506
 
449
507
  route "POST /w/:slug/api/ports/kill" requires auth
508
+ private
450
509
  expect body {pid: number}
451
510
  let b be json of request
452
511
  give {"result": proc.kill_pid(b["pid"])}
453
512
 
454
513
  route "POST /w/:slug/api/proc/stop" requires auth
514
+ private
455
515
  expect body {name: text}
456
516
  let b be json of request
457
517
  give {"result": proc.halt(b["name"])}
458
518
 
459
519
  route "GET /w/:slug/api/file" requires auth
520
+ private
460
521
  when not contains(query, "path")
461
522
  give fail(400, "path required")
462
523
  give tree.file_content(query.path)
@@ -464,6 +525,7 @@ serve on 8080
464
525
  -- explorador: nuevo archivo/carpeta, renombrar, mover, copiar/duplicar, borrar (lib/fs.syn; solo dentro
465
526
  -- del workspace, nunca pisa un destino). {op, path, name?, to?, content?} → {ok, result: {path, is_dir}}
466
527
  route "POST /w/:slug/api/fs" requires auth
528
+ private
467
529
  expect body {op: text, path: text}
468
530
  let b be json of request
469
531
  try
@@ -473,9 +535,11 @@ serve on 8080
473
535
 
474
536
  -- configuración general (rueda de la UI): zona horaria, URL pública, webhook… → .lampson/config.json
475
537
  route "GET /w/:slug/api/settings/values" requires auth
538
+ private
476
539
  give {"values": settings.values(), "tz_detected": schedule.tz_offset()}
477
540
 
478
541
  route "POST /w/:slug/api/settings/values" requires auth
542
+ private
479
543
  let b be json of request
480
544
  try
481
545
  each k in keys(b)
@@ -489,9 +553,11 @@ serve on 8080
489
553
  -- computer use (lib/computer.syn): estado del driver externo (instalado, versión, doctor) y encendido/apagado.
490
554
  -- Lampson no instala el driver: si falta, `install` trae el comando oficial y la UI lo muestra.
491
555
  route "GET /w/:slug/api/computer" requires auth
556
+ private
492
557
  give computer.status()
493
558
 
494
559
  route "POST /w/:slug/api/computer" requires auth
560
+ private
495
561
  let b be json of request
496
562
  try
497
563
  when contains(b, "enabled")
@@ -510,9 +576,11 @@ serve on 8080
510
576
  -- el juez de decisión (lib/judge.syn): una credencial de Lampson, no de computer use. El runtime lo lee al
511
577
  -- arrancar el proceso, así que cambiarlo reinicia este workspace solo en ~3 s (la UI espera y recarga).
512
578
  route "GET /w/:slug/api/judge" requires auth
579
+ private
513
580
  give jdg.status()
514
581
 
515
582
  route "POST /w/:slug/api/judge" requires auth
583
+ private
516
584
  let b be json of request
517
585
  try
518
586
  let cur be jdg.status()
@@ -532,16 +600,19 @@ serve on 8080
532
600
 
533
601
  -- aprobaciones (lib/approvals.syn): las del chat y las de tareas programadas comparten la cola
534
602
  route "POST /w/:slug/api/approve" requires auth
603
+ private
535
604
  expect body {id: text, decision: bool}
536
605
  let b be json of request
537
606
  give {"ok": approvals.answer(text(b["id"]), b["decision"])}
538
607
 
539
608
  route "GET /w/:slug/api/approvals" requires auth
609
+ private
540
610
  give {"approvals": approvals.list(), "public_url": approvals.public_url(), "webhook": approvals.webhook_url() != ""}
541
611
 
542
612
  -- link de decisión (PÚBLICO a propósito: lo abre el humano desde el teléfono; el token de un solo uso es la
543
613
  -- autorización, como en el `approve` nativo de Synsema bajo serve). GET porque un link en un chat es un GET.
544
614
  route "GET /w/:slug/approve/:id/:token"
615
+ private
545
616
  let d be when contains(query, "d") then lower(text(query.d)) otherwise ""
546
617
  when d != "yes" and d != "no"
547
618
  give html(approvals.html_page("¿Permitir?", "<a href='?d=yes' style='display:inline-block;padding:10px 18px;border-radius:4px;background:#1d1c1a;color:#fff;text-decoration:none;margin-right:10px'>Sí, permitir</a> <a href='?d=no' style='display:inline-block;padding:10px 18px;border-radius:4px;border:1px solid #a33;color:#a33;text-decoration:none'>No, denegar</a>"))
@@ -552,11 +623,13 @@ serve on 8080
552
623
 
553
624
  -- tareas programadas (lib/schedule.syn): listar, crear, quitar, encender/apagar, correr ahora, log
554
625
  route "GET /w/:slug/api/schedules" requires auth
626
+ private
555
627
  let age be schedule.daemon_age()
556
628
  -- este proceso tiene su propio tick (cron_every): las tareas corren mientras la web esté abierta
557
629
  give {"tasks": schedule.summary(), "tick": schedule.TICK_SECONDS, "alive": true, "heartbeat_age": age, "mount_ok": schedule.mount_ok(), "workspace": env("LAMPSON_WORKSPACE", ""), "tz": schedule.tz_offset(), "plugins": plugins.summary()}
558
630
 
559
631
  route "POST /w/:slug/api/schedules/add" requires auth
632
+ private
560
633
  let b be json of request
561
634
  try
562
635
  let t be schedule.add(b)
@@ -565,6 +638,7 @@ serve on 8080
565
638
  give fail(400, text(err))
566
639
 
567
640
  route "POST /w/:slug/api/schedules/remove" requires auth
641
+ private
568
642
  expect body {id: text}
569
643
  let b be json of request
570
644
  try
@@ -573,6 +647,7 @@ serve on 8080
573
647
  give fail(400, text(err))
574
648
 
575
649
  route "POST /w/:slug/api/schedules/toggle" requires auth
650
+ private
576
651
  expect body {id: text}
577
652
  let b be json of request
578
653
  let on be contains(b, "enabled") and b["enabled"] == true
@@ -584,6 +659,7 @@ serve on 8080
584
659
  -- correr ahora: la marca run_now la levanta el próximo tick (así el request no se queda minutos abierto
585
660
  -- y la corrida vive en el hilo del cron, no en el del request)
586
661
  route "POST /w/:slug/api/schedules/run" requires auth
662
+ private
587
663
  expect body {id: text}
588
664
  let b be json of request
589
665
  try
@@ -593,12 +669,14 @@ serve on 8080
593
669
  give fail(400, text(err))
594
670
 
595
671
  route "GET /w/:slug/api/schedules/log" requires auth
672
+ private
596
673
  when not contains(query, "id")
597
674
  give fail(400, "id required")
598
675
  let n be when contains(query, "tail") then floor(number(query.tail)) otherwise 300
599
676
  give {"id": query.id, "log": schedule.log_tail(query.id, n), "task": schedule.get(query.id)}
600
677
 
601
678
  route "POST /w/:slug/api/chat" requires auth
679
+ private
602
680
  expect body {message: text}
603
681
  let b be json of request
604
682
  let message be b["message"]
@@ -611,8 +689,8 @@ serve on 8080
611
689
  let pmodel be when contains(b, "model") then text(b["model"]) otherwise ""
612
690
  state_set("lampson:last_used", now())
613
691
  stream
692
+ -- el runtime (lib/runtime.syn) ya traza cada evento en .lampson/trace/<sid>.log: acá solo se reenvían por SSE
614
693
  task emit(kind, data, tag)
615
- trace.event(sid, kind, data, tag)
616
694
  send {"kind": kind, "data": data, "tag": tag} as "event"
617
695
  -- aprobación humana: la cola de lib/approvals.syn (id + token) — la UI responde por SSE/POST /api/approve,
618
696
  -- y si hay webhook/LAMPSON_PUBLIC_URL también llega un link al canal del usuario (aprobar desde el móvil)
@@ -623,38 +701,30 @@ serve on 8080
623
701
  let ok be approvals.wait(id, APPROVAL_TIMEOUT)
624
702
  send {"kind": "approval_result", "data": {"id": id, "approved": ok, "timeout": (not ok) and now() - t0 >= APPROVAL_TIMEOUT - 1}} as "event"
625
703
  give ok
626
- let ctx be boot(want, mode, ask_web, pname, pmodel)
627
- let messages be [ctx["system"]]
628
- when sid != ""
629
- when session.exists(sid)
630
- let prev_doc be session.load(sid)
631
- let prev be prev_doc["messages"]
632
- set messages to [ctx["system"]] + slice(prev, 1, length(prev))
633
- -- sesión guardada por otra corrida de lampson: sus procesos ya no viven — decírselo
634
- -- al modelo con el estado real (una sola vez: el próximo save re-estampa meta.run)
635
- when session.from_other_run(prev_doc)
636
- let note be proc.resume_note(sid)
637
- when note != ""
638
- set messages to append(messages, {"role": "user", "content": note})
639
- trace.event(sid, "inbox", note, "")
640
- send {"kind": "inbox", "data": note, "tag": ""} as "event"
641
- otherwise
642
- set sid to ""
643
- when sid == ""
644
- set sid to session.new_id()
645
- -- sesión actual (blackboard): la tool todo guarda su lista por sesión (lib/tools/todo.syn)
646
- share {"id": sid} as "lampson:session"
647
- send {"kind": "session", "data": sid} as "event"
648
- send {"kind": "mode", "data": {"agent": ctx["profile"], "permission": mode, "provider": ctx["cfg"]["provider"], "model": ctx["cfg"]["model"], "has_key": ctx["cfg"]["has_key"]}} as "event"
704
+ task on_start(info)
705
+ set sid to info["session"]
706
+ send {"kind": "session", "data": sid} as "event"
707
+ send {"kind": "mode", "data": {"agent": info["agent"], "permission": info["mode"], "provider": info["provider"], "model": info["model"], "has_key": info["has_key"]}} as "event"
708
+ -- worker es interno de delegate: por la API tampoco se elige como agente de sesión
709
+ when not contains(runtime.names(), want)
710
+ set want to "build"
711
+ let sobre be {"to": want, "session": sid, "from": {"id": "", "name": "", "kind": "human"}, "text": message, "images": [], "channel": "web", "meta": {}}
712
+ let hooks be {"mode": mode, "provider": pname, "model": pmodel, "ask_fn": ask_web, "on_event": emit, "on_start": on_start}
649
713
  when starts_with(trim(message), "!")
650
714
  -- comando del USUARIO: sin política de permisos, salida al contexto; el modelo no interviene
715
+ let o be runtime.open(sobre, hooks)
716
+ let cfg be o["ctx"]["cfg"]
717
+ on_start({"session": o["session"], "agent": o["ctx"]["agent"], "thread": o["thread"], "mode": o["mode"], "provider": cfg["provider"], "model": cfg["model"], "has_key": cfg["has_key"]})
718
+ when o["note"] != ""
719
+ trace.event(sid, "inbox", o["note"], "")
720
+ send {"kind": "inbox", "data": o["note"], "tag": ""} as "event"
651
721
  let cmd be trim(slice(trim(message), 1, length(trim(message))))
652
722
  let bash_tool be agents.registry_for("build")["bash"]
653
723
  send {"kind": "tool_call", "data": {"id": "user", "name": "bash", "args": {"command": cmd}}} as "event"
654
724
  let out be call_tool(bash_tool, {"command": cmd, "timeout": 600})
655
725
  send {"kind": "tool_result", "data": {"call": {"id": "user", "name": "bash", "args": {"command": cmd}}, "output": out}} as "event"
656
- set messages to append(messages, {"role": "user", "content": "[The user ran this command in the shell themselves]\n$ " + cmd + "\n" + tools.truncate(out, 6000)})
657
- session.save(sid, messages, {"title": session.title_of(messages)})
726
+ let messages be append(o["messages"], {"role": "user", "content": "[The user ran this command in the shell themselves]\n$ " + cmd + "\n" + tools.truncate(out, 6000)})
727
+ runtime.save(o, messages)
658
728
  send {"kind": "done", "data": {"text": "", "steps": 0, "usage": {"input": 0, "output": 0}, "stopped": "user_command", "session": sid}} as "event"
659
729
  otherwise
660
730
  -- imágenes pegadas en la UI: [{media_type, data(base64)}] — el cliente ya las redujo; tope 5 MB por mensaje
@@ -669,12 +739,210 @@ serve on 8080
669
739
  when contains(im, "w") and contains(im, "h")
670
740
  set entry to {"media_type": text(im["media_type"]), "data": text(im["data"]), "w": floor(number(im["w"])), "h": floor(number(im["h"]))}
671
741
  set images to append(images, entry)
672
- let umsg be {"role": "user", "content": message}
673
- when length(images) > 0
674
- set umsg to {"role": "user", "content": message, "images": images}
675
- set messages to append(messages, umsg)
676
- trace.user(sid, message, ctx["profile"], mode, ctx["cfg"]["model"])
677
- let result be loop.run_turn(ctx["cfg"], messages, ctx["opts"], emit)
678
- trace.turn_end(sid, result)
679
- session.save(sid, result["messages"], {"title": session.title_of(result["messages"])})
680
- send {"kind": "done", "data": {"text": result["text"], "steps": result["steps"], "usage": result["usage"], "stopped": result["stopped"], "session": sid}} as "event"
742
+ set sobre["images"] to images
743
+ let result be runtime.deliver(sobre, hooks)
744
+ send {"kind": "done", "data": {"text": result["text"], "steps": result["steps"], "usage": result["usage"], "stopped": result["stopped"], "session": result["session"]}} as "event"
745
+
746
+ -- ---------- API /v1 para apps (lib/api.syn · spec/engine.md fase 2) ----------
747
+ -- Sin `requires auth`: bajo el hub todo llega por loopback y check_client lo daría por bueno. La API exige SIEMPRE
748
+ -- una API key (Authorization: Bearer lk_…), que valida api.authorize.
749
+ -- el OpenAPI de la API pública (solo /v1: el resto lleva `private`), por la ruta /v1 que el hub sí reenvía
750
+ route "GET /w/:slug/v1/openapi.json"
751
+ private
752
+ give respond(openapi_json(), "application/json")
753
+
754
+ route "GET /w/:slug/v1/agents" requires auth
755
+ let a be api.authorize(headers of request)
756
+ when not a["ok"]
757
+ give api.refuse(a)
758
+ give {"agents": api.agents_for(a["key"])}
759
+
760
+ route "POST /w/:slug/v1/messages" requires auth
761
+ expect body {text: text}
762
+ let a be api.authorize(headers of request)
763
+ when not a["ok"]
764
+ give api.refuse(a)
765
+ let p be api.parse(json of request, a["key"])
766
+ when not p["ok"]
767
+ give fail(p["status"], p["error"])
768
+ state_set("lampson:last_used", now())
769
+ -- todo pasa por el buzón de la conversación (lib/mailbox.syn): fila, espera de silencio, mitad de turno
770
+ let mo be api.mailbox_opts(p["sobre"])
771
+ when p["callback"] != ""
772
+ let jid be mailbox.new_id()
773
+ api.create_job(jid, a["key"], p["sobre"], p["callback"])
774
+ mailbox.submit(p["sobre"], merge(mo, {"id": jid, "callback": p["callback"], "job": true}))
775
+ give respond(json_encode({"job": jid, "status": "queued"}), "application/json", 202)
776
+ let s be mailbox.submit(p["sobre"], mo)
777
+ give mailbox.wait(s["id"])
778
+
779
+ route "POST /w/:slug/v1/messages/stream" requires auth
780
+ expect body {text: text}
781
+ let a be api.authorize(headers of request)
782
+ when not a["ok"]
783
+ give api.refuse(a)
784
+ let p be api.parse(json of request, a["key"])
785
+ when not p["ok"]
786
+ give fail(p["status"], p["error"])
787
+ state_set("lampson:last_used", now())
788
+ let sobre be p["sobre"]
789
+ let mo be api.mailbox_opts(sobre)
790
+ -- suscripto ANTES de encolar: el worker publica en el bus los eventos de la conversación
791
+ let mid be mailbox.new_id()
792
+ let sub be bus_subscribe("lampson.mb." + mailbox.key_of(sobre, mid))
793
+ mailbox.submit(sobre, merge(mo, {"id": mid}))
794
+ stream
795
+ let finished be false
796
+ let deadline be now() + mailbox.WAIT_TIMEOUT
797
+ while not finished and now() < deadline
798
+ let ev be bus_recv(sub, 1)
799
+ when ev != nothing
800
+ let d be ev["data"]
801
+ when d["kind"] == "done"
802
+ -- el done de un lote anterior de la misma conversación no es el nuestro
803
+ when contains(d["data"]["batch"], mid)
804
+ state_delete("mb:res:" + mid)
805
+ send d as "event"
806
+ set finished to true
807
+ otherwise
808
+ send d as "event"
809
+ -- por si el done pasó mientras no estábamos escuchando
810
+ when not finished
811
+ let r be state_get("mb:res:" + mid, nothing)
812
+ when r != nothing
813
+ state_delete("mb:res:" + mid)
814
+ send {"kind": "done", "data": r, "tag": "", "agent": r["agent"], "thread": r["thread"]} as "event"
815
+ set finished to true
816
+ bus_unsubscribe(sub)
817
+
818
+ -- MCP por HTTP (lib/mcp_server.syn, "Streamable HTTP" con respuestas JSON): Claude, Cursor u otro agente usan los
819
+ -- agentes de este workspace desde cualquier lado, con la API key. Una notificación → 202 sin cuerpo.
820
+ route "POST /w/:slug/v1/mcp" requires auth
821
+ expect body {jsonrpc: text, method: text}
822
+ let a be api.authorize(headers of request)
823
+ when not a["ok"]
824
+ give with_header(fail(a["status"], a["error"]), "WWW-Authenticate", "Bearer")
825
+ state_set("lampson:last_used", now())
826
+ let offered be apply((x) => x["id"], api.agents_for(a["key"]))
827
+ when length(offered) == 0
828
+ give fail(403, "this API key has no agents")
829
+ let resp be mcp_server.handle(json of request, offered, api.mcp_deliver)
830
+ when resp == nothing
831
+ give respond("", "application/json", 202)
832
+ give resp
833
+
834
+ -- la misma conversación MCP pero con respuestas SSE: si el pedido trae params._meta.progressToken, cada paso del
835
+ -- agente sale como notifications/progress antes de la respuesta. Ruta aparte porque en Synsema una ruta transmite
836
+ -- o no (un `stream` dentro de un `when` no transmite) y /v1/mcp debe contestar 202 vacío a las notificaciones.
837
+ route "POST /w/:slug/v1/mcp/stream" requires auth
838
+ expect body {jsonrpc: text, method: text}
839
+ let a be api.authorize(headers of request)
840
+ let offered be when a["ok"] then apply((x) => x["id"], api.agents_for(a["key"])) otherwise []
841
+ let req be json of request
842
+ let ptoken be nothing
843
+ when contains(req, "params") and type_of(req["params"]) == "map" and contains(req["params"], "_meta") and type_of(req["params"]["_meta"]) == "map" and contains(req["params"]["_meta"], "progressToken")
844
+ set ptoken to req["params"]["_meta"]["progressToken"]
845
+ stream
846
+ -- un ask por el buzón, mirando el bus de la conversación para el progreso
847
+ task deliver_sse(sobre, mode)
848
+ let mid be mailbox.new_id()
849
+ let sub be bus_subscribe("lampson.mb." + mailbox.key_of(sobre, mid))
850
+ mailbox.submit(sobre, {"mode": mode, "buffer": mailbox.buffer_of(runtime.get(sobre["to"]), false), "id": mid})
851
+ let n be 0
852
+ let result be nothing
853
+ let deadline be now() + mailbox.WAIT_TIMEOUT
854
+ while result == nothing and now() < deadline
855
+ let ev be bus_recv(sub, 1)
856
+ when ev != nothing
857
+ let d be ev["data"]
858
+ when d["kind"] == "done" and contains(d["data"]["batch"], mid)
859
+ set result to d["data"]
860
+ otherwise when ptoken != nothing and (d["kind"] == "assistant" or d["kind"] == "tool_call")
861
+ set n to n + 1
862
+ let what be when d["kind"] == "tool_call" then "using " + text(d["data"]["name"]) otherwise slice(text(d["data"]), 0, 200)
863
+ send {"jsonrpc": "2.0", "method": "notifications/progress", "params": {"progressToken": ptoken, "progress": n, "message": what}} as "message"
864
+ when result == nothing
865
+ let r be state_get("mb:res:" + mid, nothing)
866
+ when r != nothing
867
+ set result to r
868
+ state_delete("mb:res:" + mid)
869
+ bus_unsubscribe(sub)
870
+ give when result == nothing then {"agent": sobre["to"], "thread": sobre["thread"], "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: timed out"} otherwise result
871
+ when not a["ok"]
872
+ send {"jsonrpc": "2.0", "id": nothing, "error": {"code": -32001, "message": a["error"]}} as "message"
873
+ otherwise when length(offered) == 0
874
+ send {"jsonrpc": "2.0", "id": nothing, "error": {"code": -32001, "message": "this API key has no agents"}} as "message"
875
+ otherwise
876
+ state_set("lampson:last_used", now())
877
+ let resp be mcp_server.handle(req, offered, deliver_sse)
878
+ when resp != nothing
879
+ send resp as "message"
880
+
881
+ route "GET /w/:slug/v1/mcp"
882
+ give fail(405, "this MCP server does not open a server-to-client stream; POST JSON-RPC messages")
883
+
884
+ -- ---------- panel de la UI: API keys y canales (privadas: son de la UI, autenticadas por el hub/local) ----------
885
+ route "GET /w/:slug/api/keys" requires auth
886
+ private
887
+ let pub be approvals.public_url()
888
+ let base be (when pub != "" then pub otherwise "http://127.0.0.1:8080") + "/w/" + env("LAMPSON_WS", "local") + "/v1"
889
+ give {"keys": apikeys.list(), "api_url": base + "/messages", "mcp_url": base + "/mcp", "public": pub != "", "agents": runtime.names()}
890
+
891
+ route "POST /w/:slug/api/keys/add" requires auth
892
+ private
893
+ let b be json of request
894
+ let ag be when b != nothing and contains(b, "agents") and type_of(b["agents"]) == "list" then b["agents"] otherwise []
895
+ each a in ag
896
+ when a != "*" and not contains(runtime.names(), text(a))
897
+ give fail(400, "no agent named '" + text(a) + "'")
898
+ let cbs be when b != nothing and contains(b, "callbacks") and type_of(b["callbacks"]) == "list" then b["callbacks"] otherwise []
899
+ each cb in cbs
900
+ when not (starts_with(text(cb), "https://") or starts_with(text(cb), "http://"))
901
+ give fail(400, "a callback prefix must be an http(s) URL")
902
+ let ko be {"callbacks": cbs}
903
+ when b != nothing and contains(b, "rate") and b["rate"] != nothing and text(b["rate"]) != ""
904
+ set ko["rate"] to floor(number(b["rate"]))
905
+ give apikeys.create_with(when b != nothing and contains(b, "name") then text(b["name"]) otherwise "", ag, ko)
906
+
907
+ route "POST /w/:slug/api/keys/remove" requires auth
908
+ private
909
+ expect body {id: text}
910
+ give {"ok": apikeys.remove(text((json of request)["id"]))}
911
+
912
+ route "GET /w/:slug/api/channels" requires auth
913
+ private
914
+ give {"channels": channels.summary(approvals.public_url(), env("LAMPSON_WS", "local")), "public": approvals.public_url() != ""}
915
+
916
+ route "POST /w/:slug/api/channels/toggle" requires auth
917
+ private
918
+ expect body {name: text, on: bool}
919
+ let b be json of request
920
+ give {"ok": plugins.set_enabled(text(b["name"]), b["on"])}
921
+
922
+ route "POST /w/:slug/api/channels/setup" requires auth
923
+ private
924
+ expect body {name: text}
925
+ give channels.setup_channel(text((json of request)["name"]), approvals.public_url(), env("LAMPSON_WS", "local"))
926
+
927
+ -- ---------- canales (lib/channels.syn · spec/engine.md fase 4) ----------
928
+ -- El webhook de la plataforma. Sin auth de Lampson: la firma de la plataforma la verifica el plugin en `receive`
929
+ -- (recibe el body exacto). GET para las verificaciones de webhook (Meta, Slack…), que el plugin contesta con "http".
930
+ route "POST /w/:slug/ch/:name"
931
+ private
932
+ state_set("lampson:last_used", now())
933
+ let r be channels.handle(params.name, {"method": "POST", "path": request.path, "query": query, "headers": headers of request, "body": read_body()})
934
+ give respond(r["body"], r["ctype"], r["status"])
935
+
936
+ route "GET /w/:slug/ch/:name"
937
+ private
938
+ let r be channels.handle(params.name, {"method": "GET", "path": request.path, "query": query, "headers": headers of request, "body": ""})
939
+ give respond(r["body"], r["ctype"], r["status"])
940
+
941
+ route "GET /w/:slug/v1/jobs/:id" requires auth
942
+ let a be api.authorize(headers of request)
943
+ when not a["ok"]
944
+ give api.refuse(a)
945
+ let j be api.job(params.id)
946
+ when j == nothing or j["key"] != a["key"]["id"]
947
+ give fail(404, "no such job")
948
+ give j