lampson 0.5.0 → 0.5.2

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
@@ -29,6 +29,7 @@ use "./agents.syn" as agents
29
29
  use "./approvals.syn" as approvals
30
30
  use "./permission.syn" as permission
31
31
  use "./plugins.syn" as plugins
32
+ use "./apikeys.syn" as apikeys
32
33
 
33
34
  export let DEFAULT_BUFFER be {"quiet_s": 3, "max_s": 15}
34
35
  export let JOBS_DIR be ".lampson/api/jobs"
@@ -51,7 +52,7 @@ export task key_of(sobre, id)
51
52
  give runtime.thread_key(sobre["to"], th)
52
53
  let ss be text(sobre["session"])
53
54
  when ss != ""
54
- give runtime.thread_key(sobre["to"], "session:" + ss)
55
+ give runtime.thread_key(sobre["to"], get(sobre, "space", "") + "session:" + ss)
55
56
  give runtime.thread_key(sobre["to"], "msg:" + id)
56
57
 
57
58
  -- la espera de un agente: la suya, o la de la puerta (DEFAULT_BUFFER para la API); false → {0, 0}
@@ -168,12 +169,20 @@ export task save_job(j)
168
169
  require file(".lampson/*")
169
170
  write_file(job_path(j["job"]), json_encode(j))
170
171
 
171
- task post_callback(url, payload)
172
+ -- firma: con el secreto de la key que pidió la callback (apikeys, desde 2026-10-18) y si no tiene, el global de
173
+ -- antes. X-Lampson-Key dice cuál: la app verifica con el secreto de esa key (Lampson.verifySignature del SDK)
174
+ task post_callback(url, payload, key_id)
172
175
  require net
173
176
  require env("LAMPSON_*")
177
+ require file.read(".lampson")
178
+ require file.read(".lampson/*")
174
179
  let body be json_encode(payload)
175
180
  let headers be {"Content-Type": "application/json", "User-Agent": "lampson"}
176
- let sec be env("LAMPSON_WEBHOOK_SECRET", "")
181
+ let sec be when key_id != "" then apikeys.signing_secret(key_id) otherwise ""
182
+ when sec == ""
183
+ set sec to env("LAMPSON_WEBHOOK_SECRET", "")
184
+ when key_id != ""
185
+ set headers["X-Lampson-Key"] to key_id
177
186
  when sec != ""
178
187
  set headers["X-Lampson-Signature"] to "sha256=" + decode(hmac(body, sec), "hex")
179
188
  -- dos intentos: un receptor que parpadea no pierde la respuesta
@@ -258,16 +267,19 @@ task run_batch(k, spec, items)
258
267
  recover err
259
268
  set typing_at to typing_at
260
269
  typing()
270
+ -- el thread que mandó la app (sin el "key:<id>:" de lib/api.syn): es el que vuelve en eventos, resultado y callback
271
+ let shown be get(lead, "shown_thread", lead["thread"])
261
272
  task publish(kind, data, tag)
262
273
  when kind == "busy"
263
274
  typing()
264
275
  when kind != "busy" and kind != "idle"
265
- bus_publish(topic, {"kind": kind, "data": data, "tag": tag, "agent": lead["to"], "thread": lead["thread"]})
276
+ bus_publish(topic, {"kind": kind, "data": data, "tag": tag, "agent": lead["to"], "thread": shown})
266
277
  let hooks be {"mode": spec["mode"], "ask_fn": approve_queue, "on_event": publish}
267
278
  let result be nothing
268
279
  try
269
- let o be runtime.open({"to": lead["to"], "thread": lead["thread"], "session": lead["session"], "text": "", "channel": lead["channel"], "meta": lead["meta"]}, hooks)
270
- bus_publish(topic, {"kind": "session", "data": {"session": o["session"], "agent": o["ctx"]["agent"], "thread": o["thread"], "batch": apply((it) => it["id"], ordered)}, "tag": "", "agent": lead["to"], "thread": lead["thread"]})
280
+ -- from (el ctx de las herramientas de la app) y las funciones de la app que mandó el mensaje (lib/remotetools.syn)
281
+ let o be runtime.open({"to": lead["to"], "thread": lead["thread"], "session": lead["session"], "text": "", "channel": lead["channel"], "meta": lead["meta"], "from": get(lead, "from", {}), "tools": get(lead, "tools", []), "tools_url": get(lead, "tools_url", ""), "tools_key": get(lead, "tools_key", ""), "space": get(lead, "space", "")}, hooks)
282
+ bus_publish(topic, {"kind": "session", "data": {"session": o["session"], "agent": o["ctx"]["agent"], "thread": shown, "batch": apply((it) => it["id"], ordered)}, "tag": "", "agent": lead["to"], "thread": shown})
271
283
  when o["note"] != ""
272
284
  publish("inbox", o["note"], "")
273
285
  -- a mitad de turno: lo que llegó mientras el agente trabajaba entra antes de la próxima llamada al modelo
@@ -295,9 +307,9 @@ task run_batch(k, spec, items)
295
307
  set msgs to append(msgs, user_msg(it))
296
308
  let label be join(apply((it) => it["text"], ordered), " ⏎ ")
297
309
  let r be runtime.turn(o, msgs, label, hooks)
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"]}
310
+ set result to {"agent": o["ctx"]["agent"], "thread": when shown != "" then shown otherwise o["thread"], "session": o["session"], "text": r["text"], "steps": r["steps"], "usage": r["usage"], "stopped": r["stopped"]}
299
311
  recover err
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)}
312
+ set result to {"agent": lead["to"], "thread": shown, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
301
313
  -- equipos y objetivos: un turno que falló (proveedor caído, error del runtime) queda en el registro del equipo —
302
314
  -- lo ven el líder en su próximo turno y la pantalla; si no, el equipo esperaría en silencio
303
315
  when starts_with(text(result["stopped"]), "error") and (starts_with(text(lead["thread"]), "team:") or starts_with(text(lead["thread"]), "objective:"))
@@ -319,7 +331,8 @@ task run_batch(k, spec, items)
319
331
  each u in urls
320
332
  let mine be where(all, (it) => it["callback"] == u)
321
333
  let payload be {"job": mine[0]["id"], "jobs": apply((it) => it["id"], mine), "batch": ids, "status": when starts_with(result["stopped"], "error") then "error" otherwise "done", "agent": result["agent"], "thread": result["thread"], "session": result["session"], "text": result["text"], "steps": result["steps"], "usage": result["usage"], "stopped": result["stopped"], "meta": mine[0]["meta"]}
322
- let ok be post_callback(u, payload)
334
+ let j0 be job(mine[0]["id"])
335
+ let ok be post_callback(u, payload, when j0 != nothing and contains(j0, "key") and j0["key"] != nothing then text(j0["key"]) otherwise "")
323
336
  each it in mine
324
337
  when it["job"]
325
338
  let j be job(it["id"])
@@ -395,6 +408,7 @@ export task work(spec_json)
395
408
  agent MailboxWorker
396
409
  require db(".lampson/teams.db")
397
410
  require net
411
+ require sign("LAMPSON_TOOLS")
398
412
  require exec
399
413
  require time
400
414
  require random
@@ -431,7 +445,7 @@ export task submit(sobre, opts)
431
445
  let sent be nothing
432
446
  when contains(sobre["meta"], "sent_at")
433
447
  set sent to sobre["meta"]["sent_at"]
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 ""}
448
+ 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 "", "tools": get(sobre, "tools", []), "tools_url": get(sobre, "tools_url", ""), "tools_key": get(sobre, "tools_key", ""), "shown_thread": get(sobre, "shown_thread", sobre["thread"]), "space": get(sobre, "space", "")}
435
449
  when post(k, item)
436
450
  -- el worker espera {quiet_s, max_s}: false/nothing (sin espera) se normaliza acá — con `false` el worker
437
451
  -- moría al primer settle y la conversación quedaba trabada (visto 2026-10-16)
@@ -58,7 +58,8 @@ task text_result(t, structured, is_error)
58
58
  give {"content": [{"type": "text", "text": t}], "structuredContent": structured, "isError": is_error}
59
59
 
60
60
  -- tools/call → resultado MCP (no se llama `call`: taparía al builtin call() que invoca deliver_fn)
61
- export task run_tool(name, args, agents_list, deliver_fn)
61
+ -- space: "key:<id>:" por HTTP (lib/api.syn space_of), "" por stdio — la conversación es de la key
62
+ export task run_tool(name, args, agents_list, deliver_fn, space = "")
62
63
  require net
63
64
  require exec
64
65
  require time
@@ -92,7 +93,7 @@ export task run_tool(name, args, agents_list, deliver_fn)
92
93
  let lim be when contains(args, "limit") and args["limit"] != nothing then floor(number(args["limit"])) otherwise 20
93
94
  when lim < 1 or lim > 100
94
95
  set lim to 20
95
- let sid be runtime.thread_session(hag, hth)
96
+ let sid be runtime.thread_session(hag, space + hth)
96
97
  when sid == ""
97
98
  give text_result("no conversation with " + hag + " in thread '" + hth + "' yet", {"agent": hag, "thread": hth, "messages": []}, false)
98
99
  let msgs be []
@@ -117,7 +118,7 @@ export task run_tool(name, args, agents_list, deliver_fn)
117
118
  let mode be when spec["permission"] != "" then "" otherwise "strict"
118
119
  let r be nothing
119
120
  try
120
- set r to call(deliver_fn, {"sobre": {"to": agent, "thread": thread, "session": "", "from": {"id": "", "name": "", "kind": "agent"}, "text": msg, "images": [], "channel": "mcp", "meta": {}}, "mode": mode})
121
+ set r to call(deliver_fn, {"sobre": {"to": agent, "thread": space + thread, "shown_thread": thread, "space": space, "session": "", "from": {"id": "", "name": "", "kind": "agent"}, "text": msg, "images": [], "channel": "mcp", "meta": {}}, "mode": mode})
121
122
  recover err
122
123
  give text_result("error: " + text(err), {"agent": agent, "thread": thread}, true)
123
124
  let failed be starts_with(r["stopped"], "error")
@@ -126,7 +127,7 @@ export task run_tool(name, args, agents_list, deliver_fn)
126
127
  give text_result(body + footer, {"agent": agent, "thread": thread, "session": r["session"], "text": r["text"], "steps": r["steps"], "stopped": r["stopped"]}, failed)
127
128
 
128
129
  -- un mensaje JSON-RPC → la respuesta (map), o nothing si era una notificación (no se responde)
129
- export task handle(req, agents_list, deliver_fn)
130
+ export task handle(req, agents_list, deliver_fn, space = "")
130
131
  require net
131
132
  require exec
132
133
  require time
@@ -164,7 +165,7 @@ export task handle(req, agents_list, deliver_fn)
164
165
  give {"jsonrpc": "2.0", "id": id, "result": {"tools": tools_list(agents_list)}}
165
166
  when method == "tools/call"
166
167
  let args be when contains(params, "arguments") and params["arguments"] != nothing then params["arguments"] otherwise {}
167
- give {"jsonrpc": "2.0", "id": id, "result": run_tool(text(params["name"]), args, agents_list, deliver_fn)}
168
+ give {"jsonrpc": "2.0", "id": id, "result": run_tool(text(params["name"]), args, agents_list, deliver_fn, space)}
168
169
  give {"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "method not found: " + method}}
169
170
 
170
171
  -- stdio: el turno directo (un solo cliente, un proceso)
@@ -11,6 +11,7 @@
11
11
 
12
12
  use "./tools/url.syn" as u
13
13
  use "./computer.syn" as computer
14
+ use "./apptools.syn" as apptools
14
15
 
15
16
  -- Tier 1: nunca. Coincidencia por substring, case-insensitive.
16
17
  -- (el comando se evalúa con un espacio final añadido, así "rm -rf / " matchea la raíz pero NO "rm -rf /tmp/x")
@@ -31,7 +32,8 @@ export let DANGEROUS be [
31
32
  "npm publish", "cargo publish", "pip upload", "twine upload",
32
33
  "docker rm", "docker system prune", "kubectl delete",
33
34
  "chmod", "chown", "> ~/", "crontab",
34
- "> .env", ">.env", ">> .env", "tee .env", "> ./.env"
35
+ "> .env", ">.env", ">> .env", "tee .env", "> ./.env",
36
+ ".lampson"
35
37
  ]
36
38
 
37
39
  task contains_any(haystack, needles)
@@ -51,6 +53,16 @@ task is_secret_env(base)
51
53
  give false
52
54
  give true
53
55
 
56
+ -- ¿la ruta cae en la config del proyecto (.lampson/: agentes, herramientas .syn) o en la carpeta de herramientas?
57
+ -- Ahí un agente se subiría su propio techo: editar estado_pedido.syn y agregarle `require exec` (2026-10-19)
58
+ task in_lampson_dir(p)
59
+ let parts be where(split(p, "/"), (s) => s != "" and s != ".")
60
+ when contains(parts, ".lampson")
61
+ give true
62
+ let td be lower(slice(apptools.dir(), length("workspace/"), length(apptools.dir())))
63
+ let rel be join(parts, "/")
64
+ give rel == td or starts_with(rel, td + "/")
65
+
54
66
  -- (`and` no cortocircuita en Synsema: indexar args["action"] sin la clave explota → helper con when anidado)
55
67
  task is_install(args)
56
68
  when not contains(args, "action")
@@ -98,6 +110,15 @@ export task evaluate(name, args, mode)
98
110
  let p be when contains(args, "path") then lower(replace(text(args["path"]), "\\", "/")) otherwise ""
99
111
  let parts be split(p, "/")
100
112
  let base be parts[length(parts) - 1]
113
+ when in_lampson_dir(p)
114
+ -- como instalar un plugin: humano siempre, incluso en yolo; strict lo niega
115
+ when ends_with(p, "apptools_approved.json")
116
+ when mode == "strict"
117
+ give {"decision": "deny", "reason": "strict mode (the app tools' approvals)"}
118
+ give {"decision": "ask", "reason": "writes " + text(args["path"]) + ": the list of APPROVED app tools — approving this lets the agent approve its own tools"}
119
+ when mode == "strict"
120
+ give {"decision": "deny", "reason": "strict mode (writes Lampson's project config or app tools)"}
121
+ give {"decision": "ask", "reason": "writes " + text(args["path"]) + ": Lampson's project config or an app tool (what it can do is set there)"}
101
122
  when is_secret_env(base)
102
123
  when mode == "yolo"
103
124
  give {"decision": "allow", "reason": "yolo mode (.env)"}
@@ -0,0 +1,76 @@
1
+ -- lib/remotetools.syn — funciones de la app (JS / Python) cuando Lampson corre en otra máquina: modo servidor del SDK
2
+ --
3
+ -- Sin estado en Lampson: las herramientas viajan en cada mensaje de la API /v1 — {"tools": [{name, description,
4
+ -- parameters, timeout?}], "tools_url": "https://…"} — y viven lo que vive ese turno (o ese job, con callback).
5
+ -- Cuando el modelo llama a una, Lampson hace POST tools_url con {call_id, name, args, ctx} y la app contesta en ese
6
+ -- mismo POST {output} o {error}: el mismo mensaje que tool_request / tool_result por stdio (lib/sdktools.syn).
7
+ --
8
+ -- Garantías (2026-10-18, con el agente de frameworks):
9
+ -- * a dónde: tools_url tiene que estar en la lista de callbacks de la key (lista obligatoria, host exacto: lo
10
+ -- revisa lib/api.syn) y el POST sale dentro de `sandbox under {"net": <ese host>}`: aunque la comparación de la
11
+ -- lista tuviera un bug, el motor no deja salir a otro host.
12
+ -- * quién: firma RFC 9421 (http_sign: @method, @target-uri, content-digest, created, keyid = la key) con el
13
+ -- secreto de ESA key — otra app que comparte este Lampson no puede firmar un pedido falso con el ctx que quiera.
14
+ -- Una key de antes de 2026-10-18 (sin secreto propio) no puede usar herramientas remotas.
15
+ -- * fallas: sin respuesta en el plazo → error al modelo, sin reintentar (una herramienta que cobra o cancela no puede
16
+ -- correr dos veces; call_id va firmado para que la app deduplique si algo en el medio reenvía).
17
+
18
+ use "./apikeys.syn" as apikeys
19
+ use "./tools/url.syn" as urls
20
+
21
+ export let MARK be "remotetool"
22
+ let DEFAULT_TIMEOUT be 60
23
+ let MAX_OUT be 60000
24
+
25
+ -- lo que el turno necesita del sobre → {url, key, tools} o nothing
26
+ export task of_sobre(sobre)
27
+ when type_of(sobre) != "map" or not contains(sobre, "tools") or type_of(sobre["tools"]) != "list" or length(sobre["tools"]) == 0
28
+ give nothing
29
+ give {"url": text(get(sobre, "tools_url", "")), "key": text(get(sobre, "tools_key", "")), "tools": sobre["tools"]}
30
+
31
+ export task catalog(remote, allowed_names)
32
+ give apply((t) => {"name": t["name"], "description": t["description"], "parameters": t["parameters"]}, where(remote["tools"], (t) => contains(allowed_names, t["name"])))
33
+
34
+ export task call(name, args, ctx, remote)
35
+ require net
36
+ require time
37
+ require random
38
+ require sign("LAMPSON_TOOLS")
39
+ require file.read(".lampson")
40
+ require file.read(".lampson/*")
41
+ when remote == nothing
42
+ give "ERROR: no app tools in this request"
43
+ let f be where(remote["tools"], (t) => t["name"] == name)
44
+ when length(f) == 0
45
+ give "ERROR: the app sent no tool '" + name + "'"
46
+ let sec be apikeys.signing_secret(remote["key"])
47
+ when sec == ""
48
+ give "ERROR: this API key has no signing secret (it predates them): create a new key to use app tools"
49
+ let u be urls.parse(remote["url"])
50
+ when not u["ok"]
51
+ give "ERROR: invalid tools_url"
52
+ let cid be token()
53
+ let body be json_encode({"call_id": cid, "name": name, "args": when args == nothing then {} otherwise args, "ctx": when ctx == nothing then {} otherwise ctx})
54
+ let headers be http_sign({"method": "POST", "url": remote["url"], "body": body}, as_secret(sec, "LAMPSON_TOOLS"), {"alg": "hmac-sha256", "keyid": remote["key"]})
55
+ set headers["Content-Type"] to "application/json"
56
+ set headers["User-Agent"] to "lampson"
57
+ set headers["X-Lampson-Key"] to remote["key"]
58
+ let tmo be number(get(f[0], "timeout", DEFAULT_TIMEOUT), DEFAULT_TIMEOUT)
59
+ let techo be {"net": u["host"]}
60
+ let r be nothing
61
+ try
62
+ sandbox under techo
63
+ set r to http_post(remote["url"], body, headers, tmo)
64
+ recover err
65
+ give "ERROR: the app's tool '" + name + "' did not answer: " + text(err)
66
+ when r == nothing
67
+ give "ERROR: the app's tool '" + name + "' did not answer"
68
+ when not r["ok"]
69
+ give "ERROR: the app answered HTTP " + text(r["status"]) + " for tool '" + name + "': " + slice(text(r["body"]), 0, 300)
70
+ let doc be json_decode(text(r["body"]), nothing)
71
+ when type_of(doc) != "map"
72
+ give "ERROR: the app's answer for tool '" + name + "' is not JSON {output} or {error}"
73
+ when get(doc, "error", nothing) != nothing
74
+ give "ERROR: " + text(doc["error"])
75
+ let o be get(doc, "output", nothing)
76
+ give when o == nothing then "(no output)" otherwise slice(when type_of(o) == "text" then o otherwise json_encode(o), 0, MAX_OUT)
package/lib/runtime.syn CHANGED
@@ -40,6 +40,9 @@ use "./session.syn" as session
40
40
  use "./trace.syn" as trace
41
41
  use "./mcp.syn" as mcp
42
42
  use "./plugins.syn" as plugins
43
+ use "./apptools.syn" as apptools
44
+ use "./sdktools.syn" as sdktools
45
+ use "./remotetools.syn" as remotetools
43
46
  use "./tools/proc.syn" as proc
44
47
  use "./scope.syn" as scope
45
48
  use "./teams.syn" as teams
@@ -249,7 +252,7 @@ task team_tools(spec)
249
252
  give false
250
253
  give contains(spec["tools"], "send") or contains(spec["tools"], "board") or length(teams.teams_of(spec["id"])) > 0
251
254
 
252
- export task registry_of(spec)
255
+ task registry_full(spec)
253
256
  require exec
254
257
  require time
255
258
  require file(".lampson")
@@ -274,13 +277,21 @@ export task registry_of(spec)
274
277
  each m in plugins.names(false)
275
278
  when allowed(spec["tools"], m)
276
279
  set reg[m] to "plugin"
280
+ -- herramientas de la app (lib/apptools.syn): un archivo .syn por herramienta en .lampson/tools/ del proyecto
281
+ each m in apptools.names()
282
+ when allowed(spec["tools"], m)
283
+ set reg[m] to apptools.MARK
284
+ -- funciones de la app registradas con lampson.tool() (lib/sdktools.syn; solo con el SDK en modo local)
285
+ each m in sdktools.names()
286
+ when allowed(spec["tools"], m) and not contains(reg, m)
287
+ set reg[m] to sdktools.MARK
277
288
  -- equipos (lib/teams.syn): un miembro coordina con send y board; fuera de un equipo, solo si los lista
278
289
  when team_tools(spec)
279
290
  set reg["send"] to teams.send_tool
280
291
  set reg["board"] to teams.board_tool
281
292
  give reg
282
293
 
283
- export task catalog_of(spec)
294
+ task catalog_full(spec)
284
295
  require exec
285
296
  require time
286
297
  require file(".lampson")
@@ -300,10 +311,104 @@ export task catalog_of(spec)
300
311
  when contains(names, "delegate")
301
312
  set cat to append(cat, agents.DELEGATE_SPEC)
302
313
  let extra be where(mcp.catalog(false) + plugins.catalog(false), (s) => allowed(spec["tools"], s["name"]))
314
+ set extra to extra + apptools.catalog(where(apptools.names(), (n) => allowed(spec["tools"], n)))
315
+ let app_tools be apptools.names()
316
+ set extra to extra + sdktools.catalog(where(sdktools.names(), (n) => allowed(spec["tools"], n) and not contains(app_tools, n)))
303
317
  when team_tools(spec)
304
318
  set extra to extra + [teams.SEND_SPEC, teams.BOARD_SPEC]
305
319
  give cat + extra
306
320
 
321
+ -- LAMPSON_BUILTIN_TOOLS=off (SDK: lampsonTools: false): el proceso no ofrece NINGUNA tool propia de Lampson (bash,
322
+ -- read, write, fetch, delegate…), ni a los agentes integrados: solo las que trae quien lo usa (plugins, MCP) y la
323
+ -- coordinación de un equipo (send, board). Para una app que embebe un agente: nada que inyectar hacia el shell.
324
+ export task builtin_off()
325
+ require env("LAMPSON_*")
326
+ give lower(env("LAMPSON_BUILTIN_TOOLS", "")) == "off"
327
+
328
+ task external(name)
329
+ give starts_with(name, plugins.PREFIX) or starts_with(name, "mcp_") or name == "send" or name == "board"
330
+
331
+ export task registry_of(spec)
332
+ require exec
333
+ require time
334
+ require file(".lampson")
335
+ require file(".lampson/*")
336
+ require file("workspace")
337
+ require file("workspace/*")
338
+ require file.read("plugins")
339
+ require file.read("plugins/*")
340
+ require file.read("agents")
341
+ require file.read("agents/*")
342
+ require env("LAMPSON_*")
343
+ require env("OS")
344
+ let reg be registry_full(spec)
345
+ when not builtin_off()
346
+ give reg
347
+ let out be {}
348
+ each k in keys(reg)
349
+ when external(k) or reg[k] == apptools.MARK or reg[k] == sdktools.MARK
350
+ set out[k] to reg[k]
351
+ give out
352
+
353
+ export task catalog_of(spec)
354
+ require exec
355
+ require time
356
+ require file(".lampson")
357
+ require file(".lampson/*")
358
+ require file("workspace")
359
+ require file("workspace/*")
360
+ require file.read("plugins")
361
+ require file.read("plugins/*")
362
+ require file.read("agents")
363
+ require file.read("agents/*")
364
+ require env("LAMPSON_*")
365
+ require env("OS")
366
+ let cat be catalog_full(spec)
367
+ when not builtin_off()
368
+ give cat
369
+ let keep be keys(registry_of(spec))
370
+ give where(cat, (s) => contains(keep, s["name"]))
371
+
372
+ -- las tools que el agente lista y no va a tener (plugin apagado o inexistente, MCP caído, nombre mal escrito) →
373
+ -- un aviso por tool. Sin esto el agente arranca sin su herramienta y nadie se entera (2026-10-18, prueba del SDK)
374
+ export task missing(spec)
375
+ require exec
376
+ require time
377
+ require file(".lampson")
378
+ require file(".lampson/*")
379
+ require file("workspace")
380
+ require file("workspace/*")
381
+ require file.read("plugins")
382
+ require file.read("plugins/*")
383
+ require file.read("agents")
384
+ require file.read("agents/*")
385
+ require env("LAMPSON_*")
386
+ require env("OS")
387
+ when spec == nothing or spec["builtin"]
388
+ give []
389
+ let have be keys(registry_of(spec))
390
+ let out be []
391
+ each t in spec["tools"]
392
+ when length(where(have, (h) => allowed([t], h))) == 0
393
+ let why be "not a known tool"
394
+ when starts_with(t, plugins.PREFIX)
395
+ let rest be slice(t, length(plugins.PREFIX), length(t))
396
+ let pn be split(rest, "_")[0]
397
+ let found be where(plugins.all(), (l) => l["name"] == pn)
398
+ set why to when length(found) == 0 then "there is no plugin '" + pn + "'" otherwise (when found[0]["error"] != nothing then "plugin '" + pn + "' is broken: " + text(found[0]["error"]) otherwise (when not found[0]["enabled"] then "plugin '" + pn + "' is off (turn it on: lampson plugin on " + pn + ")" otherwise "plugin '" + pn + "' has no such tool"))
399
+ otherwise when apptools.get(t) != nothing
400
+ set why to "tool file " + apptools.dir() + "/" + t + ".syn: " + text(apptools.get(t)["error"])
401
+ otherwise when apptools.load_error() != ""
402
+ set why to "the app tools folder " + apptools.dir() + " could not be read: " + apptools.load_error()
403
+ otherwise when builtin_off() and (t == "delegate" or contains(apply((s) => s["name"], tools.CATALOG), t))
404
+ set why to "Lampson's own tools are off in this process (lampsonTools: false)"
405
+ otherwise when starts_with(t, "mcp_")
406
+ set why to "no MCP server provides it (is the server configured and running?)"
407
+ when why == "not a known tool"
408
+ set why to "no Lampson tool, plugin, MCP server or app tool (" + apptools.dir() + "/" + t + ".syn, or lampson.tool() in the SDK) has that name"
409
+ set out to append(out, "agent '" + spec["id"] + "': tool '" + t + "' is not available: " + why)
410
+ give out
411
+
307
412
  -- ---------- boot: cfg + system + opts de un agente ----------
308
413
 
309
414
  task pick(a, b)
@@ -350,8 +455,15 @@ export task opts_for(id, mode, ask_fn)
350
455
  set opts["budget_tokens"] to spec["budget_tokens"]
351
456
  when length(keys(spec["scopes"])) > 0
352
457
  set opts["scopes"] to spec["scopes"]
353
- when length(keys(spec["approve"])) > 0
354
- set opts["approve"] to spec["approve"]
458
+ -- una herramienta de la app que declara `require spend(…)` pide aprobación siempre, salvo que el agente diga otra cosa
459
+ let appr be spec["approve"]
460
+ each k in keys(opts["registry"])
461
+ when opts["registry"][k] == apptools.MARK and not contains(appr, k)
462
+ let at be apptools.get(k)
463
+ when at != nothing and at["spend"]
464
+ set appr[k] to "ask"
465
+ when length(keys(appr)) > 0
466
+ set opts["approve"] to appr
355
467
  -- buzón de subagentes: los integrados siempre (igual que antes); uno del proyecto solo si puede delegar
356
468
  when spec["builtin"] or contains(spec["tools"], "delegate")
357
469
  set opts to loop.with_inbox(opts, agents.parent_inbox, "")
@@ -382,7 +494,8 @@ export task system_for(id, cfg)
382
494
  require secret("LAMPSON_*")
383
495
  let spec be spec_or_raise(id)
384
496
  -- 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"]))
497
+ let tnames be apply(catalog_of(spec), (s) => s["name"])
498
+ let extra be plugins.instructions(tnames) + apptools.instructions(tnames)
386
499
  -- su equipo: rol, a quién reporta, a quién le puede escribir, cómo se usa el tablero (lib/teams.syn)
387
500
  when not spec["builtin"]
388
501
  set extra to extra + teams.instructions(spec["id"])
@@ -428,11 +541,24 @@ export task fresh_session()
428
541
  let i be 0
429
542
  while i < 20
430
543
  set i to i + 1
431
- let id be base + "-" + slice(text(10000 + floor(random() * 10000)), 1, 5)
544
+ -- antes 4 dígitos: con la hora, se adivinaba (2026-10-19). La API además exige que sea de su key
545
+ let id be base + "-" + token(16)
432
546
  when not session.exists(id)
433
547
  give id
434
548
  raise("could not allocate a session id")
435
549
 
550
+ -- de qué key es una sesión ("key:<id>:", lib/api.syn space_of); "" si no es de la API o no existe
551
+ export task session_space(sid)
552
+ require file.read(".lampson")
553
+ require file.read(".lampson/*")
554
+ when not session.exists(sid)
555
+ give ""
556
+ try
557
+ let doc be session.load(sid)
558
+ give when contains(doc, "meta") and type_of(doc["meta"]) == "map" and contains(doc["meta"], "space") then text(doc["meta"]["space"]) otherwise ""
559
+ recover err
560
+ give ""
561
+
436
562
  -- la sesión de (agente, thread) si ya existe; "" si no
437
563
  export task thread_session(agent, thread)
438
564
  require file.read(".lampson")
@@ -489,6 +615,11 @@ export task open(sobre, hooks)
489
615
  let ctx be boot(id, hooks, field(hooks, "ask_fn", nothing))
490
616
  let thread be text(field(sobre, "thread", ""))
491
617
  let sid be text(field(sobre, "session", ""))
618
+ -- por la API (space = "key:<id>:"): solo una sesión de esa key, y su thread nunca se adopta (lib/api.syn ya
619
+ -- contestó 404 a una ajena; esto es la segunda capa)
620
+ let space be text(field(sobre, "space", ""))
621
+ when sid != "" and space != "" and session_space(sid) != space
622
+ raise("no such session: " + sid)
492
623
  when sid != "" and not session.exists(sid)
493
624
  set sid to ""
494
625
  when sid == ""
@@ -499,7 +630,7 @@ export task open(sobre, hooks)
499
630
  let doc be session.load(sid)
500
631
  let prev be doc["messages"]
501
632
  set messages to [ctx["system"]] + slice(prev, 1, length(prev))
502
- when thread == "" and contains(doc["meta"], "thread")
633
+ when thread == "" and space == "" and contains(doc["meta"], "thread")
503
634
  set thread to text(doc["meta"]["thread"])
504
635
  -- sesión guardada por otra corrida de lampson: sus procesos ya no viven — decírselo al modelo (una vez)
505
636
  when session.from_other_run(doc)
@@ -538,9 +669,26 @@ export task open(sobre, hooks)
538
669
  set copts["registry"] to reg
539
670
  set copts["catalog"] to where(copts["catalog"], (s) => s["name"] != "board" and s["name"] != "objective") + [teams.BOARD_SPEC, teams.OBJECTIVE_SPEC]
540
671
  set ctx["opts"] to copts
672
+ -- contexto de confianza para las herramientas de la app (lib/apptools.syn): lo pone quien manda el sobre, el
673
+ -- modelo no lo ve ni lo escribe
674
+ let aopts be ctx["opts"]
675
+ set aopts["tool_ctx"] to {"from": field(sobre, "from", {}), "thread": thread, "agent": ctx["agent"], "session": sid, "meta": field(sobre, "meta", {}), "channel": text(field(sobre, "channel", ""))}
676
+ -- funciones de la app que viajan en el mensaje (modo servidor, lib/remotetools.syn): solo las que el agente lista
677
+ -- y sin pisar ninguna que ya tenga
678
+ let remote be remotetools.of_sobre(sobre)
679
+ when remote != nothing
680
+ let rspec be ctx["spec"]
681
+ let rreg be aopts["registry"]
682
+ let rnames be where(apply((t) => t["name"], remote["tools"]), (n) => allowed(rspec["tools"], n) and not contains(rreg, n))
683
+ each n in rnames
684
+ set rreg[n] to remotetools.MARK
685
+ set aopts["registry"] to rreg
686
+ set aopts["catalog"] to aopts["catalog"] + remotetools.catalog(remote, rnames)
687
+ set aopts["remote_tools"] to remote
688
+ set ctx["opts"] to aopts
541
689
  -- sesión actual (blackboard): la tool todo guarda su lista por sesión (lib/tools/todo.syn)
542
690
  share {"id": sid} as "lampson:session"
543
- give {"ctx": ctx, "session": sid, "thread": thread, "messages": messages, "mode": ctx["opts"]["permission_mode"], "note": note}
691
+ give {"ctx": ctx, "session": sid, "thread": thread, "messages": messages, "mode": ctx["opts"]["permission_mode"], "note": note, "space": space}
544
692
 
545
693
  -- guarda la sesión con su agente y thread (y el índice del thread)
546
694
  export task save(o, messages)
@@ -548,7 +696,7 @@ export task save(o, messages)
548
696
  require file(".lampson")
549
697
  require file(".lampson/*")
550
698
  require env("LAMPSON_*")
551
- session.save(o["session"], messages, {"title": session.title_of(messages), "agent": o["ctx"]["agent"], "thread": o["thread"]})
699
+ session.save(o["session"], messages, {"title": session.title_of(messages), "agent": o["ctx"]["agent"], "thread": o["thread"], "space": text(field(o, "space", ""))})
552
700
  remember_thread(o["ctx"]["agent"], o["thread"], o["session"])
553
701
 
554
702
  -- la vista en vivo de un objetivo (public/js/objlive.js): cada paso de un asiento de equipo u objetivo sale al bus
@@ -0,0 +1,73 @@
1
+ -- lib/sdktools.syn — herramientas que son funciones de la app (JS / Python), registradas con lampson.tool() del SDK
2
+ --
3
+ -- Solo en `lampson run --stdio` (el modo local del SDK): la función corre DENTRO del proceso de la app, con su base
4
+ -- de datos, su auth y sus tipos. Lampson pone lo suyo: qué agente la tiene (la lista de tools del agente), aprobación
5
+ -- ("approve" del agente), plazo y el registro de la llamada. Lo que hace la función adentro es de la app: no hay techo
6
+ -- de Synsema (para eso, una herramienta .syn — lib/apptools.syn).
7
+ --
8
+ -- Protocolo (run.syn):
9
+ -- SDK → Lampson {"op": "tools", "tools": [{name, description, parameters, timeout?}]} reemplaza la lista entera
10
+ -- Lampson → SDK {"id": "", "kind": "tool_request", "data": {call_id, name, args, ctx}}
11
+ -- SDK → Lampson {"op": "tool_result", "call_id", "output"} | {…, "error"}
12
+ -- La lista vive en el blackboard ("sdk:tools"): la escribe el hilo principal y la leen los StdioJob. La respuesta
13
+ -- vuelve por el bus ("sdktool.result"); cada llamada espera la suya por call_id.
14
+
15
+ use "./apptools.syn" as apptools
16
+
17
+ export let MARK be "sdktool"
18
+ let DEFAULT_TIMEOUT be 60
19
+ let MAX_TIMEOUT be 600
20
+
21
+ -- valida y normaliza lo que mandó el SDK → {tools, errors}
22
+ export task normalize(raw)
23
+ let out be []
24
+ let errors be []
25
+ when type_of(raw) != "list"
26
+ give {"tools": [], "errors": ["tools must be a list"]}
27
+ each t in raw
28
+ let n be when type_of(t) == "map" then text(get(t, "name", "")) otherwise ""
29
+ when not matches(n, "[a-z][a-z0-9_]{0,39}")
30
+ set errors to append(errors, "tool name '" + n + "': lowercase letters, digits and _ (max 40), starting with a letter")
31
+ otherwise when contains(apptools.TAKEN, n) or starts_with(n, "plugin_") or starts_with(n, "mcp_")
32
+ set errors to append(errors, "tool name '" + n + "' is a name Lampson already uses")
33
+ otherwise
34
+ let ps be get(t, "parameters", {})
35
+ let tmo be number(get(t, "timeout", DEFAULT_TIMEOUT), DEFAULT_TIMEOUT)
36
+ set out to append(out, {"name": n, "description": text(get(t, "description", "")), "parameters": when type_of(ps) == "map" then ps otherwise {"type": "object", "properties": {}}, "timeout": when tmo <= 0 then DEFAULT_TIMEOUT otherwise (when tmo > MAX_TIMEOUT then MAX_TIMEOUT otherwise tmo)})
37
+ give {"tools": out, "errors": errors}
38
+
39
+ export task all()
40
+ observe "sdk:tools" as st
41
+ when st == nothing or type_of(st) != "map"
42
+ give []
43
+ give st["tools"]
44
+
45
+ export task names()
46
+ give apply((t) => t["name"], all())
47
+
48
+ export task catalog(allowed_names)
49
+ give apply((t) => {"name": t["name"], "description": t["description"], "parameters": t["parameters"]}, where(all(), (t) => contains(allowed_names, t["name"])))
50
+
51
+ -- pedirle la llamada a la app y esperar su respuesta (o el plazo)
52
+ export task call(name, args, ctx)
53
+ require time
54
+ require random
55
+ let f be where(all(), (t) => t["name"] == name)
56
+ when length(f) == 0
57
+ give "ERROR: the app has no tool '" + name + "' registered (lampson.tool)"
58
+ let cid be token()
59
+ let sub be bus_subscribe(["sdktool.result"], {"max_queue": 1000, "on_full": "drop_oldest"})
60
+ bus_publish("stdio.out", {"id": "", "kind": "tool_request", "data": {"call_id": cid, "name": name, "args": when args == nothing then {} otherwise args, "ctx": when ctx == nothing then {} otherwise ctx}})
61
+ let deadline be now() + f[0]["timeout"]
62
+ let res be nothing
63
+ while res == nothing and now() < deadline
64
+ let ev be bus_recv(sub, deadline - now())
65
+ when ev != nothing and type_of(ev["data"]) == "map" and get(ev["data"], "call_id", "") == cid
66
+ set res to ev["data"]
67
+ bus_unsubscribe(sub)
68
+ when res == nothing
69
+ give "ERROR: the app did not answer tool '" + name + "' within " + text(f[0]["timeout"]) + "s"
70
+ when get(res, "error", nothing) != nothing
71
+ give "ERROR: " + text(res["error"])
72
+ let o be get(res, "output", nothing)
73
+ give when o == nothing then "(no output)" otherwise (when type_of(o) == "text" then o otherwise json_encode(o))
package/lib/session.syn CHANGED
@@ -13,7 +13,13 @@ export task new_id()
13
13
  require time
14
14
  give format_time(now(), "%Y%m%d-%H%M%S")
15
15
 
16
+ -- un id es un nombre de archivo: sin / ni .. (un id con ../ abría otro JSON de .lampson)
17
+ export task valid_id(id)
18
+ give matches(text(id), "[A-Za-z0-9_-]{1,96}")
19
+
16
20
  task path_of(id)
21
+ when not valid_id(id)
22
+ raise("invalid session id")
17
23
  give DIR + "/" + id + ".json"
18
24
 
19
25
  export task save(id, messages, meta)
@@ -50,6 +56,8 @@ export task from_other_run(doc)
50
56
  export task exists(id)
51
57
  require file.read(".lampson")
52
58
  require file.read(".lampson/*")
59
+ when not valid_id(id)
60
+ give false
53
61
  try
54
62
  read_file(path_of(id), 1, 1)
55
63
  give true