lampson 0.3.0 → 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/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,142 @@
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
+
15
+ export let TICK_SECONDS be 3
16
+ 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."
17
+
18
+ task flag_budget(team, agent)
19
+ require db(".lampson/teams.db")
20
+ require file(".lampson")
21
+ require file(".lampson/*")
22
+ require time
23
+ let k be "teams:budget:" + team["id"] + ":" + agent + ":" + format_time(now(), "%Y-%m-%d")
24
+ when state_get(k) == nothing
25
+ state_set(k, true)
26
+ teams.log("team:" + team["id"], agent, "budget", "", "daily budget reached (" + text(team["budget_daily_tokens"]) + " tokens): no more turns today")
27
+
28
+ -- un turno para `agent` en su conversación del equipo
29
+ export task deliver_to(team, agent, sender, head)
30
+ require db(".lampson/teams.db")
31
+ require time
32
+ require random
33
+ require file(".lampson")
34
+ require file(".lampson/*")
35
+ require file.read("workspace")
36
+ require file.read("workspace/*")
37
+ require file.read("agents")
38
+ require file.read("agents/*")
39
+ let spec be runtime.get(agent)
40
+ when spec == nothing
41
+ teams.log("team:" + team["id"], "lampson", "error", "", "no agent file for '" + agent + "' — create .lampson/agents/" + agent + ".agent.json")
42
+ give false
43
+ 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}}
44
+ mailbox.submit(sobre, {"mode": when spec["permission"] != "" then "" otherwise "strict", "buffer": mailbox.buffer_of(spec, false)})
45
+ give true
46
+
47
+ -- un turno del objetivo `o` en su conversación (thread objective:<id>)
48
+ export task deliver_objective(o)
49
+ require db(".lampson/teams.db")
50
+ require time
51
+ require random
52
+ require file(".lampson")
53
+ require file(".lampson/*")
54
+ require file.read("workspace")
55
+ require file.read("workspace/*")
56
+ require file.read("agents")
57
+ require file.read("agents/*")
58
+ let spec be runtime.get(o["agent"])
59
+ when spec == nothing
60
+ teams.obj_set(o["id"], {"status": "failed", "result": "no agent file for '" + o["agent"] + "'"})
61
+ give false
62
+ -- objetivo de equipo: el turno es del líder, en la conversación del equipo (con sus novedades y el tablero del equipo)
63
+ when o["team"] != ""
64
+ let tm be teams.get(o["team"])
65
+ when tm == nothing
66
+ teams.obj_set(o["id"], {"status": "failed", "result": "team '" + o["team"] + "' no longer exists"})
67
+ give false
68
+ let head be teams.obj_head(o)
69
+ teams.obj_set(o["id"], {"last_start": now(), "turns": o["turns"] + 1, "reply": ""})
70
+ give deliver_to(tm, o["agent"], "lampson", head)
71
+ let txt be teams.obj_turn_text(o)
72
+ teams.obj_set(o["id"], {"last_start": now(), "turns": o["turns"] + 1, "reply": ""})
73
+ let sobre be {"to": o["agent"], "thread": "objective:" + text(o["id"]), "session": "", "from": "lampson", "text": txt, "images": [], "channel": "objective", "meta": {"objective": o["id"]}}
74
+ mailbox.submit(sobre, {"mode": when spec["permission"] != "" then "" otherwise "strict", "buffer": mailbox.buffer_of(spec, false)})
75
+ give true
76
+
77
+ -- ¿le toca un turno? activo, el anterior terminó y pasaron round_seconds (el primero, enseguida; una respuesta de la
78
+ -- persona, enseguida también)
79
+ export task objective_due(o)
80
+ require db(".lampson/teams.db")
81
+ require file(".lampson")
82
+ require file(".lampson/*")
83
+ require time
84
+ when o["status"] != "active"
85
+ give false
86
+ when o["turns"] == 0
87
+ give true
88
+ -- el turno anterior sigue (o murió sin cerrar: a los 15 min se da por perdido y se sigue)
89
+ when o["last_end"] < o["last_start"] and now() - o["last_start"] < 900
90
+ give false
91
+ when o["reply"] != ""
92
+ give true
93
+ when now() - o["last_end"] < o["round_seconds"]
94
+ give false
95
+ -- en un equipo, el líder solo hace ronda si algo cambió o tiene tareas propias (si no, está esperando a los demás)
96
+ when o["team"] != ""
97
+ give teams.has_work("team:" + o["team"], o["agent"])
98
+ give true
99
+
100
+ export task tick()
101
+ require db(".lampson/teams.db")
102
+ require time
103
+ require random
104
+ require file(".lampson")
105
+ require file(".lampson/*")
106
+ require file.read("workspace")
107
+ require file.read("workspace/*")
108
+ require file.read("agents")
109
+ require file.read("agents/*")
110
+ let n be 0
111
+ each o in teams.obj_list()
112
+ when objective_due(o)
113
+ when deliver_objective(o)
114
+ set n to n + 1
115
+ let teams_now be teams.all()
116
+ when length(teams_now) == 0
117
+ give n
118
+ each m in teams.pending()
119
+ let tid be slice(m["scope"], 5, length(m["scope"]))
120
+ let found be where(teams_now, (t) => t["id"] == tid)
121
+ when length(found) == 0
122
+ teams.mark(m["id"], "dropped")
123
+ otherwise
124
+ let team be found[0]
125
+ when teams.over_budget(team, m["recipient"])
126
+ flag_budget(team, m["recipient"])
127
+ otherwise
128
+ let who be teams.member(team, m["sender"])
129
+ let head be "[message from " + m["sender"] + (when who != nothing then " (" + who["role"] + ")" otherwise "") + "]\n" + m["text"]
130
+ when deliver_to(team, m["recipient"], m["sender"], head)
131
+ teams.mark(m["id"], "delivered")
132
+ set n to n + 1
133
+ otherwise
134
+ teams.mark(m["id"], "failed")
135
+ each team in teams_now
136
+ each mem in team["members"]
137
+ when teams.over_budget(team, mem["agent"])
138
+ flag_budget(team, mem["agent"])
139
+ otherwise when teams.round_due(team, mem["agent"])
140
+ deliver_to(team, mem["agent"], "lampson", ROUND_TEXT)
141
+ set n to n + 1
142
+ give n