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
@@ -0,0 +1,142 @@
1
+ -- lib/diagnose.syn — ¿por qué está trabado un objetivo de equipo? (la pantalla «Revisar qué pasa»)
2
+ --
3
+ -- Dos niveles:
4
+ -- * facts(o): lo que se ve sin IA, sacado del tablero, el registro y la traza de cada asiento — quién está
5
+ -- bloqueado y por qué, quién contestó en su respuesta final (que nadie lee), quién se quedó sin pasos, si el
6
+ -- equipo cree que alguien no tiene presupuesto cuando sí lo tiene, hace cuánto no se mueve nada
7
+ -- * analysis(o): el mismo expediente al modelo configurado, que devuelve qué pasó y qué hacer, con acciones de una
8
+ -- lista cerrada (escribirle a un asiento, mover una tarea) que la persona aplica con un botón
9
+ -- (Visto 2026-10-18 con un modelo flojo: el Dev respondió «voy avanzando» en su respuesta final, nadie lo leyó, el
10
+ -- CEO creyó que estaba sin presupuesto y le pidió a la persona esperar a mañana: todo quedó bloqueado.)
11
+ use "./teams.syn" as teams
12
+ use "./trace.syn" as trace
13
+ use "./mailbox.syn" as mailbox
14
+ use "./runtime.syn" as runtime
15
+ use "./provider.syn" as provider
16
+
17
+ task field(m, k, fallback)
18
+ when contains(m, k) and m[k] != nothing
19
+ give m[k]
20
+ give fallback
21
+
22
+ -- el último turno de una sesión, leído de su traza: {calls: [nombres], said, stopped, at}
23
+ export task last_turn(sid)
24
+ require file(".lampson")
25
+ require file(".lampson/*")
26
+ let out be {"calls": [], "said": "", "stopped": "", "trigger": ""}
27
+ when sid == ""
28
+ give out
29
+ let lines be split(trace.tail(sid, 160), "\n")
30
+ let start be -1
31
+ let i be 0
32
+ each line in lines
33
+ when contains(line, "s USER ")
34
+ set start to i
35
+ set i to i + 1
36
+ when start < 0
37
+ give out
38
+ let k be 0
39
+ each line in lines
40
+ when k >= start
41
+ let body be regex_replace(line, "^\\S+ \\+\\s*[0-9.]+s\\s+", "")
42
+ let kind be split(body, " ")[0]
43
+ let txt be trim(slice(body, length(kind), length(body)))
44
+ when kind == "USER"
45
+ set out["trigger"] to slice(regex_replace(txt, "^\\[[^\\]]*\\]\\s*", ""), 0, 160)
46
+ when kind == "CALL"
47
+ set out["calls"] to append(out["calls"], split(txt, " ")[0])
48
+ when kind == "SAY"
49
+ set out["said"] to slice(replace(txt, " ⏎ ", "\n"), 0, 700)
50
+ when kind == "END"
51
+ let parts be split(txt, " · ")
52
+ set out["stopped"] to trim(parts[length(parts) - 1])
53
+ set k to k + 1
54
+ give out
55
+
56
+ -- lo que se ve sin IA. → [{kind, agent, task, text}] (kind: quiet, blocked, waits, unsent, cut, budget_belief, over)
57
+ export task facts(o)
58
+ require db(".lampson/teams.db")
59
+ require time
60
+ require file(".lampson")
61
+ require file(".lampson/*")
62
+ require file.read("workspace")
63
+ require file.read("workspace/*")
64
+ let out be []
65
+ let tm be teams.get(o["team"])
66
+ when tm == nothing
67
+ give out
68
+ let scope be "team:" + tm["id"]
69
+ let ts be where(teams.tasks(scope), (t) => field(t, "objective", 0) == o["id"])
70
+ let busy be where(tm["members"], (m) => mailbox.working(m["agent"], scope))
71
+ let quiet be teams.quiet_for(scope)
72
+ when length(busy) == 0 and quiet >= 300 and o["status"] == "active"
73
+ set out to append(out, {"kind": "quiet", "agent": "", "task": 0, "text": "nobody is working and nothing has moved for " + text(floor(quiet / 60)) + " min"})
74
+ let left be when o["budget_tokens"] > 0 then o["budget_tokens"] - o["spent"] otherwise 1
75
+ each t in ts
76
+ when t["status"] == "blocked"
77
+ set out to append(out, {"kind": "blocked", "agent": t["owner"], "task": t["id"], "text": "#" + text(t["id"]) + " is blocked: " + slice(t["notes"], 0, 240)})
78
+ -- el equipo cree que alguien se quedó sin presupuesto, pero con el objetivo con presupuesto sigue pudiendo
79
+ when left > 0 and matches(lower(t["notes"]), ".*(cap|presupuesto|budget|tokens|sin servicio|fuera de servicio).*")
80
+ set out to append(out, {"kind": "budget_belief", "agent": t["owner"], "task": t["id"], "text": "#" + text(t["id"]) + " waits for " + t["owner"] + " to have budget, but while this objective has budget left (" + text(left) + " tokens) every seat keeps getting turns, even past its daily cap"})
81
+ when t["status"] == "todo"
82
+ each d in json_decode(field(t, "depends", "[]"))
83
+ let x be teams.task_get(scope, floor(number(d)))
84
+ when x != nothing and x["status"] == "blocked"
85
+ set out to append(out, {"kind": "waits", "agent": t["owner"], "task": t["id"], "text": "#" + text(t["id"]) + " waits for #" + text(x["id"]) + ", which is blocked"})
86
+ each m in tm["members"]
87
+ let sid be teams.seat_session_of(o["id"], m["agent"])
88
+ let lt be last_turn(sid)
89
+ let mine be where(ts, (t) => t["owner"] == m["agent"] and t["status"] != "done")
90
+ when lt["said"] != "" and not contains(lt["calls"], "send") and lt["stopped"] == "done" and length(mine) > 0 and length(trim(lt["said"])) > 80
91
+ set out to append(out, {"kind": "unsent", "agent": m["agent"], "task": mine[0]["id"], "text": m["agent"] + " answered in its final reply, which nobody reads (it didn't `send` it): «" + slice(lt["said"], 0, 400) + "»"})
92
+ when lt["stopped"] == "max_steps" or lt["stopped"] == "budget"
93
+ set out to append(out, {"kind": "cut", "agent": m["agent"], "task": when length(mine) > 0 then mine[0]["id"] otherwise 0, "text": m["agent"] + "'s last turn was cut (" + lt["stopped"] + ")" + (when lt["said"] != "" then ": «" + slice(lt["said"], 0, 300) + "»" otherwise "")})
94
+ give out
95
+
96
+ -- el expediente para el modelo: el pedido, el equipo, el tablero, lo último del registro, el último turno de cada uno
97
+ task dossier(o, fs)
98
+ require db(".lampson/teams.db")
99
+ require time
100
+ require file(".lampson")
101
+ require file(".lampson/*")
102
+ require file.read("workspace")
103
+ require file.read("workspace/*")
104
+ let tm be teams.get(o["team"])
105
+ let scope be "team:" + tm["id"]
106
+ let ts be where(teams.tasks(scope), (t) => field(t, "objective", 0) == o["id"])
107
+ let seats be []
108
+ each m in tm["members"]
109
+ let lt be last_turn(teams.seat_session_of(o["id"], m["agent"]))
110
+ set seats to append(seats, "- " + m["agent"] + " (" + m["role"] + (when m["reports_to"] != "" then ", reports to " + m["reports_to"] otherwise ", lead") + ")" + (when mailbox.working(m["agent"], scope) then " — WORKING NOW" otherwise "") + " · today " + text(teams.spent_today(m["agent"])) + " of " + text(teams.cap_of(tm, m["agent"])) + " tokens" + "\n last turn: woken by «" + lt["trigger"] + "» · tools: " + (when length(lt["calls"]) == 0 then "none" otherwise join(lt["calls"], ", ")) + " · ended: " + lt["stopped"] + (when lt["said"] != "" then "\n its final reply (nobody reads it): «" + slice(lt["said"], 0, 500) + "»" otherwise ""))
111
+ let rows be teams.ledger(scope, 0, 400)
112
+ let mine be where(rows, (r) => r["at"] >= o["created_at"] - 2)
113
+ let lg be slice(mine, max(0, length(mine) - 40), length(mine))
114
+ give "OBJECTIVE O-" + text(o["id"]) + " [" + o["status"] + "] spent " + text(o["spent"]) + " of " + text(o["budget_tokens"]) + " tokens\n" + o["text"] + "\n\nSEATS\n" + join(seats, "\n") + "\n\nBOARD\n" + join(apply(ts, (t) => "#" + text(t["id"]) + " [" + t["status"] + "] " + t["title"] + " — " + t["owner"] + (when t["depends"] != "[]" then " · depends on " + t["depends"] otherwise "") + (when t["notes"] != "" then "\n notes: " + slice(t["notes"], 0, 300) otherwise "")), "\n") + "\n\nLAST RECORD ENTRIES\n" + join(apply(lg, (r) => format_time(r["at"], "%H:%M") + " " + r["actor"] + " " + r["kind"] + (when r["ref"] != "" then " " + r["ref"] otherwise "") + (when r["text"] != "" then ": " + slice(r["text"], 0, 260) otherwise "")), "\n") + "\n\nWHAT LAMPSON ALREADY SEES\n" + join(apply(fs, (f) => "- " + f["text"]), "\n") + "\n\nHOW THE TEAM RUNTIME WORKS\n- A seat only gets a turn when a message reaches it (`send`), when the lead's objective round comes, or when Lampson continues a turn that was cut. A seat's final reply is NOT delivered to anyone.\n- The daily cap does NOT stop a seat while the objective still has budget.\n- The person can send a message to any seat, and move tasks on the board."
115
+
116
+ -- el análisis con el modelo configurado. → {ok, summary, actions: [{kind: message|task, agent?, text?, task?, status?, why}]}
117
+ export task analysis(o)
118
+ require db(".lampson/teams.db")
119
+ require net
120
+ require time
121
+ require env("LAMPSON_*")
122
+ require secret("LAMPSON_*")
123
+ require file(".lampson")
124
+ require file(".lampson/*")
125
+ require file.read("workspace")
126
+ require file.read("workspace/*")
127
+ let fs be facts(o)
128
+ let cfg be provider.config()
129
+ let brief be "You are diagnosing why a team of AI agents is stuck on an objective. Read the dossier and answer ONLY with JSON, no prose around it:\n{\"summary\": \"<3 to 6 short sentences, in the same language as the objective text, for the person who owns the team: what happened, why it is stuck, what to do>\", \"actions\": [{\"kind\": \"message\", \"agent\": \"<seat id>\", \"text\": \"<the message the person sends that seat, in the objective's language, concrete: what is true, what to do now, who to tell>\", \"why\": \"<one line>\"}, {\"kind\": \"task\", \"task\": <id>, \"status\": \"todo|doing|review|done|blocked\", \"why\": \"<one line>\"}]}\nAt most 3 actions, the smallest set that gets the work moving again. Prefer messaging the seat that has to act. Don't invent facts that aren't in the dossier.\nA message action is sent BY the person TO that seat, as the person's instruction to the team: never write it as a summary or a question for the person. If the team is waiting for a decision only the person can make (an approval, a choice), don't propose a message or a task move for it: say in the summary what they have to decide and where (the approval waiting for them, or the objective's question). Move a task only when that move lets someone start real work; never to «reflect» who has the ball.\n\n" + dossier(o, fs)
130
+ let r be provider.chat_retry(cfg, [{"role": "system", "content": "You are a precise operations analyst. You answer with JSON only."}, {"role": "user", "content": brief}], [], 2)
131
+ when r["error"] != nothing
132
+ give {"ok": false, "error": text(r["error"]), "facts": fs}
133
+ let raw be text(r["text"])
134
+ let found be regex_find_all(raw, "(?s)\\{.*\\}")
135
+ when length(found) == 0
136
+ give {"ok": true, "summary": trim(raw), "actions": [], "facts": fs, "model": cfg["model"]}
137
+ try
138
+ let j be json_decode(found[0])
139
+ let acts be where(field(j, "actions", []), (x) => type_of(x) == "map" and (field(x, "kind", "") == "message" or field(x, "kind", "") == "task"))
140
+ give {"ok": true, "summary": text(field(j, "summary", "")), "actions": slice(acts, 0, 3), "facts": fs, "model": cfg["model"]}
141
+ recover err
142
+ give {"ok": true, "summary": trim(raw), "actions": [], "facts": fs, "model": cfg["model"]}
package/lib/loop.syn CHANGED
@@ -24,6 +24,9 @@ use "./provider.syn" as provider
24
24
  use "./permission.syn" as permission
25
25
  use "./mcp.syn" as mcp
26
26
  use "./plugins.syn" as plugins
27
+ use "./apptools.syn" as apptools
28
+ use "./sdktools.syn" as sdktools
29
+ use "./remotetools.syn" as remotetools
27
30
  use "./tools/todo.syn" as todo
28
31
  use "./scope.syn" as scope
29
32
  use "./worktree.syn" as worktree
@@ -324,6 +327,12 @@ task execute(tc, opts, on_event)
324
327
  when verdict["decision"] == "deny"
325
328
  emit(on_event, "tool_denied", {"call": tc, "reason": verdict["reason"]}, tag)
326
329
  give "DENIED by policy (" + verdict["reason"] + "). Do not retry this exact action; explain or propose an alternative."
330
+ -- equipos: un asiento que no es el líder no le pregunta a la persona (lib/runtime.syn → escalate_to = su jefe). Lo
331
+ -- que necesita aprobación sube por la cadena: su jefe lo resuelve, o lo lleva hasta el líder, que es quien pregunta
332
+ let boss be when contains(opts, "escalate_to") and opts["escalate_to"] != nothing then text(opts["escalate_to"]) otherwise ""
333
+ when boss != "" and verdict["decision"] == "ask"
334
+ emit(on_event, "tool_denied", {"call": tc, "reason": "needs approval — goes up to " + boss + " (" + verdict["reason"] + ")"}, tag)
335
+ give "NOT RUN: this needs approval (" + verdict["reason"] + "), and in a team approvals go up the chain of command — you don't ask the person. Ask your boss " + boss + " with `send`: say exactly what you want to run and why. They will do it, find another way, or take it up to the lead, who is the only one who asks the person."
327
336
  when verdict["decision"] == "ask"
328
337
  let approved be false
329
338
  let expired be false
@@ -355,6 +364,16 @@ task execute(tc, opts, on_event)
355
364
  -- tools de plugins: un proceso hijo por llamada (lib/plugins.syn)
356
365
  otherwise when registry[name] == "plugin"
357
366
  set out to text(plugins.call(name, args))
367
+ -- herramientas de la app (lib/apptools.syn): un proceso Synsema bajo los require del archivo, con el contexto
368
+ -- del sobre (opts.tool_ctx) aparte de los argumentos que escribió el modelo
369
+ otherwise when registry[name] == apptools.MARK
370
+ set out to text(apptools.call(name, args, when contains(opts, "tool_ctx") then opts["tool_ctx"] otherwise {}))
371
+ -- funciones de la app (lib/sdktools.syn): se las pide al SDK por stdio y espera su respuesta
372
+ otherwise when registry[name] == sdktools.MARK
373
+ set out to text(sdktools.call(name, args, when contains(opts, "tool_ctx") then opts["tool_ctx"] otherwise {}))
374
+ -- funciones de la app en modo servidor (lib/remotetools.syn): POST firmado a tools_url, bajo sandbox under
375
+ otherwise when registry[name] == remotetools.MARK
376
+ set out to text(remotetools.call(name, args, when contains(opts, "tool_ctx") then opts["tool_ctx"] otherwise {}, when contains(opts, "remote_tools") then opts["remote_tools"] otherwise nothing))
358
377
  -- equipos: send/board saben quién llama por opts.agent_id (el modelo no lo elige: se pisa lo que mande)
359
378
  otherwise when name == "send" or name == "board" or name == "objective"
360
379
  let targs be args
@@ -431,6 +450,14 @@ export task run_turn(cfg, messages, opts, on_event)
431
450
  set nudged to true
432
451
  set msgs to noted["msgs"]
433
452
  emit(on_event, "inbox", "presupuesto de tokens al 80% (" + text(spent) + "/" + text(floor(budget)) + "): el harness le pidió al modelo que cierre", tag)
453
+ -- pocos pasos antes del límite, un aviso (una vez): que deje las cosas en orden antes de que se corte — guardar
454
+ -- lo hecho y, en un equipo, contar dónde quedó (visto 2026-10-18: el Dev llegó a 25 pasos a mitad de una tarea,
455
+ -- sin commit ni aviso, y el equipo quedó esperándolo)
456
+ when max_steps > 8 and steps == max_steps - 3
457
+ let wrap be append_to_last_tool(msgs, "[SYSTEM NOTICE — 3 tool calls left in this turn] Finish the step you are on and leave your work in order: save/commit what you have, and if you are in a team, update the board and `send` your status (what is done, what is left). If the work isn't finished, you get a new turn to continue where you left off.")
458
+ when wrap["ok"]
459
+ set msgs to wrap["msgs"]
460
+ emit(on_event, "inbox", "quedan 3 pasos en este turno: el harness le pidió que deje todo en orden", tag)
434
461
  let over_budget be spent >= budget * 0.95
435
462
  let last_step be steps == max_steps or over_budget
436
463
  let cat be when last_step then [] otherwise catalog
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)"}
package/lib/plugins.syn CHANGED
@@ -14,8 +14,10 @@
14
14
  -- "instructions": "INSTRUCTIONS.md" (opcional: cómo usar sus tools — texto, o un .md de su carpeta;
15
15
  -- sin el campo, INSTRUCTIONS.md si existe. Va al prompt de cada
16
16
  -- agente que tenga alguna de sus tools: el plugin trae su proceso)
17
- -- "channel": {"agent": "tienda"}} (opcional: un CANAL — lib/channels.syn. Sus acciones `receive` y
17
+ -- "channel": {"agent": "tienda"}, (opcional: un CANAL — lib/channels.syn. Sus acciones `receive` y
18
18
  -- `send` no son tools del modelo, así que un canal puede no tener tools)
19
+ -- "example": true} (opcional: una plantilla para copiar — plugins/example-hello. Funciona
20
+ -- igual, pero las UIs no la muestran entre los plugins para usar)
19
21
  --
20
22
  -- Cómo corre (patrón "safe runner" de la doc 22-sandbox): cada llamada es UN proceso hijo que termina.
21
23
  -- kind=syn → `synsema run --cap-set stdout,time,env=PLUGIN_*[,caps] <entry>`: el techo lo fija el
@@ -116,7 +118,7 @@ task read_manifest(dir, name, scope, legacy)
116
118
  set instr to trim(ifile)
117
119
  when length(instr) > MAX_INSTRUCTIONS
118
120
  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}}
121
+ 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, "example": contains(doc, "example") and doc["example"] == true}}
120
122
 
121
123
  task scan(dir, scope, legacy)
122
124
  let out be []
@@ -168,7 +170,7 @@ export task all()
168
170
  set l["error"] to nothing
169
171
  set out to append(out, l)
170
172
  otherwise
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"]})
173
+ 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"], "example": false})
172
174
  give out
173
175
 
174
176
  export task enabled()
@@ -491,5 +493,5 @@ export task summary()
491
493
  require env("LAMPSON_*")
492
494
  let out be []
493
495
  each l in all()
494
- set out to append(out, {"name": l["name"], "scope": l["scope"], "kind": l["kind"], "legacy": l["legacy"], "description": l["description"], "enabled": l["enabled"], "error": l["error"], "caps": when l["kind"] == "syn" and l["error"] == nothing then ceiling_of(l) otherwise "", "command": when l["kind"] == "exec" then l["command"] otherwise "", "tools": apply(l["tools"], (t) => t["name"]), "tool_specs": l["tools"], "dir": l["dir"], "channel": l["channel"] != nothing})
496
+ set out to append(out, {"name": l["name"], "scope": l["scope"], "kind": l["kind"], "legacy": l["legacy"], "description": l["description"], "enabled": l["enabled"], "error": l["error"], "caps": when l["kind"] == "syn" and l["error"] == nothing then ceiling_of(l) otherwise "", "command": when l["kind"] == "exec" then l["command"] otherwise "", "tools": apply(l["tools"], (t) => t["name"]), "tool_specs": l["tools"], "dir": l["dir"], "channel": l["channel"] != nothing, "example": l["example"]})
495
497
  give out
package/lib/provider.syn CHANGED
@@ -26,16 +26,18 @@ use "./settings.syn" as settings
26
26
 
27
27
  let ANTHROPIC_VERSION be "2023-06-01"
28
28
 
29
- -- Tabla base URL por proveedor
29
+ -- Tabla base URL por proveedor. Modelos por defecto revisados 2026-10-18 contra la doc de cada uno: el más
30
+ -- nuevo de uso general (no el más caro). deepseek-flash es el alias que DeepSeek mueve a su último Flash
31
+ -- (hoy V4.1-Flash-1017); kimi-k2-* se retiró el 2026-05-25; en Groq gpt-oss-120b es el que mejor usa tools.
30
32
  export let PRESETS be {
31
- "openai": {"wire": "openai", "base_url": "https://api.openai.com/v1", "model": "gpt-4o"},
32
- "deepseek": {"wire": "openai", "base_url": "https://api.deepseek.com/v1", "model": "deepseek-v4-flash"},
33
- "kimi": {"wire": "openai", "base_url": "https://api.moonshot.ai/v1", "model": "kimi-k2-0711-preview"},
34
- "groq": {"wire": "openai", "base_url": "https://api.groq.com/openai/v1", "model": "llama-3.3-70b-versatile"},
35
- "grok": {"wire": "openai", "base_url": "https://api.x.ai/v1", "model": "grok-3"},
36
- "openrouter": {"wire": "openai", "base_url": "https://openrouter.ai/api/v1", "model": "deepseek/deepseek-chat"},
37
- "ollama": {"wire": "openai", "base_url": "http://127.0.0.1:11434/v1", "model": "qwen2.5-coder"},
38
- "anthropic": {"wire": "anthropic", "base_url": "https://api.anthropic.com/v1", "model": "claude-sonnet-4-6"},
33
+ "openai": {"wire": "openai", "base_url": "https://api.openai.com/v1", "model": "gpt-6.1-sol"},
34
+ "deepseek": {"wire": "openai", "base_url": "https://api.deepseek.com/v1", "model": "deepseek-flash"},
35
+ "kimi": {"wire": "openai", "base_url": "https://api.moonshot.ai/v1", "model": "kimi-k3"},
36
+ "groq": {"wire": "openai", "base_url": "https://api.groq.com/openai/v1", "model": "openai/gpt-oss-120b"},
37
+ "grok": {"wire": "openai", "base_url": "https://api.x.ai/v1", "model": "grok-4.7"},
38
+ "openrouter": {"wire": "openai", "base_url": "https://openrouter.ai/api/v1", "model": "deepseek/deepseek-v4.1-flash"},
39
+ "ollama": {"wire": "openai", "base_url": "http://127.0.0.1:11434/v1", "model": "qwen3-coder"},
40
+ "anthropic": {"wire": "anthropic", "base_url": "https://api.anthropic.com/v1", "model": "claude-sonnet-5-5"},
39
41
  "minimax": {"wire": "anthropic", "base_url": "https://api.minimax.io/anthropic/v1", "model": "MiniMax-M3"},
40
42
  -- Z.ai (Zhipu), API compatible con OpenAI, dos presets con la MISMA key (es la misma cuenta):
41
43
  -- `glm` = pago por uso (saldo prepago); `glm-coding` = GLM Coding Plan (suscripción), que solo vale
@@ -284,12 +286,13 @@ export task supports_vision(cfg)
284
286
  give true
285
287
  when p == "groq"
286
288
  give contains(m, "llama-4") or contains(m, "vision")
289
+ -- DeepSeek V4.1-Flash (2026-09-10) es multimodal nativo; deepseek-v4-flash quedó como alias que va a él
287
290
  when p == "deepseek"
288
- give contains(m, "vision")
291
+ give contains(m, "vision") or contains(m, "flash")
289
292
  when p == "openai"
290
- give starts_with(m, "gpt-4o") or starts_with(m, "gpt-4.1") or starts_with(m, "gpt-5") or starts_with(m, "o1") or starts_with(m, "o3") or starts_with(m, "o4")
293
+ give starts_with(m, "gpt-4o") or starts_with(m, "gpt-4.1") or starts_with(m, "gpt-5") or starts_with(m, "gpt-6") or starts_with(m, "o1") or starts_with(m, "o3") or starts_with(m, "o4")
291
294
  when p == "openrouter" or p == "ollama"
292
- give contains(m, "vision") or contains(m, "vl") or contains(m, "gpt-4o") or contains(m, "gpt-5") or contains(m, "claude") or contains(m, "gemini") or contains(m, "llava") or contains(m, "pixtral") or contains(m, "qwen2.5vl") or contains(m, "qwen3-vl")
295
+ give contains(m, "vision") or contains(m, "vl") or contains(m, "gpt-4o") or contains(m, "gpt-5") or contains(m, "gpt-6") or contains(m, "claude") or contains(m, "gemini") or contains(m, "llava") or contains(m, "pixtral") or contains(m, "qwen2.5vl") or contains(m, "qwen3-vl")
293
296
  when p == "grok"
294
297
  give contains(m, "vision") or starts_with(m, "grok-4")
295
298
  when p == "kimi"
@@ -307,7 +310,7 @@ task image_note(m)
307
310
  each e in enumerate(m["images"])
308
311
  let im be e["item"]
309
312
  let dims be when contains(im, "w") then " " + text(floor(im["w"])) + "x" + text(floor(im["h"])) + "px" otherwise ""
310
- set notes to append(notes, "[Image " + text(e["index"] + 1) + dims + " attached, but this model does not accept image input — tell the user to switch to a vision model (e.g. anthropic or gpt-4o) if they need it read]")
313
+ set notes to append(notes, "[Image " + text(e["index"] + 1) + dims + " attached, but this model does not accept image input — tell the user to switch to a vision model (e.g. anthropic or gpt-6.1-sol) if they need it read]")
311
314
  give m["content"] + "\n" + join(notes, "\n")
312
315
 
313
316
  -- Handle textual junto a cada imagen (patrón de hermes/deepseek): el modelo sabe cuántas hay y de qué tamaño.
@@ -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)