lampson 0.3.0 → 0.4.1

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/lib/mailbox.syn CHANGED
@@ -22,6 +22,7 @@
22
22
  -- resultados, entrega los callbacks (uno por lote y por URL) y se va cuando la fila queda vacía. Tomar la fila y
23
23
  -- soltar el worker ocurren bajo el mismo lock: un mensaje que llega en ese instante nunca queda huérfano.
24
24
 
25
+ use "./teams.syn" as teams
25
26
  use "./runtime.syn" as runtime
26
27
  use "./loop.syn" as loop
27
28
  use "./agents.syn" as agents
@@ -97,6 +98,13 @@ export task post(k, item)
97
98
  unlock(k)
98
99
  give claim
99
100
 
101
+ -- ¿hay un worker atendiendo la conversación (agente, thread)? (la pantalla de equipos lo muestra en vivo)
102
+ export task working(agent, thread)
103
+ try
104
+ give state_get("mb:w:" + runtime.thread_key(agent, thread), false) == true
105
+ recover err
106
+ give false
107
+
100
108
  -- saca todo lo encolado
101
109
  task take(k)
102
110
  lock(k)
@@ -189,8 +197,10 @@ export task approve_queue(name, args, why)
189
197
  require env("LAMPSON_*")
190
198
  require file.read(".lampson")
191
199
  require file.read(".lampson/*")
192
- let id be approvals.open("api", permission.describe_call(name, args), why, APPROVAL_TIMEOUT)
193
- give approvals.wait(id, APPROVAL_TIMEOUT)
200
+ -- tocar la historia compartida (merge a main desde la copia de un agente): la persona tiene 30 min, no 3
201
+ let tmo be when contains(text(why), "shared history") then 1800 otherwise APPROVAL_TIMEOUT
202
+ let id be approvals.open("api", permission.describe_call(name, args), why, tmo)
203
+ give approvals.wait_detail(id, tmo)
194
204
 
195
205
  -- ---------- el worker ----------
196
206
 
@@ -209,6 +219,7 @@ task user_msg(it)
209
219
 
210
220
  -- un lote: un turno con todos los mensajes (y los que lleguen mientras), resultados, callbacks, jobs
211
221
  task run_batch(k, spec, items)
222
+ require db(".lampson/teams.db")
212
223
  require net
213
224
  require exec
214
225
  require time
@@ -277,7 +288,7 @@ task run_batch(k, spec, items)
277
288
  give nothing
278
289
  give {"messages": msgs, "stop": halt}
279
290
  let ctx be o["ctx"]
280
- set ctx["opts"] to loop.with_inbox(ctx["opts"], mid, "")
291
+ set ctx["opts"] to loop.with_final_inbox(loop.with_inbox(ctx["opts"], mid, ""))
281
292
  set o["ctx"] to ctx
282
293
  let msgs be o["messages"]
283
294
  each it in ordered
@@ -287,6 +298,13 @@ task run_batch(k, spec, items)
287
298
  set result to {"agent": o["ctx"]["agent"], "thread": o["thread"], "session": o["session"], "text": r["text"], "steps": r["steps"], "usage": r["usage"], "stopped": r["stopped"]}
288
299
  recover err
289
300
  set result to {"agent": lead["to"], "thread": lead["thread"], "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
301
+ -- equipos y objetivos: un turno que falló (proveedor caído, error del runtime) queda en el registro del equipo —
302
+ -- lo ven el líder en su próximo turno y la pantalla; si no, el equipo esperaría en silencio
303
+ when starts_with(text(result["stopped"]), "error") and (starts_with(text(lead["thread"]), "team:") or starts_with(text(lead["thread"]), "objective:"))
304
+ try
305
+ teams.log(lead["thread"], result["agent"], "error", "", "turn failed: " + slice(text(result["stopped"]), 0, 300))
306
+ recover err
307
+ set err to err
290
308
  let ids be apply((it) => it["id"], all)
291
309
  set result["batch"] to ids
292
310
  set result["lead"] to lead["id"]
@@ -339,6 +357,7 @@ task run_batch(k, spec, items)
339
357
  give result
340
358
 
341
359
  export task work(spec_json)
360
+ require db(".lampson/teams.db")
342
361
  require net
343
362
  require exec
344
363
  require time
@@ -374,6 +393,7 @@ export task work(spec_json)
374
393
  -- MIGA runtime (igual que agents.Child): un `agent` solo ve sus parámetros, las builtins y las tasks TOP-LEVEL del
375
394
  -- entry. web.syn define `task lampson_mailbox_worker(spec_json) give mailbox.work(spec_json)`.
376
395
  agent MailboxWorker
396
+ require db(".lampson/teams.db")
377
397
  require net
378
398
  require exec
379
399
  require time
@@ -413,6 +433,8 @@ export task submit(sobre, opts)
413
433
  set sent to sobre["meta"]["sent_at"]
414
434
  let item be {"id": id, "to": sobre["to"], "thread": sobre["thread"], "session": sobre["session"], "text": sobre["text"], "images": sobre["images"], "channel": sobre["channel"], "meta": sobre["meta"], "from": sobre["from"], "sent_at": sent, "arrived": now(), "callback": when contains(opts, "callback") then opts["callback"] otherwise "", "job": contains(opts, "job") and opts["job"] == true, "reply_channel": when contains(opts, "reply_channel") then opts["reply_channel"] otherwise "", "reply_thread": when contains(opts, "reply_thread") then opts["reply_thread"] otherwise ""}
415
435
  when post(k, item)
416
- let buf be opts["buffer"]
436
+ -- el worker espera {quiet_s, max_s}: false/nothing (sin espera) se normaliza acá — con `false` el worker
437
+ -- moría al primer settle y la conversación quedaba trabada (visto 2026-10-16)
438
+ let buf be when contains(opts, "buffer") and type_of(opts["buffer"]) == "map" then opts["buffer"] otherwise buffer_of(nothing, false)
417
439
  spawn MailboxWorker with spec_json = json_encode({"key": k, "mode": opts["mode"], "buffer": buf})
418
440
  give {"id": id, "key": k}
package/lib/plugins.syn CHANGED
@@ -11,6 +11,9 @@
11
11
  -- "tools": [{"name", "description", "parameters": {JSON Schema}, "readonly": false}],
12
12
  -- "config": ["CHATWOOT_TOKEN", …] (opcional: el hijo recibe PLUGIN_<X> = LAMPSON_<X> del .env/entorno;
13
13
  -- así un plugin syn con techo env=PLUGIN_* también tiene sus secretos)
14
+ -- "instructions": "INSTRUCTIONS.md" (opcional: cómo usar sus tools — texto, o un .md de su carpeta;
15
+ -- sin el campo, INSTRUCTIONS.md si existe. Va al prompt de cada
16
+ -- agente que tenga alguna de sus tools: el plugin trae su proceso)
14
17
  -- "channel": {"agent": "tienda"}} (opcional: un CANAL — lib/channels.syn. Sus acciones `receive` y
15
18
  -- `send` no son tools del modelo, así que un canal puede no tener tools)
16
19
  --
@@ -49,6 +52,7 @@ let LEGACY_STATE_FILE be ".lampson/lamps.json"
49
52
  export let PREFIX be "plugin_"
50
53
  export let LEGACY_HINT be "old .lampson/lamps/ folder — rename it to .lampson/plugins/ (and lamp.json to plugin.json)"
51
54
  let DEFAULT_TIMEOUT be 60
55
+ let MAX_INSTRUCTIONS be 12000
52
56
  let BASE_CAPS be "stdout,time,env=PLUGIN_*,env=LAMP_*"
53
57
 
54
58
  -- nombre de plugin: SIN "_" (el separador de plugin_<plugin>_<tool>); las tools sí pueden llevarlo
@@ -102,7 +106,17 @@ task read_manifest(dir, name, scope, legacy)
102
106
  when not contains(t, "name") or not valid_tool_name(t["name"])
103
107
  give {"ok": false, "name": name, "scope": scope, "legacy": is_legacy, "error": "a tool has no valid name"}
104
108
  set tools to append(tools, {"name": text(t["name"]), "description": when contains(t, "description") then text(t["description"]) otherwise "", "parameters": when contains(t, "parameters") then t["parameters"] otherwise {"type": "object", "properties": {}}, "readonly": contains(t, "readonly") and t["readonly"] == true})
105
- give {"ok": true, "name": name, "scope": scope, "legacy": is_legacy, "plugin": {"name": name, "scope": scope, "dir": dir + "/" + name, "kind": kind, "legacy": is_legacy, "description": when contains(doc, "description") then text(doc["description"]) otherwise "", "entry": when contains(doc, "entry") then text(doc["entry"]) otherwise "", "command": when contains(doc, "command") then text(doc["command"]) otherwise "", "caps": when contains(doc, "caps") then text(doc["caps"]) otherwise "", "timeout": when contains(doc, "timeout") then floor(number(doc["timeout"])) otherwise DEFAULT_TIMEOUT, "tools": tools, "channel": channel, "config": config}}
109
+ -- instrucciones: texto en el manifiesto, o un .md de la carpeta (por defecto INSTRUCTIONS.md)
110
+ let instr be ""
111
+ let ifile be when contains(doc, "instructions") and doc["instructions"] != nothing then text(doc["instructions"]) otherwise "INSTRUCTIONS.md"
112
+ when ends_with(lower(ifile), ".md") and not contains(ifile, "/") and not contains(ifile, "\\") and not contains(ifile, "\n")
113
+ when file_exists(dir + "/" + name + "/" + ifile)
114
+ set instr to trim(read_file(dir + "/" + name + "/" + ifile))
115
+ otherwise
116
+ set instr to trim(ifile)
117
+ when length(instr) > MAX_INSTRUCTIONS
118
+ set instr to slice(instr, 0, MAX_INSTRUCTIONS)
119
+ give {"ok": true, "name": name, "scope": scope, "legacy": is_legacy, "plugin": {"instructions": instr,"name": name, "scope": scope, "dir": dir + "/" + name, "kind": kind, "legacy": is_legacy, "description": when contains(doc, "description") then text(doc["description"]) otherwise "", "entry": when contains(doc, "entry") then text(doc["entry"]) otherwise "", "command": when contains(doc, "command") then text(doc["command"]) otherwise "", "caps": when contains(doc, "caps") then text(doc["caps"]) otherwise "", "timeout": when contains(doc, "timeout") then floor(number(doc["timeout"])) otherwise DEFAULT_TIMEOUT, "tools": tools, "channel": channel, "config": config}}
106
120
 
107
121
  task scan(dir, scope, legacy)
108
122
  let out be []
@@ -154,7 +168,7 @@ export task all()
154
168
  set l["error"] to nothing
155
169
  set out to append(out, l)
156
170
  otherwise
157
- set out to append(out, {"name": n, "scope": r["scope"], "dir": "", "kind": "?", "legacy": r["legacy"], "description": "", "entry": "", "command": "", "caps": "", "timeout": 0, "tools": [], "channel": nothing, "config": [], "enabled": false, "error": r["error"]})
171
+ set out to append(out, {"name": n, "scope": r["scope"], "dir": "", "kind": "?", "legacy": r["legacy"], "description": "", "entry": "", "command": "", "caps": "", "timeout": 0, "tools": [], "channel": nothing, "config": [], "instructions": "", "enabled": false, "error": r["error"]})
158
172
  give out
159
173
 
160
174
  export task enabled()
@@ -344,6 +358,24 @@ export task invoke(l, tool, args)
344
358
  set resolved to append(resolved, tok)
345
359
  give c.truncate(run_child(resolved[0], slice(resolved, 1, length(resolved)), c.ROOT, envs, l["timeout"]), c.MAX_OUTPUT)
346
360
 
361
+ -- las instrucciones de los plugins encendidos que tienen alguna tool en `tool_names` (el catálogo de un agente),
362
+ -- listas para sumar a su prompt. Un agente sin tools del plugin no las recibe.
363
+ export task instructions(tool_names)
364
+ require file(".lampson")
365
+ require file(".lampson/*")
366
+ require file.read("plugins")
367
+ require file.read("plugins/*")
368
+ require file("workspace")
369
+ require file("workspace/*")
370
+ require env("LAMPSON_*")
371
+ let out be ""
372
+ each l in enabled()
373
+ when l["instructions"] != ""
374
+ let mine be where(l["tools"], (t) => contains(tool_names, tool_name(l["name"], t["name"])))
375
+ when length(mine) > 0
376
+ set out to out + "\n\n# Plugin " + l["name"] + "\n" + l["instructions"]
377
+ give out
378
+
347
379
  -- los canales encendidos (plugins con "channel"), y uno por nombre
348
380
  export task channels()
349
381
  require file(".lampson")
package/lib/runtime.syn CHANGED
@@ -42,6 +42,8 @@ use "./mcp.syn" as mcp
42
42
  use "./plugins.syn" as plugins
43
43
  use "./tools/proc.syn" as proc
44
44
  use "./scope.syn" as scope
45
+ use "./teams.syn" as teams
46
+ use "./worktree.syn" as worktree
45
47
 
46
48
  export let PROJECT_DIR be "workspace/.lampson/agents"
47
49
  export let GLOBAL_DIR be "agents"
@@ -239,6 +241,14 @@ task builtin_tool_names(spec)
239
241
  require file.read(".lampson/*")
240
242
  give agents.tool_names({"tools": where(spec["tools"], (n) => not ends_with(n, "*"))})
241
243
 
244
+ -- ¿tiene send y board? los miembros de un equipo siempre; un integrado nunca (el de programación no coordina equipos)
245
+ task team_tools(spec)
246
+ require file.read("workspace")
247
+ require file.read("workspace/*")
248
+ when spec["builtin"]
249
+ give false
250
+ give contains(spec["tools"], "send") or contains(spec["tools"], "board") or length(teams.teams_of(spec["id"])) > 0
251
+
242
252
  export task registry_of(spec)
243
253
  require exec
244
254
  require time
@@ -264,6 +274,10 @@ export task registry_of(spec)
264
274
  each m in plugins.names(false)
265
275
  when allowed(spec["tools"], m)
266
276
  set reg[m] to "plugin"
277
+ -- equipos (lib/teams.syn): un miembro coordina con send y board; fuera de un equipo, solo si los lista
278
+ when team_tools(spec)
279
+ set reg["send"] to teams.send_tool
280
+ set reg["board"] to teams.board_tool
267
281
  give reg
268
282
 
269
283
  export task catalog_of(spec)
@@ -286,6 +300,8 @@ export task catalog_of(spec)
286
300
  when contains(names, "delegate")
287
301
  set cat to append(cat, agents.DELEGATE_SPEC)
288
302
  let extra be where(mcp.catalog(false) + plugins.catalog(false), (s) => allowed(spec["tools"], s["name"]))
303
+ when team_tools(spec)
304
+ set extra to extra + [teams.SEND_SPEC, teams.BOARD_SPEC]
289
305
  give cat + extra
290
306
 
291
307
  -- ---------- boot: cfg + system + opts de un agente ----------
@@ -327,6 +343,7 @@ export task opts_for(id, mode, ask_fn)
327
343
  require secret("LAMPSON_*")
328
344
  let spec be spec_or_raise(id)
329
345
  let opts be loop.default_opts(registry_of(spec), catalog_of(spec), ask_fn)
346
+ set opts["agent_id"] to spec["id"]
330
347
  -- pasos: los integrados como siempre (LAMPSON_MAX_STEPS o el del perfil); uno del proyecto, el suyo si lo fija
331
348
  set opts to loop.with_steps(opts, when spec["builtin"] or spec["steps"] == 0 then agents.steps_for(when spec["builtin"] then id otherwise "build") otherwise spec["steps"])
332
349
  when spec["budget_tokens"] > 0
@@ -364,9 +381,14 @@ export task system_for(id, cfg)
364
381
  require env("OS")
365
382
  require secret("LAMPSON_*")
366
383
  let spec be spec_or_raise(id)
384
+ -- los plugins traen su proceso: las instrucciones de los que tienen tools en el catálogo de este agente
385
+ let extra be plugins.instructions(apply(catalog_of(spec), (s) => s["name"]))
386
+ -- su equipo: rol, a quién reporta, a quién le puede escribir, cómo se usa el tablero (lib/teams.syn)
387
+ when not spec["builtin"]
388
+ set extra to extra + teams.instructions(spec["id"])
367
389
  when spec["base"] == "lampson"
368
- give {"role": "system", "content": prompt.build(agents.env_info(cfg), spec["system"])}
369
- give {"role": "system", "content": spec["system"] + "\n\n# Environment\n- Date: " + format_time(now(), "%Y-%m-%d")}
390
+ give {"role": "system", "content": prompt.build(agents.env_info(cfg), spec["system"]) + extra}
391
+ give {"role": "system", "content": spec["system"] + extra + "\n\n# Environment\n- Date: " + format_time(now(), "%Y-%m-%d")}
370
392
 
371
393
  -- over: {mode, provider, model} — lo que pide la puerta pisa lo del agente; vacío = lo del agente / lo configurado
372
394
  export task boot(id, over, ask_fn)
@@ -437,6 +459,7 @@ task remember_thread(agent, thread, sid)
437
459
  -- abre la conversación sin correr el turno: {ctx, session, thread, messages, mode}. La usan las puertas que a
438
460
  -- veces hacen otra cosa con la sesión (el `!comando` de la web); el resto llama a deliver.
439
461
  export task open(sobre, hooks)
462
+ require db(".lampson/teams.db")
440
463
  require exec
441
464
  require time
442
465
  require random
@@ -478,6 +501,31 @@ export task open(sobre, hooks)
478
501
  set messages to append(messages, {"role": "user", "content": note})
479
502
  otherwise
480
503
  set sid to fresh_session()
504
+ -- equipos y objetivos (lib/teams.syn): la conversación dice en qué trabaja; send/board/objective lo reciben como
505
+ -- _scope (lib/loop.syn). En un objetivo el agente tiene su tablero y la tool objective aunque no esté en un equipo.
506
+ when starts_with(thread, "team:") or starts_with(thread, "objective:")
507
+ let copts be ctx["opts"]
508
+ set copts["scope"] to thread
509
+ -- en un equipo con git, cada agente en su copia (lib/worktree.syn); "worktrees": false en el equipo lo apaga
510
+ when starts_with(thread, "team:")
511
+ let tm be teams.get(slice(thread, 5, length(thread)))
512
+ when tm != nothing and tm["worktrees"]
513
+ let me be teams.member(tm, ctx["agent"])
514
+ let wt be worktree.ensure(tm["id"], ctx["agent"], {"name": (when me != nothing and me["role"] != ctx["agent"] then me["role"] + " · " + ctx["agent"] otherwise ctx["agent"]) + " (Lampson)", "email": ctx["agent"] + "@lampson.local"})
515
+ when wt["ok"]
516
+ set copts["root"] to wt["root"]
517
+ when tm != nothing and teams.team_objective(tm["id"], ctx["agent"]) != nothing
518
+ let treg be copts["registry"]
519
+ set treg["objective"] to teams.objective_tool
520
+ set copts["registry"] to treg
521
+ set copts["catalog"] to where(copts["catalog"], (s) => s["name"] != "objective") + [teams.OBJECTIVE_SPEC]
522
+ when starts_with(thread, "objective:")
523
+ let reg be copts["registry"]
524
+ set reg["board"] to teams.board_tool
525
+ set reg["objective"] to teams.objective_tool
526
+ set copts["registry"] to reg
527
+ set copts["catalog"] to where(copts["catalog"], (s) => s["name"] != "board" and s["name"] != "objective") + [teams.BOARD_SPEC, teams.OBJECTIVE_SPEC]
528
+ set ctx["opts"] to copts
481
529
  -- sesión actual (blackboard): la tool todo guarda su lista por sesión (lib/tools/todo.syn)
482
530
  share {"id": sid} as "lampson:session"
483
531
  give {"ctx": ctx, "session": sid, "thread": thread, "messages": messages, "mode": ctx["opts"]["permission_mode"], "note": note}
@@ -495,6 +543,7 @@ export task save(o, messages)
495
543
  -- o: {ctx: {cfg, opts, agent}, session, thread} — lo que devuelve open(), o lo que arma la terminal.
496
544
  -- label: lo que se anota como turno del usuario en la traza ("" = el último mensaje de usuario).
497
545
  export task turn(o, messages, label, hooks)
546
+ require db(".lampson/teams.db")
498
547
  require net
499
548
  require exec
500
549
  require time
@@ -529,10 +578,19 @@ export task turn(o, messages, label, hooks)
529
578
  trace.user(sid, said, o["ctx"]["agent"], o["ctx"]["opts"]["permission_mode"], cfg["model"])
530
579
  let result be loop.run_turn(cfg, messages, o["ctx"]["opts"], on_event)
531
580
  trace.turn_end(sid, result)
581
+ -- presupuesto de equipos: lo que gastó este turno (los cacheados pesan 10%, como en el loop)
582
+ let cost be result["usage"]["input"] - result["usage"]["cached"] + floor(result["usage"]["cached"] / 10) + result["usage"]["output"]
583
+ let th be text(field(o, "thread", ""))
584
+ when starts_with(th, "team:")
585
+ teams.record_spend(o["ctx"]["agent"], cost)
586
+ teams.team_turn_end(slice(th, 5, length(th)), o["ctx"]["agent"], cost)
587
+ when starts_with(th, "objective:")
588
+ teams.obj_turn_end(floor(number(slice(th, 10, length(th)))), cost)
532
589
  save(o, result["messages"])
533
590
  give result
534
591
 
535
592
  export task deliver(sobre, hooks)
593
+ require db(".lampson/teams.db")
536
594
  require net
537
595
  require exec
538
596
  require time
@@ -0,0 +1,179 @@
1
+ -- lib/teamrun.syn — el pulso de los equipos: entrega los mensajes entre agentes y lanza las rondas
2
+ --
3
+ -- Corre en el proceso del workspace (web.syn, cron cada TICK_SECONDS). Todo entra al agente por el BUZÓN
4
+ -- (lib/mailbox.syn), como un mensaje de un cliente: una conversación por agente y equipo (thread "team:<id>"),
5
+ -- nunca dos turnos a la vez, ráfagas juntas. Cada turno arranca con lo que llegó + lo que pasó en el equipo desde su
6
+ -- último turno + sus tareas (teams.turn_text).
7
+ -- * mensajes: los que `send` dejó pendientes en la base → al buzón del destinatario
8
+ -- * rondas: un agente con trabajo (novedades de otros o tareas suyas abiertas) cada round_minutes del equipo
9
+ -- * presupuesto: un agente que pasó su tope diario no recibe turnos (sus mensajes esperan al día siguiente);
10
+ -- queda UNA entrada en el registro por día
11
+ use "./teams.syn" as teams
12
+ use "./mailbox.syn" as mailbox
13
+ use "./runtime.syn" as runtime
14
+ use "./approvals.syn" as approvals
15
+
16
+ export let TICK_SECONDS be 3
17
+ -- lo que el hub muestra de este workspace (inicio, /equipos) sin abrir su base: equipos, objetivos y lo que espera
18
+ export let SUMMARY_FILE be ".lampson/teams-summary.json"
19
+ export let ROUND_TEXT be "[round] Your periodic round: look at your open tasks and the team's news above, and move your work forward. If there is nothing for you to do, reply with one short line and stop — don't invent work."
20
+
21
+ task flag_budget(team, agent)
22
+ require db(".lampson/teams.db")
23
+ require file(".lampson")
24
+ require file(".lampson/*")
25
+ require time
26
+ let k be "teams:budget:" + team["id"] + ":" + agent + ":" + format_time(now(), "%Y-%m-%d")
27
+ when state_get(k) == nothing
28
+ state_set(k, true)
29
+ teams.log("team:" + team["id"], agent, "budget", "", "daily budget reached (" + text(team["budget_daily_tokens"]) + " tokens): no more turns today")
30
+
31
+ -- un turno para `agent` en su conversación del equipo
32
+ export task deliver_to(team, agent, sender, head)
33
+ require db(".lampson/teams.db")
34
+ require time
35
+ require random
36
+ require file(".lampson")
37
+ require file(".lampson/*")
38
+ require file.read("workspace")
39
+ require file.read("workspace/*")
40
+ require file.read("agents")
41
+ require file.read("agents/*")
42
+ let spec be runtime.get(agent)
43
+ when spec == nothing
44
+ teams.log("team:" + team["id"], "lampson", "error", "", "no agent file for '" + agent + "' — create .lampson/agents/" + agent + ".agent.json")
45
+ give false
46
+ let sobre be {"to": agent, "thread": "team:" + team["id"], "session": "", "from": sender, "text": teams.turn_text(team, agent, head), "images": [], "channel": "team", "meta": {"team": team["id"], "from": sender}}
47
+ mailbox.submit(sobre, {"mode": when spec["permission"] != "" then "" otherwise "strict", "buffer": mailbox.buffer_of(spec, false)})
48
+ give true
49
+
50
+ -- un turno del objetivo `o` en su conversación (thread objective:<id>)
51
+ export task deliver_objective(o)
52
+ require db(".lampson/teams.db")
53
+ require time
54
+ require random
55
+ require file(".lampson")
56
+ require file(".lampson/*")
57
+ require file.read("workspace")
58
+ require file.read("workspace/*")
59
+ require file.read("agents")
60
+ require file.read("agents/*")
61
+ let spec be runtime.get(o["agent"])
62
+ when spec == nothing
63
+ teams.obj_set(o["id"], {"status": "failed", "result": "no agent file for '" + o["agent"] + "'"})
64
+ give false
65
+ -- objetivo de equipo: el turno es del líder, en la conversación del equipo (con sus novedades y el tablero del equipo)
66
+ when o["team"] != ""
67
+ let tm be teams.get(o["team"])
68
+ when tm == nothing
69
+ teams.obj_set(o["id"], {"status": "failed", "result": "team '" + o["team"] + "' no longer exists"})
70
+ give false
71
+ let head be teams.obj_head(o)
72
+ teams.obj_set(o["id"], {"last_start": now(), "turns": o["turns"] + 1, "reply": ""})
73
+ give deliver_to(tm, o["agent"], "lampson", head)
74
+ let txt be teams.obj_turn_text(o)
75
+ teams.obj_set(o["id"], {"last_start": now(), "turns": o["turns"] + 1, "reply": ""})
76
+ let sobre be {"to": o["agent"], "thread": "objective:" + text(o["id"]), "session": "", "from": "lampson", "text": txt, "images": [], "channel": "objective", "meta": {"objective": o["id"]}}
77
+ mailbox.submit(sobre, {"mode": when spec["permission"] != "" then "" otherwise "strict", "buffer": mailbox.buffer_of(spec, false)})
78
+ give true
79
+
80
+ -- ¿le toca un turno? activo, el anterior terminó y pasaron round_seconds (el primero, enseguida; una respuesta de la
81
+ -- persona, enseguida también)
82
+ export task objective_due(o)
83
+ require db(".lampson/teams.db")
84
+ require file(".lampson")
85
+ require file(".lampson/*")
86
+ require time
87
+ when o["status"] != "active"
88
+ give false
89
+ when o["turns"] == 0
90
+ give true
91
+ -- el turno anterior sigue (o murió sin cerrar: a los 15 min se da por perdido y se sigue)
92
+ when o["last_end"] < o["last_start"] and now() - o["last_start"] < 900
93
+ give false
94
+ when o["reply"] != ""
95
+ give true
96
+ when now() - o["last_end"] < o["round_seconds"]
97
+ give false
98
+ -- en un equipo, el líder solo hace ronda si algo cambió o tiene tareas propias (si no, está esperando a los demás)
99
+ when o["team"] != ""
100
+ give teams.has_work("team:" + o["team"], o["agent"])
101
+ give true
102
+
103
+ -- escribe el resumen si cambió: equipos, objetivos abiertos (y los últimos cerrados) y aprobaciones pendientes
104
+ export task write_summary()
105
+ require db(".lampson/teams.db")
106
+ require time
107
+ require net
108
+ require env("LAMPSON_*")
109
+ require file(".lampson")
110
+ require file(".lampson/*")
111
+ require file.read("workspace")
112
+ require file.read("workspace/*")
113
+ let ts be apply(teams.all(), (t) => {"id": t["id"], "description": t["description"], "members": length(t["members"]), "lead": teams.lead_of(t)})
114
+ let objs be teams.obj_list()
115
+ let open_o be where(objs, (o) => contains(["active", "waiting", "paused"], o["status"]))
116
+ let closed be slice(where(objs, (o) => not contains(["active", "waiting", "paused"], o["status"])), 0, 5)
117
+ let brief be apply(open_o + closed, (o) => {"id": o["id"], "ref": "O-" + text(o["id"]), "agent": o["agent"], "team": o["team"], "text": slice(o["text"], 0, 240), "status": o["status"], "question": o["question"], "question_kind": o["question_kind"], "progress": slice(o["progress"], 0, 240), "spent": o["spent"], "updated_at": o["updated_at"]})
118
+ let aps be []
119
+ try
120
+ set aps to apply(approvals.pending(), (a) => {"id": a["id"], "message": a["message"], "why": a["why"], "created": a["created"]})
121
+ recover err
122
+ set aps to []
123
+ let body be {"teams": ts, "objectives": brief, "approvals": aps, "active": length(where(open_o, (o) => o["status"] == "active")), "waiting": length(where(open_o, (o) => o["status"] == "waiting")) + length(aps)}
124
+ let enc be json_encode(body)
125
+ when state_get("teams:summary:last", "") != enc
126
+ state_set("teams:summary:last", enc)
127
+ set body["updated"] to now()
128
+ write_file(SUMMARY_FILE, json_encode(body))
129
+ give body
130
+
131
+ export task tick()
132
+ require net
133
+ require env("LAMPSON_*")
134
+ require db(".lampson/teams.db")
135
+ require time
136
+ require random
137
+ require file(".lampson")
138
+ require file(".lampson/*")
139
+ require file.read("workspace")
140
+ require file.read("workspace/*")
141
+ require file.read("agents")
142
+ require file.read("agents/*")
143
+ let n be 0
144
+ try
145
+ write_summary()
146
+ recover err
147
+ set n to 0
148
+ each o in teams.obj_list()
149
+ when objective_due(o)
150
+ when deliver_objective(o)
151
+ set n to n + 1
152
+ let teams_now be teams.all()
153
+ when length(teams_now) == 0
154
+ give n
155
+ each m in teams.pending()
156
+ let tid be slice(m["scope"], 5, length(m["scope"]))
157
+ let found be where(teams_now, (t) => t["id"] == tid)
158
+ when length(found) == 0
159
+ teams.mark(m["id"], "dropped")
160
+ otherwise
161
+ let team be found[0]
162
+ when teams.over_budget(team, m["recipient"])
163
+ flag_budget(team, m["recipient"])
164
+ otherwise
165
+ let who be teams.member(team, m["sender"])
166
+ let head be "[message from " + m["sender"] + (when who != nothing then " (" + who["role"] + ")" otherwise "") + "]\n" + m["text"]
167
+ when deliver_to(team, m["recipient"], m["sender"], head)
168
+ teams.mark(m["id"], "delivered")
169
+ set n to n + 1
170
+ otherwise
171
+ teams.mark(m["id"], "failed")
172
+ each team in teams_now
173
+ each mem in team["members"]
174
+ when teams.over_budget(team, mem["agent"])
175
+ flag_budget(team, mem["agent"])
176
+ otherwise when teams.round_due(team, mem["agent"])
177
+ deliver_to(team, mem["agent"], "lampson", ROUND_TEXT)
178
+ set n to n + 1
179
+ give n