lampson 0.4.1 → 0.5.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.
Files changed (69) hide show
  1. package/README.md +19 -0
  2. package/chat.syn +1 -1
  3. package/hub.tpl.syn +55 -12
  4. package/lampson.ps1 +13 -6
  5. package/lampson.sh +11 -5
  6. package/lib/api.syn +224 -9
  7. package/lib/apikeys.syn +42 -9
  8. package/lib/apptools.syn +549 -0
  9. package/lib/diagnose.syn +142 -0
  10. package/lib/loop.syn +27 -0
  11. package/lib/mailbox.syn +24 -10
  12. package/lib/mcp_server.syn +6 -5
  13. package/lib/permission.syn +22 -1
  14. package/lib/plugins.syn +6 -4
  15. package/lib/provider.syn +16 -13
  16. package/lib/remotetools.syn +76 -0
  17. package/lib/runtime.syn +213 -9
  18. package/lib/schedule.syn +40 -2
  19. package/lib/sdktools.syn +73 -0
  20. package/lib/session.syn +8 -0
  21. package/lib/teamrun.syn +42 -5
  22. package/lib/teams.syn +397 -24
  23. package/lib/tools/common.syn +5 -0
  24. package/lib/tools/url.syn +82 -9
  25. package/lib/workspaces.syn +87 -3
  26. package/lib/worktree.syn +108 -0
  27. package/package.json +2 -2
  28. package/plugins/example-hello/plugin.json +1 -0
  29. package/public/css/chat.css +9 -8
  30. package/public/css/hub.css +69 -16
  31. package/public/css/layout.css +12 -4
  32. package/public/css/login.css +1 -1
  33. package/public/css/mobile.css +2 -2
  34. package/public/css/panel.css +18 -7
  35. package/public/css/sidebar.css +1 -1
  36. package/public/css/teams.css +701 -55
  37. package/public/css/tokens.css +36 -12
  38. package/public/css/views.css +124 -0
  39. package/public/hub.html +17 -9
  40. package/public/index.html +5 -2
  41. package/public/js/app.js +2 -2
  42. package/public/js/approvals.js +1 -1
  43. package/public/js/apptools.js +63 -0
  44. package/public/js/core.js +5 -2
  45. package/public/js/flow.js +187 -0
  46. package/public/js/hub.js +131 -31
  47. package/public/js/navtabs.js +23 -0
  48. package/public/js/objdiag.js +90 -0
  49. package/public/js/objlive.js +393 -0
  50. package/public/js/panel.js +3 -2
  51. package/public/js/plugins-home.js +59 -0
  52. package/public/js/plugins.js +40 -18
  53. package/public/js/schedules.js +5 -0
  54. package/public/js/sidebar.js +6 -4
  55. package/public/js/tasks-home.js +104 -0
  56. package/public/js/teams-home.js +64 -15
  57. package/public/js/teams.js +927 -202
  58. package/public/js/terminal.js +8 -2
  59. package/public/js/workspaces.js +6 -3
  60. package/public/plugins-home.html +32 -0
  61. package/public/tasks-home.html +31 -0
  62. package/public/teams-home.html +5 -2
  63. package/public/teams.html +33 -46
  64. package/public/vendor/xterm-addon-webgl.js +2 -0
  65. package/run.syn +87 -6
  66. package/sdk/index.d.ts +64 -3
  67. package/sdk/index.js +253 -11
  68. package/skills/lampson/SKILL.md +15 -0
  69. package/web.syn +91 -12
package/README.md CHANGED
@@ -116,8 +116,23 @@ lampson run --agent shop "hi" # one message from a script; --
116
116
  import { Lampson } from "lampson"; // also: pip install lampson
117
117
  const lampson = new Lampson({ local: { workspace: "./my-project" } }); // or { url, key } for a running Lampson
118
118
  const r = await lampson.ask({ agent: "shop", thread: "customer-42", text: "do you have whole-wheat bread?" });
119
+
120
+ // an agent for your customers: only the tools you give it — no bash, read, write or fetch of Lampson's own
121
+ const shop = new Lampson({ agent: "shop", local: { workspace: "./my-project", lampsonTools: false } });
122
+ shop.tool("stock", { description: "Units in stock", inputSchema: z.object({ product: z.string() }),
123
+ execute: async ({ product }, ctx) => db.stock(product, ctx.from.id) }); // your function; ctx comes from your app
124
+
125
+ // Lampson on another machine: the same tools; it POSTs each call to your endpoint, signed with the key's secret
126
+ const remote = new Lampson({ url, key, toolsUrl: "https://my-app.com/api/lampson/tools", toolsSecret });
127
+ export const POST = remote.toolsHandler(); // Next/Hono/Bun; Express: app.post(path, remote.toolsHandler())
119
128
  ```
120
129
 
130
+ Or write the tool in Synsema — `.lampson/tools/stock.syn`, one file per tool — and its `require`s are everything it can
131
+ touch: a message that tricks the model into sending data elsewhere gets `Capability not granted`. It reads only
132
+ the variables it names with `env("NAME")` (never Lampson's own, never the folder's `.env`), and it runs only once
133
+ you approved that exact content (`lampson tools approve`, or *herramientas* in the web UI): if an agent rewrites
134
+ it, it stops until you look.
135
+
121
136
  - **An agent is a file**: `.lampson/agents/shop.agent.json` (or `~/lampson/agents/` for every project) — its prompt,
122
137
  the exact tools it may use (optionally limited to some paths, with per-tool approval) and its model.
123
138
  - **One conversation per customer** (`thread`), and a mailbox per conversation: a burst of messages gets one
@@ -147,6 +162,10 @@ view at `/w/<project>/equipos` with the objectives, the team as a live graph, it
147
162
  editor to build the team.
148
163
  → **[lampson.org/docs/teams](https://lampson.org/docs/teams)**
149
164
 
165
+ The home page has a tab per product: **proyectos · equipos · tareas · plugins**. `/tareas` lists the scheduled tasks
166
+ of every project (switch them on or off, run one now) and `/plugins` shows what's installed and where it's on —
167
+ turning a plugin on is still decided project by project, inside the project.
168
+
150
169
  ## Also in the box
151
170
 
152
171
  Sub-agents that work in parallel · skills (`SKILL.md` procedures, anything on [skills.sh](https://skills.sh)
package/chat.syn CHANGED
@@ -854,7 +854,7 @@ task attach_image(mode, path)
854
854
  let vis be provider.supports_vision(cfg)
855
855
  print(" " + green("📎 imagen " + text(length(pending_images)) + " adjunta") + dim(" · " + text(im["w"]) + "x" + text(im["h"]) + " · " + text(floor(length(im["data"]) * 3 / 4 / 1024)) + " KB · se manda con tu próximo mensaje"))
856
856
  when not vis
857
- print(" " + yellow("ojo: " + cfg["provider"] + " · " + cfg["model"] + " no acepta imágenes; el modelo recibirá solo una nota. Cambiá con /provider a uno con visión (anthropic, gpt-4o…)"))
857
+ print(" " + yellow("ojo: " + cfg["provider"] + " · " + cfg["model"] + " no acepta imágenes; el modelo recibirá solo una nota. Cambiá con /provider a uno con visión (anthropic, gpt-6.1-sol, deepseek-flash…)"))
858
858
  give true
859
859
 
860
860
  -- ---------- boot ----------
package/hub.tpl.syn CHANGED
@@ -6,6 +6,8 @@
6
6
  -- GET /w/<slug> la UI de ese workspace (public/index.html; los assets /css /js los sirve el hub)
7
7
  -- * /w/<slug>/api/… proxy al proceso del workspace (127.0.0.1:808N) — SSE y WebSocket pasan (Synsema ≥ 0.6.12)
8
8
  -- GET /w/<slug>/approve/… links de aprobación de ese workspace
9
+ -- GET /equipos · /tareas · /plugins vistas de todos los proyectos (pestañas del inicio)
10
+ -- GET /w/<slug>/equipos[/…] · /w/<slug>/objetivos/<n> equipos, objetivos y rutinas de un proyecto
9
11
  -- /api/workspaces… registro, crear (diálogo nativo o explorador), start/stop/quitar, política
10
12
  -- Supervisor: cada 15 s arranca los workspaces que deben vivir y apaga los inactivos (política en ⚙ → idle_hours).
11
13
  -- Acceso: esta PC entra sin nada; lo remoto — túnel, LAN, VPS — necesita la sesión de un dispositivo emparejado con
@@ -35,6 +37,9 @@ require file.read("public/*")
35
37
  -- equipos que no programan: su carpeta vive en la instalación (equipos/<nombre>/), creada desde /equipos
36
38
  require file("equipos")
37
39
  require file("equipos/*")
40
+ -- /plugins: el catálogo de plugins de la instalación (solo lectura: encender es dentro de cada proyecto)
41
+ require file.read("plugins")
42
+ require file.read("plugins/*")
38
43
  require random
39
44
 
40
45
  use "./lib/workspaces.syn" as ws
@@ -62,6 +67,21 @@ task check_client(token, request)
62
67
  task page_allowed(request)
63
68
  give check_client(nothing, request) != nothing
64
69
 
70
+ -- la pantalla de equipos (public/teams.html) en cualquiera de sus rutas: /w/<nombre> sin el hash va al slug completo, y
71
+ -- entrar enciende el workspace si estaba apagado
72
+ task teams_page(request, slug, rest, query)
73
+ when not page_allowed(request)
74
+ give redirect("/login", 302)
75
+ let full be ws.resolve_slug(slug)
76
+ when full != nothing and full != slug
77
+ give redirect("/w/" + full + rest + (when contains(query, "new") then "?new=1" otherwise ""), 302)
78
+ let w be ws.get(slug)
79
+ when w != nothing and ws.health(w) == nothing
80
+ ws.start_ws(w)
81
+ ws.wait_ready(w, 8)
82
+ ws.summary()
83
+ give html(read_file("public/teams.html"))
84
+
65
85
  task with_session(resp, request, sid)
66
86
  give set_cookie(resp, auth.COOKIE, sid, {"max_age": auth.SESSION_MAX_DAYS * 86400, "secure": auth.secure_cookie(headers of request), "same_site": "Lax"})
67
87
 
@@ -185,19 +205,15 @@ serve on 8080
185
205
  ws.summary()
186
206
  give html(read_file("public/index.html"))
187
207
 
188
- -- la pantalla de equipos y objetivos de un workspace (public/teams.html): página propia, a pantalla completa
208
+ -- la pantalla de equipos y objetivos de un workspace (public/teams.html): página propia, a pantalla completa. Las
209
+ -- subrutas (…/equipos/<equipo>, /editar, /objetivos/<n>, /rutinas/<id>, /w/<slug>/objetivos/<n>) son la misma
210
+ -- página: js/teams.js lee la URL y muestra ese nivel (así «atrás» y los enlaces van a donde dicen)
189
211
  route "GET /w/:slug/equipos"
190
- when not page_allowed(request)
191
- give redirect("/login", 302)
192
- let full be ws.resolve_slug(params.slug)
193
- when full != nothing and full != params.slug
194
- give redirect("/w/" + full + "/equipos" + (when contains(query, "new") then "?new=1" otherwise ""), 302)
195
- let w be ws.get(params.slug)
196
- when w != nothing and ws.health(w) == nothing
197
- ws.start_ws(w)
198
- ws.wait_ready(w, 8)
199
- ws.summary()
200
- give html(read_file("public/teams.html"))
212
+ give teams_page(request, params.slug, "/equipos", query)
213
+ route "GET /w/:slug/equipos/*rest"
214
+ give teams_page(request, params.slug, "/equipos/" + params.rest, query)
215
+ route "GET /w/:slug/objetivos/*rest"
216
+ give teams_page(request, params.slug, "/objetivos/" + params.rest, query)
201
217
 
202
218
  -- EQUIPOS Y OBJETIVOS de todos los workspaces (public/teams-home.html): lo que espera a la persona, cada proyecto
203
219
  -- con sus equipos y objetivos, y «+ equipo». Lee el resumen que escribe cada workspace (lib/teamrun.syn).
@@ -238,6 +254,33 @@ serve on 8080
238
254
  ws.summary()
239
255
  give {"ok": true, "slug": w["slug"], "url": "/w/" + w["slug"] + "/equipos?new=1"}
240
256
 
257
+ -- TAREAS PROGRAMADAS de todos los workspaces (public/tasks-home.html): leídas del json de cada uno, así se ven
258
+ -- también las de un proyecto apagado. Correr y encender/apagar van al workspace por el proxy (/w/<slug>/api/…).
259
+ route "GET /tareas"
260
+ when not page_allowed(request)
261
+ give redirect("/login", 302)
262
+ give html(read_file("public/tasks-home.html"))
263
+
264
+ route "GET /api/tasks-home" requires auth
265
+ let out be []
266
+ each w in ws.summary_cached(20)
267
+ set out to append(out, {"slug": w["slug"], "name": w["name"], "path": w["path"], "alive": w["alive"], "tasks": ws.tasks_summary(w)})
268
+ give {"workspaces": out}
269
+
270
+ -- PLUGINS (public/plugins-home.html): qué hay instalado y en qué proyectos está encendido cada uno. Es un
271
+ -- escaparate: encender sigue siendo una decisión por proyecto, dentro del proyecto (/w/<slug>#plugins=<nombre>).
272
+ route "GET /plugins"
273
+ when not page_allowed(request)
274
+ give redirect("/login", 302)
275
+ give html(read_file("public/plugins-home.html"))
276
+
277
+ route "GET /api/plugins-home" requires auth
278
+ let out be []
279
+ each w in ws.summary_cached(20)
280
+ let p be ws.plugins_of(w)
281
+ set out to append(out, {"slug": w["slug"], "name": w["name"], "path": w["path"], "alive": w["alive"], "enabled": p["enabled"], "local": p["local"]})
282
+ give {"global": ws.plugins_global(), "workspaces": out}
283
+
241
284
  route "GET /api/hub" requires auth
242
285
  give {"ok": true, "port": ws.HUB_PORT, "idle_hours": ws.idle_hours(), "home": ws.home(), "local": request.user["local"]}
243
286
 
package/lampson.ps1 CHANGED
@@ -13,6 +13,8 @@
13
13
  # lampson key add [--agent ID[,ID]] [--name NOMBRE] [--rate N] [--callback URL] · key list · key remove <id> # API keys /v1
14
14
  # lampson mcp serve [--agent ID[,ID]] [--workspace RUTA] # Lampson como servidor MCP (stdio) para otros agentes
15
15
  # lampson channel list · channel on|off <canal> · channel setup <canal> # canales (Telegram, Chatwoot…)
16
+ # lampson plugin list · plugin on|off <nombre> # encender plugins sin interfaz (VPS por SSH, scripts)
17
+ # lampson tools list · tools approve [nombre] # herramientas .syn del proyecto: corren solo aprobadas
16
18
  # lampson objective add "…" --agent ID | --team ID [--budget N] [--round S] · objective list · show <id> · reply <id> "…" [--approve|--deny] · cancel <id> # objetivos
17
19
  # lampson team list # equipos de agentes y quién reporta a quién
18
20
  #
@@ -25,7 +27,7 @@ $caller = (Get-Location).Path
25
27
 
26
28
  # --- args: acepta --flag y -Flag, sin distinguir mayúsculas ---
27
29
  $Workspace = ""; $Web = $false; $Agent = ""; $Perm = ""; $Hub = ""; $Install = ""; $Domain = $null; $Email = ""; $Pair = $null
28
- $Run = $false; $Message = @(); $Thread = ""; $Session = ""; $Json = $false; $Key = ""; $KeyName = ""; $KeyId = ""; $McpServe = $false; $ChannelCmd = ""; $ChannelName = ""; $Stdio = $false; $KeyRate = ""; $KeyCallbacks = @(); $ObjCmd = ""; $ObjId = ""; $ObjTeam = ""; $ObjBudget = ""; $ObjRound = ""; $ObjDecision = ""; $TeamCmd = ""
30
+ $Run = $false; $Message = @(); $Thread = ""; $Session = ""; $Json = $false; $Key = ""; $KeyName = ""; $KeyId = ""; $McpServe = $false; $ChannelCmd = ""; $ChannelName = ""; $Stdio = $false; $KeyRate = ""; $KeyCallbacks = @(); $PluginCmd = ""; $PluginName = ""; $ToolsCmd = ""; $ObjCmd = ""; $ObjId = ""; $ObjTeam = ""; $ObjBudget = ""; $ObjRound = ""; $ObjDecision = ""; $TeamCmd = ""
29
31
  $i = 0
30
32
  # `lampson run …`: subcomando sin interfaz (run.syn, spec/engine.md); las palabras sueltas son el mensaje
31
33
  if ($args.Count -gt 0 -and ([string]$args[0]).ToLower() -eq "run") { $Run = $true; $i = 1 }
@@ -33,6 +35,10 @@ if ($args.Count -gt 0 -and ([string]$args[0]).ToLower() -eq "run") { $Run = $tru
33
35
  # `lampson mcp serve …`: servidor MCP por stdio (run.syn con LAMPSON_MCP_SERVE)
34
36
  if ($args.Count -gt 1 -and ([string]$args[0]).ToLower() -eq "mcp" -and ([string]$args[1]).ToLower() -eq "serve") { $Run = $true; $McpServe = $true; $i = 2 }
35
37
  # `lampson channel list|on|off|setup <canal>` (run.syn con LAMPSON_CHANNEL_CMD)
38
+ # `lampson plugin list|on|off <nombre>` (run.syn con LAMPSON_PLUGIN_CMD)
39
+ # `lampson tools list|approve [nombre]` (run.syn con LAMPSON_TOOLS_CMD): aprobar las herramientas .syn del proyecto
40
+ if ($args.Count -gt 0 -and ([string]$args[0]).ToLower() -eq "tools") { $Run = $true; $ToolsCmd = $(if ($args.Count -gt 1) { ([string]$args[1]).ToLower() } else { "list" }); $i = 2 }
41
+ if ($args.Count -gt 0 -and ([string]$args[0]).ToLower() -eq "plugin") { $Run = $true; $PluginCmd = $(if ($args.Count -gt 1) { ([string]$args[1]).ToLower() } else { "list" }); $i = 2 }
36
42
  if ($args.Count -gt 0 -and ([string]$args[0]).ToLower() -eq "channel") { $Run = $true; $ChannelCmd = $(if ($args.Count -gt 1) { ([string]$args[1]).ToLower() } else { "list" }); $i = 2 }
37
43
  # `lampson objective add|list|show|reply|cancel` y `lampson team list` (run.syn con LAMPSON_OBJ_CMD / LAMPSON_TEAM_CMD)
38
44
  if ($args.Count -gt 0 -and ([string]$args[0]).ToLower() -eq "objective") { $Run = $true; $ObjCmd = $(if ($args.Count -gt 1) { ([string]$args[1]).ToLower() } else { "list" }); $i = 2 }
@@ -68,14 +74,15 @@ while ($i -lt $args.Count) {
68
74
  '^--?deny$' { $ObjDecision = "deny" }
69
75
  '^--?(update|u)$' { Write-Host "actualizando Lampson en $here"; git -C $here pull --ff-only origin main; Write-Host ("lampson " + (git -C $here rev-parse --short HEAD)); exit $LASTEXITCODE }
70
76
  '^--?(help|h|\?)$' { Get-Content $PSCommandPath | Select-Object -Skip 1 -First 9 | ForEach-Object { $_.TrimStart('#',' ') }; exit 0 }
71
- default { if ($ObjCmd -ne "" -and $ObjId -eq "" -and @("show", "reply", "cancel") -contains $ObjCmd -and -not $a.StartsWith("-")) { $ObjId = $a } elseif ($ObjCmd -ne "" -and -not $a.StartsWith("-")) { $Message += $a } elseif ($ChannelCmd -ne "" -and -not $a.StartsWith("-")) { $ChannelName = $a } elseif ($Key -ne "" -and -not $a.StartsWith("-")) { $KeyId = $a } elseif ($Run -and -not $a.StartsWith("-")) { $Message += $a } elseif ($Workspace -eq "" -and -not $a.StartsWith("-")) { $Workspace = $a } else { Write-Error "argumento desconocido: $a (probá lampson --help)"; exit 1 } }
77
+ default { if ($ObjCmd -ne "" -and $ObjId -eq "" -and @("show", "reply", "cancel") -contains $ObjCmd -and -not $a.StartsWith("-")) { $ObjId = $a } elseif ($ObjCmd -ne "" -and -not $a.StartsWith("-")) { $Message += $a } elseif ($ChannelCmd -ne "" -and -not $a.StartsWith("-")) { $ChannelName = $a } elseif (($PluginCmd -ne "" -or $ToolsCmd -ne "") -and -not $a.StartsWith("-")) { $PluginName = $a } elseif ($Key -ne "" -and -not $a.StartsWith("-")) { $KeyId = $a } elseif ($Run -and -not $a.StartsWith("-")) { $Message += $a } elseif ($Workspace -eq "" -and -not $a.StartsWith("-")) { $Workspace = $a } else { Write-Error "argumento desconocido: $a (probá lampson --help)"; exit 1 } }
72
78
  }
73
79
  $i++
74
80
  }
75
81
 
76
- # motor mínimo: el hub y los workspaces declaran `trust proxy` (Synsema 0.6.42+; ver lib/origin.syn). Con uno viejo el
82
+ # motor mínimo: `trust proxy` en el hub y los workspaces (0.6.42+), y las herramientas de la app usan --cap-set,
83
+ # --no-env-file y http_sign (probados en 0.6.44). Con uno viejo el
77
84
  # hub ni arranca: mejor decirlo acá que dejar un 502
78
- $MinEngine = [version]"0.6.42"
85
+ $MinEngine = [version]"0.6.44"
79
86
  $engine = ((& synsema --version 2>$null) -replace '^\D*', '').Trim()
80
87
  if (-not ($engine -as [version]) -or [version]$engine -lt $MinEngine) { Write-Error "lampson necesita synsema $MinEngine o más nuevo (tenés '$engine'): synsema update"; exit 1 }
81
88
 
@@ -219,7 +226,7 @@ try {
219
226
  $env:LAMPSON_KEY_CMD = $Key; $env:LAMPSON_KEY_NAME = $KeyName; $env:LAMPSON_KEY_ID = $KeyId; $env:LAMPSON_KEY_AGENTS = $Agent
220
227
  $env:LAMPSON_KEY_RATE = $KeyRate; $env:LAMPSON_KEY_CALLBACKS = ($KeyCallbacks -join ",")
221
228
  $env:LAMPSON_MCP_SERVE = $(if ($McpServe) { "1" } else { "" }); $env:LAMPSON_MCP_AGENTS = $(if ($McpServe) { $Agent } else { "" })
222
- $env:LAMPSON_CHANNEL_CMD = $ChannelCmd; $env:LAMPSON_CHANNEL_NAME = $ChannelName
229
+ $env:LAMPSON_CHANNEL_CMD = $ChannelCmd; $env:LAMPSON_CHANNEL_NAME = $ChannelName; $env:LAMPSON_PLUGIN_CMD = $PluginCmd; $env:LAMPSON_PLUGIN_NAME = $PluginName; $env:LAMPSON_TOOLS_CMD = $ToolsCmd; $env:LAMPSON_TOOLS_NAME = $PluginName
223
230
  $env:LAMPSON_RUN_STDIO = $(if ($Stdio) { "1" } else { "" })
224
231
  $env:LAMPSON_OBJ_CMD = $ObjCmd; $env:LAMPSON_OBJ_ID = $ObjId; $env:LAMPSON_OBJ_AGENT = $(if ($ObjCmd -ne "") { $Agent } else { "" }); $env:LAMPSON_OBJ_TEAM = $ObjTeam
225
232
  $env:LAMPSON_OBJ_BUDGET = $ObjBudget; $env:LAMPSON_OBJ_ROUND = $ObjRound; $env:LAMPSON_OBJ_DECISION = $ObjDecision; $env:LAMPSON_TEAM_CMD = $TeamCmd
@@ -230,7 +237,7 @@ try {
230
237
  Pop-Location
231
238
  # `lampson` corre este script dentro de TU sesión de PowerShell: lo de `run`/`key` no debe quedar en el entorno
232
239
  # (un LAMPSON_SESSION que queda haría que el próximo `lampson` retome esa sesión sin pedirlo)
233
- if ($Run) { foreach ($v in "LAMPSON_MESSAGE","LAMPSON_RUN_PERMISSION","LAMPSON_THREAD","LAMPSON_SESSION","LAMPSON_RUN_JSON","LAMPSON_KEY_CMD","LAMPSON_KEY_NAME","LAMPSON_KEY_ID","LAMPSON_KEY_AGENTS","LAMPSON_MCP_SERVE","LAMPSON_MCP_AGENTS","LAMPSON_CHANNEL_CMD","LAMPSON_CHANNEL_NAME","LAMPSON_RUN_STDIO","LAMPSON_KEY_RATE","LAMPSON_KEY_CALLBACKS","LAMPSON_OBJ_CMD","LAMPSON_OBJ_ID","LAMPSON_OBJ_AGENT","LAMPSON_OBJ_TEAM","LAMPSON_OBJ_BUDGET","LAMPSON_OBJ_ROUND","LAMPSON_OBJ_DECISION","LAMPSON_TEAM_CMD") { Remove-Item "Env:$v" -ErrorAction SilentlyContinue } }
240
+ if ($Run) { foreach ($v in "LAMPSON_MESSAGE","LAMPSON_RUN_PERMISSION","LAMPSON_THREAD","LAMPSON_SESSION","LAMPSON_RUN_JSON","LAMPSON_KEY_CMD","LAMPSON_KEY_NAME","LAMPSON_KEY_ID","LAMPSON_KEY_AGENTS","LAMPSON_MCP_SERVE","LAMPSON_MCP_AGENTS","LAMPSON_CHANNEL_CMD","LAMPSON_CHANNEL_NAME","LAMPSON_PLUGIN_CMD","LAMPSON_PLUGIN_NAME","LAMPSON_TOOLS_CMD","LAMPSON_TOOLS_NAME","LAMPSON_RUN_STDIO","LAMPSON_KEY_RATE","LAMPSON_KEY_CALLBACKS","LAMPSON_OBJ_CMD","LAMPSON_OBJ_ID","LAMPSON_OBJ_AGENT","LAMPSON_OBJ_TEAM","LAMPSON_OBJ_BUDGET","LAMPSON_OBJ_ROUND","LAMPSON_OBJ_DECISION","LAMPSON_TEAM_CMD") { Remove-Item "Env:$v" -ErrorAction SilentlyContinue } }
234
241
  }
235
242
  } finally {
236
243
  Pop-Location
package/lampson.sh CHANGED
@@ -12,6 +12,8 @@
12
12
  # lampson key add [--agent ID[,ID]] [--name NOMBRE] [--rate N] [--callback URL] · key list · key remove <id> # API keys /v1
13
13
  # lampson mcp serve [--agent ID[,ID]] [--workspace RUTA] # Lampson como servidor MCP (stdio) para otros agentes
14
14
  # lampson channel list · channel on|off <canal> · channel setup <canal> # canales (Telegram, Chatwoot…)
15
+ # lampson plugin list · plugin on|off <nombre> # encender plugins sin interfaz (VPS por SSH, scripts)
16
+ # lampson tools list · tools approve [nombre] # herramientas .syn del proyecto: corren solo aprobadas
15
17
  # lampson objective add "…" --agent ID | --team ID [--budget N] [--round S] · objective list · show <id> · reply <id> "…" [--approve|--deny] · cancel <id> # objetivos
16
18
  # lampson team list # equipos de agentes y quién reporta a quién
17
19
  set -euo pipefail
@@ -19,7 +21,7 @@ set -euo pipefail
19
21
  here="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
20
22
  caller="$(pwd)"
21
23
  ws=""; web=0; hub=""; install=""; domain="-"; email=""; pair_url="-"
22
- run=0; msg=""; perm_flag=""; key=""; key_name=""; key_id=""; mcp_serve=""; ch_cmd=""; ch_name=""
24
+ run=0; msg=""; perm_flag=""; key=""; key_name=""; key_id=""; mcp_serve=""; ch_cmd=""; ch_name=""; pl_cmd=""; pl_name=""; tl_cmd=""
23
25
  obj_cmd=""; obj_id=""; obj_team=""; obj_budget=""; obj_round=""; obj_decision=""; team_cmd=""
24
26
  # `lampson run …`: subcomando sin interfaz (run.syn); las palabras sueltas son el mensaje, no el workspace
25
27
  if [ "${1:-}" = run ]; then run=1; shift; fi
@@ -28,6 +30,10 @@ if [ "${1:-}" = run ]; then run=1; shift; fi
28
30
  if [ "${1:-}" = mcp ] && [ "${2:-}" = serve ]; then run=1; mcp_serve=1; shift 2; fi
29
31
  # `lampson channel list|on|off|setup <canal>` (run.syn con LAMPSON_CHANNEL_CMD)
30
32
  if [ "${1:-}" = channel ]; then run=1; ch_cmd="${2:-list}"; shift; [ $# -gt 0 ] && shift; fi
33
+ # `lampson plugin list|on|off <nombre>` (run.syn con LAMPSON_PLUGIN_CMD)
34
+ # `lampson tools list|approve [nombre]` (run.syn con LAMPSON_TOOLS_CMD): aprobar las herramientas .syn del proyecto
35
+ if [ "${1:-}" = tools ]; then run=1; tl_cmd="${2:-list}"; shift; [ $# -gt 0 ] && shift; fi
36
+ if [ "${1:-}" = plugin ]; then run=1; pl_cmd="${2:-list}"; shift; [ $# -gt 0 ] && shift; fi
31
37
  if [ "${1:-}" = key ]; then run=1; key="${2:-help}"; shift; [ $# -gt 0 ] && shift; fi
32
38
  # `lampson objective add|list|show|reply|cancel` y `lampson team list` (run.syn con LAMPSON_OBJ_CMD / LAMPSON_TEAM_CMD)
33
39
  if [ "${1:-}" = objective ]; then run=1; obj_cmd="${2:-list}"; shift; [ $# -gt 0 ] && shift; fi
@@ -60,13 +66,13 @@ while [ $# -gt 0 ]; do
60
66
  --deny) obj_decision=deny ;;
61
67
  --update) echo "actualizando Lampson en $here"; git -C "$here" pull --ff-only origin main; echo "lampson $(git -C "$here" rev-parse --short HEAD)"; exit $? ;;
62
68
  -*) echo "uso: lampson run [--agent ID] [--thread T|--session ID] [--json] [--yolo|--strict|--ask] [mensaje]" >&2; echo "uso: lampson [--web] [--hub start|stop|status|logs|restart] [--domain DOMINIO|off [--email EMAIL]] [--pair [URL]] [--install|--uninstall] [--workspace RUTA] [--agent PERFIL] [--yolo|--strict|--ask] [--update]" >&2; exit 1 ;;
63
- *) if [ -n "$obj_cmd" ] && [ -z "$obj_id" ] && { [ "$obj_cmd" = show ] || [ "$obj_cmd" = reply ] || [ "$obj_cmd" = cancel ]; }; then obj_id="$1"; elif [ -n "$obj_cmd" ]; then msg="${msg:+$msg }$1"; elif [ -n "$ch_cmd" ]; then ch_name="$1"; elif [ -n "$key" ]; then key_id="$1"; elif [ "$run" = 1 ]; then msg="${msg:+$msg }$1"; else ws="$1"; fi ;;
69
+ *) if [ -n "$obj_cmd" ] && [ -z "$obj_id" ] && { [ "$obj_cmd" = show ] || [ "$obj_cmd" = reply ] || [ "$obj_cmd" = cancel ]; }; then obj_id="$1"; elif [ -n "$obj_cmd" ]; then msg="${msg:+$msg }$1"; elif [ -n "$ch_cmd" ]; then ch_name="$1"; elif [ -n "$pl_cmd" ] || [ -n "$tl_cmd" ]; then pl_name="$1"; elif [ -n "$key" ]; then key_id="$1"; elif [ "$run" = 1 ]; then msg="${msg:+$msg }$1"; else ws="$1"; fi ;;
64
70
  esac
65
71
  shift
66
72
  done
67
73
  export LAMPSON_HOME="$here"
68
- # motor mínimo: el hub y los workspaces declaran `trust proxy` (Synsema 0.6.42+; ver lib/origin.syn)
69
- min_engine="0.6.42"
74
+ # motor mínimo: `trust proxy` (0.6.42+) y, para las herramientas de la app, --cap-set, --no-env-file y http_sign (0.6.44)
75
+ min_engine="0.6.44"
70
76
  engine="$(synsema --version 2>/dev/null | sed 's/^[^0-9]*//')"
71
77
  if [ -z "$engine" ] || [ "$(printf '%s\n%s\n' "$min_engine" "$engine" | sort -V | head -n1)" != "$min_engine" ]; then
72
78
  echo "lampson necesita synsema $min_engine o más nuevo (tenés '${engine:-ninguno}'): synsema update" >&2; exit 1
@@ -183,7 +189,7 @@ if [ "$run" = 1 ]; then
183
189
  # sin interfaz: los permisos los fija el flag, o el agente (run.syn: strict si el agente no dice nada)
184
190
  entry=run.syn; export LAMPSON_MESSAGE="$msg" LAMPSON_RUN_PERMISSION="$perm_flag"
185
191
  export LAMPSON_KEY_CMD="$key" LAMPSON_KEY_NAME="$key_name" LAMPSON_KEY_ID="$key_id" LAMPSON_KEY_AGENTS="${LAMPSON_AGENT:-}"
186
- export LAMPSON_CHANNEL_CMD="$ch_cmd" LAMPSON_CHANNEL_NAME="$ch_name"
192
+ export LAMPSON_CHANNEL_CMD="$ch_cmd" LAMPSON_CHANNEL_NAME="$ch_name" LAMPSON_PLUGIN_CMD="$pl_cmd" LAMPSON_PLUGIN_NAME="$pl_name" LAMPSON_TOOLS_CMD="$tl_cmd" LAMPSON_TOOLS_NAME="$pl_name"
187
193
  export LAMPSON_OBJ_CMD="$obj_cmd" LAMPSON_OBJ_ID="$obj_id" LAMPSON_OBJ_AGENT="$([ -n "$obj_cmd" ] && echo "${LAMPSON_AGENT:-}")" LAMPSON_OBJ_TEAM="$obj_team"
188
194
  export LAMPSON_OBJ_BUDGET="$obj_budget" LAMPSON_OBJ_ROUND="$obj_round" LAMPSON_OBJ_DECISION="$obj_decision" LAMPSON_TEAM_CMD="$team_cmd"
189
195
  export LAMPSON_MCP_SERVE="$mcp_serve" LAMPSON_MCP_AGENTS="$([ -n "$mcp_serve" ] && echo "${LAMPSON_AGENT:-}")"
package/lib/api.syn CHANGED
@@ -23,6 +23,12 @@ use "./runtime.syn" as runtime
23
23
  use "./apikeys.syn" as apikeys
24
24
  use "./mailbox.syn" as mailbox
25
25
  use "./teams.syn" as teams
26
+ use "./schedule.syn" as schedule
27
+ use "./worktree.syn" as worktree
28
+ use "./diagnose.syn" as diagnose
29
+ use "./sdktools.syn" as sdktools
30
+ use "./apptools.syn" as apptools
31
+ use "./tools/url.syn" as urls
26
32
 
27
33
 
28
34
  -- la key del header Authorization (o nothing)
@@ -72,6 +78,10 @@ export task agents_for(rec)
72
78
  set out to append(out, {"id": id, "description": runtime.get(id)["description"]})
73
79
  give out
74
80
 
81
+ -- la sesión de un asiento en un objetivo: la que quedó anotada; si no hay (objetivos de antes), la del thread
82
+ task pick_session(own, thread_sid)
83
+ give when own != "" then own otherwise thread_sid
84
+
75
85
  task field(m, k, fallback)
76
86
  when contains(m, k)
77
87
  when m[k] != nothing
@@ -99,7 +109,7 @@ export task parse(body, rec)
99
109
  when cb != "" and not (starts_with(cb, "https://") or starts_with(cb, "http://"))
100
110
  give {"ok": false, "status": 400, "error": "callback must be an http(s) URL"}
101
111
  when cb != "" and not apikeys.callback_allowed(rec, cb)
102
- give {"ok": false, "status": 403, "error": "this API key cannot send callbacks to " + cb + " (allowed: " + join(rec["callbacks"], ", ") + ")"}
112
+ give {"ok": false, "status": 403, "error": "this API key cannot send callbacks to " + cb + (when length(field(rec, "callbacks", [])) > 0 then " (allowed: " + join(rec["callbacks"], ", ") + ")" otherwise ": this API key has no callback list; create one with `lampson key add --callback URL`")}
103
113
  let images be field(body, "images", [])
104
114
  when type_of(images) != "list"
105
115
  set images to []
@@ -113,8 +123,49 @@ export task parse(body, rec)
113
123
  when contains(body, "sent_at") and body["sent_at"] != nothing
114
124
  set meta["sent_at"] to body["sent_at"]
115
125
  let sobre be {"to": target, "thread": text(field(body, "thread", "")), "session": text(field(body, "session", "")), "from": from, "text": msg, "images": images, "channel": text(field(body, "channel", "http")), "meta": meta}
126
+ -- funciones de la app (lib/remotetools.syn): viajan en el mensaje, sin estado en Lampson. tools_url tiene que
127
+ -- estar en la lista de callbacks de la key (obligatoria acá: sin lista no hay tools_url) y ser https salvo loopback
128
+ let rt be field(body, "tools", nothing)
129
+ when rt != nothing
130
+ let tu be text(field(body, "tools_url", ""))
131
+ when tu == ""
132
+ give {"ok": false, "status": 400, "error": "tools needs tools_url: the URL where your app answers the tool calls"}
133
+ let tp be urls.parse(tu)
134
+ when not tp["ok"] or contains(tu, "#") or (tp["scheme"] != "https" and not urls.is_loopback(tp["host"]))
135
+ give {"ok": false, "status": 400, "error": "tools_url must be an https URL without #fragment (http only for localhost)"}
136
+ when length(field(rec, "callbacks", [])) == 0 or not apikeys.callback_allowed(rec, tu)
137
+ give {"ok": false, "status": 403, "error": "this API key cannot call tools at " + tu + ": add it to the key's list (`lampson key add --callback URL`)"}
138
+ when apikeys.signing_secret(rec["id"]) == ""
139
+ give {"ok": false, "status": 403, "error": "this API key predates per-key signing secrets: create a new one to use app tools"}
140
+ let nt be sdktools.normalize(rt)
141
+ when length(nt["errors"]) > 0
142
+ give {"ok": false, "status": 400, "error": join(nt["errors"], "; ")}
143
+ let clash be where(nt["tools"], (t) => contains(apptools.names(), t["name"]))
144
+ when length(clash) > 0
145
+ give {"ok": false, "status": 400, "error": "tool '" + clash[0]["name"] + "' already exists as a Synsema tool of this project (.lampson/tools/)"}
146
+ set sobre["tools"] to nt["tools"]
147
+ set sobre["tools_url"] to tu
148
+ set sobre["tools_key"] to rec["id"]
149
+ set sobre to scope_sobre(sobre, rec)
150
+ -- retomar una sesión: solo una de esta key. Una ajena (otra app, la web del dueño, un equipo) es 404, no una
151
+ -- sesión nueva callada: la app creería que siguió la conversación
152
+ when sobre["session"] != "" and runtime.session_space(sobre["session"]) != sobre["space"]
153
+ give {"ok": false, "status": 404, "error": "no such session: " + sobre["session"]}
116
154
  give {"ok": true, "status": 200, "error": "", "sobre": sobre, "callback": cb, "stream": field(body, "stream", false) == true}
117
155
 
156
+ -- la conversación es de la key que la empezó: por dentro el thread es "key:<id>:<thread>" y la app sigue viendo el
157
+ -- suyo (shown_thread). Antes, dos apps con el mismo thread compartían historial y lote: la de B corría con las
158
+ -- herramientas y el `from` de A (2026-10-19). Tampoco puede escribir en "team:…" u "objective:…".
159
+ export task space_of(rec)
160
+ give "key:" + text(rec["id"]) + ":"
161
+
162
+ task scope_sobre(sobre, rec)
163
+ set sobre["space"] to space_of(rec)
164
+ when sobre["thread"] != ""
165
+ set sobre["shown_thread"] to sobre["thread"]
166
+ set sobre["thread"] to space_of(rec) + sobre["thread"]
167
+ give sobre
168
+
118
169
  -- el modo de un agente por la API: el suyo, y si no dice → strict (nadie en la request para preguntarle)
119
170
  export task mode_for(spec)
120
171
  give when spec != nothing and spec["permission"] != "" then "" otherwise "strict"
@@ -133,7 +184,7 @@ export task create_job(id, rec, sobre, callback)
133
184
  require time
134
185
  require file(".lampson")
135
186
  require file(".lampson/*")
136
- mailbox.save_job({"job": id, "status": "queued", "key": rec["id"], "agent": sobre["to"], "thread": sobre["thread"], "callback": callback, "created": format_time(now()), "result": nothing, "delivered": false, "merged_into": nothing})
187
+ mailbox.save_job({"job": id, "status": "queued", "key": rec["id"], "agent": sobre["to"], "thread": get(sobre, "shown_thread", sobre["thread"]), "callback": callback, "created": format_time(now()), "result": nothing, "delivered": false, "merged_into": nothing})
137
188
 
138
189
  export task job(id)
139
190
  require file.read(".lampson")
@@ -160,10 +211,33 @@ export task objective_view(o)
160
211
  require db(".lampson/teams.db")
161
212
  require file(".lampson")
162
213
  require file(".lampson/*")
214
+ require file.read("workspace")
215
+ require file.read("workspace/*")
163
216
  let scope be teams.obj_scope(o)
164
- let ts be apply(teams.tasks(scope), (t) => {"id": t["id"], "title": t["title"], "status": t["status"], "owner": t["owner"], "notes": t["notes"], "depends": json_decode(t["depends"])})
165
- let lg be apply(teams.ledger(scope, 0, 100), (r) => {"id": r["id"], "at": r["at"], "actor": r["actor"], "kind": r["kind"], "ref": r["ref"], "text": r["text"]})
166
- give {"id": o["id"], "ref": "O-" + text(o["id"]), "agent": o["agent"], "team": o["team"], "text": o["text"], "status": o["status"], "progress": o["progress"], "question": o["question"], "question_kind": o["question_kind"], "result": o["result"], "turns": o["turns"], "spent": o["spent"], "budget_tokens": o["budget_tokens"], "round_seconds": o["round_seconds"], "created_at": o["created_at"], "updated_at": o["updated_at"], "tasks": ts, "ledger": lg}
217
+ let team_obj be field(o, "team", "") != ""
218
+ -- el tablero y el registro de un equipo son de todos sus objetivos: acá, solo lo de este (sus tareas; el registro
219
+ -- de mientras estuvo abierto)
220
+ let mine be when team_obj then where(teams.tasks(scope), (t) => field(t, "objective", 0) == o["id"]) otherwise teams.tasks(scope)
221
+ let ts be apply(mine, (t) => {"id": t["id"], "title": t["title"], "status": t["status"], "owner": t["owner"], "notes": t["notes"], "depends": json_decode(t["depends"])})
222
+ let closed be not contains(["active", "waiting", "paused"], o["status"])
223
+ let rows be when team_obj then where(teams.ledger(scope, 0, 400), (r) => r["at"] >= o["created_at"] - 2 and (not closed or r["at"] <= o["updated_at"] + 60)) otherwise teams.ledger(scope, 0, 150)
224
+ let lg be apply(slice(rows, 0, min(150, length(rows))), (r) => {"id": r["id"], "at": r["at"], "actor": r["actor"], "kind": r["kind"], "ref": r["ref"], "text": r["text"]})
225
+ -- quién trabajó y dónde quedó cada paso: la sesión de cada asiento en la conversación del objetivo (la pantalla lee
226
+ -- su traza con /api/trace y la recorta a la ventana del objetivo)
227
+ let seats be []
228
+ when team_obj
229
+ let tm be teams.get(o["team"])
230
+ when tm != nothing
231
+ each m in tm["members"]
232
+ set seats to append(seats, {"agent": m["agent"], "role": m["role"], "lead": m["agent"] == o["agent"], "today": teams.spent_today(m["agent"]), "cap": teams.cap_of(tm, m["agent"]), "session": pick_session(teams.seat_session_of(o["id"], m["agent"]), runtime.thread_session(m["agent"], scope))})
233
+ otherwise
234
+ set seats to [{"agent": o["agent"], "role": o["agent"], "lead": true, "session": runtime.thread_session(o["agent"], "objective:" + text(o["id"]))}]
235
+ -- el pase entre equipos: de dónde vino, a quién lo pasó, a quién lo puede pasar
236
+ let chain be json_decode(field(o, "chain", "[]"))
237
+ let origin be when field(o, "from_obj", 0) > 0 then {"id": o["from_obj"], "ref": "O-" + text(o["from_obj"]), "team": when length(chain) > 0 then chain[length(chain) - 1] otherwise ""} otherwise nothing
238
+ let passed be apply(teams.obj_children(o["id"]), (c) => {"id": c["id"], "ref": "O-" + text(c["id"]), "team": c["team"], "status": c["status"]})
239
+ let pend be field(o, "pass_pending", "")
240
+ give {"id": o["id"], "ref": "O-" + text(o["id"]), "agent": o["agent"], "team": o["team"], "text": o["text"], "status": o["status"], "progress": o["progress"], "question": o["question"], "question_kind": o["question_kind"], "result": o["result"], "turns": o["turns"], "spent": o["spent"], "budget_tokens": o["budget_tokens"], "round_seconds": o["round_seconds"], "created_at": o["created_at"], "updated_at": o["updated_at"], "created_by": o["created_by"], "tasks": ts, "ledger": lg, "seats": seats, "from": origin, "passed": passed, "pass_to": json_decode(field(o, "pass_to", "[]")), "pass_ask": field(o, "pass_ask", 0) == 1, "pass_pending": when pend == "" then nothing otherwise json_decode(pend)}
167
241
 
168
242
  -- POST /v1/objectives: {agent, text, round_seconds?, budget_tokens?} → {ok, id} / {ok: false, status, error}
169
243
  export task create_objective(body, rec)
@@ -193,7 +267,7 @@ export task create_objective(body, rec)
193
267
  give {"ok": false, "status": 403, "error": "this API key can't use agent '" + agent + "'"}
194
268
  when trim(text(field(body, "text", ""))) == ""
195
269
  give {"ok": false, "status": 400, "error": "text is required"}
196
- let opts be {"budget_tokens": field(body, "budget_tokens", 500000), "created_by": "api:" + rec["name"], "team": tid}
270
+ let opts be {"budget_tokens": field(body, "budget_tokens", 600000), "created_by": "api:" + rec["name"], "team": tid, "pass_ask": field(body, "pass_ask", false) == true}
197
271
  when field(body, "round_seconds", nothing) != nothing
198
272
  set opts["round_seconds"] to body["round_seconds"]
199
273
  let id be teams.obj_create(agent, field(body, "text", ""), opts)
@@ -227,10 +301,10 @@ export task teams_view()
227
301
  let members be []
228
302
  each m in t["members"]
229
303
  let spec be runtime.get(m["agent"])
230
- set members to append(members, {"agent": m["agent"], "role": m["role"], "reports_to": m["reports_to"], "description": when spec == nothing then "" otherwise spec["description"], "system": when spec == nothing then "" otherwise spec["system"], "tools": when spec == nothing then [] otherwise spec["tools"], "permission": when spec == nothing then "" otherwise spec["permission"], "missing": spec == nothing, "working": mailbox.working(m["agent"], scope), "spent_today": teams.spent_today(m["agent"]), "peers": teams.peers(t, m["agent"])})
304
+ set members to append(members, {"agent": m["agent"], "role": m["role"], "reports_to": m["reports_to"], "description": when spec == nothing then "" otherwise spec["description"], "system": when spec == nothing then "" otherwise spec["system"], "tools": when spec == nothing then [] otherwise spec["tools"], "permission": when spec == nothing then "" otherwise spec["permission"], "missing": spec == nothing, "working": mailbox.working(m["agent"], scope), "spent_today": teams.spent_today(m["agent"]), "daily_tokens": m["daily_tokens"], "cap": teams.cap_of(t, m["agent"]), "peers": teams.peers(t, m["agent"])})
231
305
  let ts be apply(teams.tasks(scope), (x) => {"id": x["id"], "title": x["title"], "status": x["status"], "owner": x["owner"], "notes": x["notes"], "depends": json_decode(x["depends"])})
232
306
  let lg be apply(teams.ledger(scope, 0, 150), (r) => {"id": r["id"], "at": r["at"], "actor": r["actor"], "kind": r["kind"], "ref": r["ref"], "text": r["text"]})
233
- set out to append(out, {"id": t["id"], "description": t["description"], "members": members, "talks": t["talks"], "round_minutes": t["round_minutes"], "budget_daily_tokens": t["budget_daily_tokens"], "worktrees": t["worktrees"], "lead": teams.lead_of(t), "tasks": ts, "ledger": lg})
307
+ set out to append(out, {"id": t["id"], "name": t["name"], "description": t["description"], "members": members, "talks": t["talks"], "round_minutes": t["round_minutes"], "budget_daily_tokens": t["budget_daily_tokens"], "worktrees": t["worktrees"], "lead": teams.lead_of(t), "tasks": ts, "ledger": lg})
234
308
  give {"teams": out, "errors": sc["errors"]}
235
309
 
236
310
 
@@ -238,6 +312,147 @@ export task teams_view()
238
312
  -- conserva lo que su archivo ya tenía y pisa solo lo que se editó. → {ok, error}
239
313
  export let TOOL_PRESETS be {"code": ["read", "write", "edit", "ls", "find", "grep", "bash", "todo"], "read": ["read", "ls", "find", "grep", "bash"], "none": []}
240
314
 
315
+ -- las aprobaciones, y en un merge o un push pendiente lo que va a pasar (rama, commits, archivos, si choca): se
316
+ -- aprueba sabiendo qué entra, no leyendo el comando
317
+ export task approvals_view(list)
318
+ require exec
319
+ require time
320
+ require file("workspace")
321
+ require file("workspace/*")
322
+ let out be []
323
+ each a in list
324
+ let x be a
325
+ when a["status"] == "pending" and contains(text(a["why"]), "shared history")
326
+ try
327
+ set x["preview"] to worktree.preview(a["message"])
328
+ recover err
329
+ set x["preview"] to nothing
330
+ set out to append(out, x)
331
+ give out
332
+
333
+ -- darle más tokens por hoy a un asiento: {agent, action: grant|reset, tokens?} → {ok, today, cap}
334
+ export task seat_tokens(body)
335
+ require db(".lampson/teams.db")
336
+ require time
337
+ require file(".lampson")
338
+ require file(".lampson/*")
339
+ require file.read("workspace")
340
+ require file.read("workspace/*")
341
+ let agent be lower(text(field(body, "agent", "")))
342
+ let ts be teams.teams_of(agent)
343
+ when length(ts) == 0
344
+ give {"ok": false, "error": "'" + agent + "' is not in any team"}
345
+ let act be lower(text(field(body, "action", "grant")))
346
+ when act != "grant" and act != "reset"
347
+ give {"ok": false, "error": "action must be grant or reset"}
348
+ let before be teams.spent_today(agent)
349
+ let after be teams.seat_tokens(agent, act, field(body, "tokens", teams.cap_of(ts[0], agent)))
350
+ each t in ts
351
+ teams.log("team:" + t["id"], "person", "tokens", "", agent + ": " + (when act == "reset" then "today's count reset" otherwise "+" + text(before - after) + " tokens for today") + " (" + text(after) + " of " + text(teams.cap_of(t, agent)) + ")")
352
+ give {"ok": true, "today": after, "cap": teams.cap_of(ts[0], agent)}
353
+
354
+ -- «Revisar qué pasa» en un objetivo de equipo: los hechos (sin IA), el análisis (con el modelo) y lo que la persona
355
+ -- hace desde ahí (escribirle a un asiento, mover una tarea)
356
+ export task obj_facts(o)
357
+ require db(".lampson/teams.db")
358
+ require time
359
+ require file(".lampson")
360
+ require file(".lampson/*")
361
+ require file.read("workspace")
362
+ require file.read("workspace/*")
363
+ when field(o, "team", "") == ""
364
+ give []
365
+ give diagnose.facts(o)
366
+
367
+ export task obj_analyze(o)
368
+ require db(".lampson/teams.db")
369
+ require net
370
+ require time
371
+ require env("LAMPSON_*")
372
+ require secret("LAMPSON_*")
373
+ require file(".lampson")
374
+ require file(".lampson/*")
375
+ require file.read("workspace")
376
+ require file.read("workspace/*")
377
+ when field(o, "team", "") == ""
378
+ give {"ok": false, "error": "only team objectives"}
379
+ let r be diagnose.analysis(o)
380
+ when r["ok"]
381
+ teams.log("team:" + o["team"], "lampson", "diagnosed", "O-" + text(o["id"]), r["summary"])
382
+ give r
383
+
384
+ export task obj_act(o, body)
385
+ require db(".lampson/teams.db")
386
+ require time
387
+ require file(".lampson")
388
+ require file(".lampson/*")
389
+ require file.read("workspace")
390
+ require file.read("workspace/*")
391
+ when field(o, "team", "") == ""
392
+ give {"ok": false, "error": "only team objectives"}
393
+ let kind be text(field(body, "kind", ""))
394
+ when kind == "message"
395
+ let ok be teams.person_message(o["team"], lower(text(field(body, "agent", ""))), text(field(body, "text", "")))
396
+ give when ok then {"ok": true} otherwise {"ok": false, "error": "no seat '" + text(field(body, "agent", "")) + "' in this team"}
397
+ when kind == "task"
398
+ let ok be teams.person_move("team:" + o["team"], floor(number(field(body, "task", 0))), text(field(body, "status", "")))
399
+ give when ok then {"ok": true} otherwise {"ok": false, "error": "no such task or status"}
400
+ give {"ok": false, "error": "kind must be message or task"}
401
+
402
+ -- borrar un equipo: {id, agents?}. Se cancelan sus objetivos en curso y se borran sus rutinas (sin equipo no tienen a
403
+ -- quién darle el trabajo); con agents=true (lo que manda la pantalla), también los archivos de sus agentes, salvo el
404
+ -- que está en otro equipo: se crearon para este y sueltos solo confunden. Lo que hizo
405
+ -- queda: el historial de sus objetivos y sus ramas de git. → {ok, cancelled, routines, agents} / {ok: false, error}
406
+ export task delete_team(body)
407
+ require db(".lampson/teams.db")
408
+ require time
409
+ require exec
410
+ require env("LAMPSON_*")
411
+ require file(".lampson")
412
+ require file(".lampson/*")
413
+ require file("workspace")
414
+ require file("workspace/*")
415
+ let id be lower(text(field(body, "id", "")))
416
+ let team be teams.get(id)
417
+ when team == nothing
418
+ give {"ok": false, "error": "no team '" + id + "'"}
419
+ let cancelled be []
420
+ each o in teams.obj_list()
421
+ when o["team"] == id and contains(["active", "waiting", "paused"], o["status"])
422
+ teams.obj_cancel(o["id"], "person")
423
+ set cancelled to append(cancelled, "O-" + text(o["id"]))
424
+ let routines be []
425
+ each t in schedule.all()
426
+ let a be field(t, "action", nothing)
427
+ when a != nothing and type_of(a) == "map" and field(a, "type", "") == "objective" and field(a, "team", "") == id
428
+ schedule.remove(t["id"])
429
+ set routines to append(routines, t["id"])
430
+ let others be []
431
+ each t in teams.all()
432
+ when t["id"] != id
433
+ each m in t["members"]
434
+ set others to append(others, m["agent"])
435
+ teams.log("team:" + id, "person", "team deleted", "", text(length(cancelled)) + " objectives cancelled, " + text(length(routines)) + " routines removed")
436
+ -- que un equipo nuevo con el mismo nombre arranque de cero: tablero y registro archivados, conversaciones olvidadas,
437
+ -- y la copia de git de cada asiento propio retirada (su trabajo sin mergear queda en una rama archive/…)
438
+ let archived be teams.archive(id)
439
+ let gone be []
440
+ let branches be []
441
+ each m in team["members"]
442
+ runtime.forget_thread(m["agent"], "team:" + id)
443
+ when not contains(others, m["agent"])
444
+ let w be worktree.retire(id, m["agent"])
445
+ when starts_with(w["branch"], "archive/")
446
+ set branches to append(branches, w["branch"])
447
+ when field(body, "agents", false) == true
448
+ let path be runtime.PROJECT_DIR + "/" + m["agent"] + runtime.SUFFIX
449
+ when file_exists(path)
450
+ delete_file(path)
451
+ set gone to append(gone, m["agent"])
452
+ teams.forget_spend(m["agent"])
453
+ delete_file(teams.DIR + "/" + id + ".team.json")
454
+ give {"ok": true, "cancelled": cancelled, "routines": routines, "agents": gone, "archived": archived, "branches": branches}
455
+
241
456
  export task save_team(body)
242
457
  require db(".lampson/teams.db")
243
458
  require time
@@ -286,7 +501,7 @@ export task save_team(body)
286
501
  give {"ok": false, "error": "agent '" + m["agent"] + "' has no file yet — give it a personality to create it"}
287
502
  each f in files
288
503
  write_file(f["path"], json_encode(f["doc"]))
289
- let raw be {"id": team["id"], "description": team["description"], "members": apply(team["members"], (m) => {"agent": m["agent"], "role": m["role"], "reports_to": m["reports_to"]}), "talks": team["talks"], "round_minutes": team["round_minutes"], "budget_daily_tokens": team["budget_daily_tokens"], "worktrees": team["worktrees"]}
504
+ let raw be {"id": team["id"], "name": team["name"], "description": team["description"], "members": apply(team["members"], (m) => when m["daily_tokens"] > 0 then {"agent": m["agent"], "role": m["role"], "reports_to": m["reports_to"], "daily_tokens": m["daily_tokens"]} otherwise {"agent": m["agent"], "role": m["role"], "reports_to": m["reports_to"]}), "talks": team["talks"], "round_minutes": team["round_minutes"], "budget_daily_tokens": team["budget_daily_tokens"], "worktrees": team["worktrees"]}
290
505
  write_file(teams.DIR + "/" + team["id"] + ".team.json", json_encode(raw))
291
506
  teams.log("team:" + team["id"], "person", "team saved", "", join(apply(team["members"], (m) => m["agent"] + " (" + m["role"] + ")"), ", "))
292
507
  give {"ok": true, "error": ""}