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.
@@ -0,0 +1,549 @@
1
+ -- lib/apptools.syn — herramientas de una app escritas en Synsema: una carpeta, un archivo por herramienta
2
+ --
3
+ -- <proyecto>/.lampson/tools/ (o LAMPSON_TOOLS_DIR, relativa al proyecto: la opción `tools` del SDK)
4
+ -- README.md cuándo usarlas: va al prompt de los agentes que las tienen
5
+ -- estado_pedido.syn 1 archivo = 1 herramienta = `export task estado_pedido(…)`; el nombre del archivo es el
6
+ -- _comun.syn nombre de la tool. Los que empiezan con _ son ayudantes (`use "./_comun.syn"`), no tools
7
+ --
8
+ -- Del archivo sale todo, sin manifiesto (`synsema code outline --json`, sin ejecutarlo): la descripción es su
9
+ -- `intent:`, los parámetros los de la firma (un default la vuelve opcional), y su techo son sus `require` de arriba
10
+ -- — lo que el archivo no declara, Synsema se lo niega. `synsema test` corre sus `test`.
11
+ --
12
+ -- Una llamada = `synsema run -` con cwd = la carpeta de las tools: el archivo tal cual por stdin y, DEBAJO (así los
13
+ -- números de línea de un error son los del archivo), una línea que lee los argumentos y otra que llama a su task
14
+ -- con `call` (los permisos del programa = sus `require`; call_tool exigiría que el task los repita). No se escribe
15
+ -- nada en la carpeta del dev. Por qué así (2026-10-18, Synsema 0.6.44): un módulo importado con `use` no puede tener
16
+ -- `require` arriba, y `use` solo acepta rutas relativas al archivo que importa, dentro de su carpeta.
17
+ --
18
+ -- Techo del proceso (2026-10-19): `synsema run --no-env-file --cap-set <sus require>` — el .env de la carpeta no se
19
+ -- carga y lo que no está en los `require` de arriba del archivo lo niega el motor, aunque se escriba dentro de un
20
+ -- task. `env(…)` solo con nombres exactos, y nada que empiece con LAMPSON_ salvo LAMPSON_CTX: el proceso hijo hereda
21
+ -- el entorno de Lampson (las keys de los proveedores, el secreto del webhook) y `env("*")` lo leía entero.
22
+ --
23
+ -- Contexto de confianza: la herramienta que declara `require env("LAMPSON_CTX")` recibe ahí {from, thread, agent,
24
+ -- session, meta, channel} del sobre — lo pone la app, el modelo no lo ve ni lo escribe. Sus argumentos sí los escribe
25
+ -- el modelo: validarlos siempre.
26
+ --
27
+ -- Aprobación (2026-10-19): cada archivo de la carpeta (herramientas, ayudantes _*.syn y el README.md) corre o
28
+ -- entra al prompt solo si su sha256 es el que aprobó el humano: `lampson tools approve [nombre]`. Lo guardado vive
29
+ -- en .lampson/ del proceso del workspace, donde las tools de archivos del agente no llegan. Así, un agente que
30
+ -- reescribe una herramienta (por un alias de ruta, un bash disfrazado…) no le sube el techo: deja de correr hasta
31
+ -- que alguien mira el cambio. Con LAMPSON_APPROVE_TOOLS=1 (el SDK en modo local con approveTools: true: quien
32
+ -- edita es el dev) se aprueba solo.
33
+ --
34
+ -- Autorización: estar en la carpeta, aprobada, y en la lista de tools del agente. Pasan en cualquier modo;
35
+ -- "approve": "ask" en el agente las hace pedir, y una que declara `require spend(…)` pide siempre (runtime.opts_for).
36
+
37
+ export let MARK be "apptool"
38
+ let DEFAULT_DIR be ".lampson/tools"
39
+ let CACHE be ".lampson/apptools.json"
40
+ let APPROVED be ".lampson/apptools_approved.json"
41
+ let TIMEOUT be 60
42
+ let MAX_OUT be 60000
43
+ let MAX_README be 12000
44
+ -- el hash de toda la carpeta corre en cada escaneo (varias veces por turno): un .syn de 1 GB o un node_modules copiado
45
+ -- ahí harían lento cada turno de todos. Pasado el tope, las herramientas se frenan (no se cachea por fecha: con bash,
46
+ -- la fecha se vuelve atrás)
47
+ let MAX_FILE_BYTES be 1000000
48
+ let MAX_TOTAL_BYTES be 5000000
49
+ let MAX_FILES be 500
50
+ let MAX_ENTRIES be 5000
51
+ let MEMO_SECONDS be 3
52
+ -- nombres que ya usa Lampson: una herramienta del dev no puede pisarlos
53
+ export let TAKEN be ["read", "write", "edit", "ls", "find", "grep", "lsp", "fetch", "bash", "process", "memory", "todo", "skill", "mcp", "plugin", "schedule", "computer_use", "delegate", "send", "board", "objective"]
54
+
55
+ -- la carpeta, relativa al cwd del proceso (workspace/… es el proyecto). LAMPSON_TOOLS_DIR no puede salir del proyecto.
56
+ export task dir()
57
+ require env("LAMPSON_*")
58
+ let d be trim(replace(env("LAMPSON_TOOLS_DIR", ""), "\\", "/"))
59
+ when d == "" or starts_with(d, "/") or contains(d, ":") or contains(split(d, "/"), "..")
60
+ give "workspace/" + DEFAULT_DIR
61
+ while ends_with(d, "/")
62
+ set d to slice(d, 0, length(d) - 1)
63
+ give "workspace/" + d
64
+
65
+ task synsema_exe()
66
+ require env("LAMPSON_*")
67
+ give env("LAMPSON_SYNSEMA", "synsema")
68
+
69
+ -- un proceso con plazo → {code, out, err}; stdin opcional (texto que se manda y se cierra)
70
+ task run_proc(argv, cwd, envs, stdin_text, t)
71
+ require exec
72
+ require time
73
+ let p be proc_spawn(synsema_exe(), argv, {"cwd": cwd, "env": envs, "on_full": "drop_oldest"})
74
+ when stdin_text != nothing
75
+ proc_send(p, stdin_text)
76
+ proc_close_stdin(p)
77
+ let deadline be now() + t
78
+ let out be []
79
+ let errs be []
80
+ let code be nothing
81
+ let timed_out be false
82
+ while code == nothing and not timed_out
83
+ let left be deadline - now()
84
+ when left <= 0
85
+ set timed_out to true
86
+ otherwise
87
+ let ev be proc_recv(p, when left < 0.2 then 0.2 otherwise left)
88
+ when ev == nothing
89
+ set timed_out to now() >= deadline
90
+ otherwise when ev["type"] == "exit"
91
+ set code to ev["data"]["exit_code"]
92
+ otherwise when ev["type"] == "stderr"
93
+ set errs to append(errs, ev["data"])
94
+ otherwise
95
+ set out to append(out, ev["data"])
96
+ proc_close(p)
97
+ give {"code": code, "timed_out": timed_out, "out": join(out, "\n"), "err": join(errs, "\n")}
98
+
99
+ -- parámetros de la firma, leídos del archivo: "id, incluir_items = false" → [{name, optional, type}]
100
+ task signature(src, name)
101
+ let out be []
102
+ let m be regex_capture(src, "export\\s+task\\s+" + name + "\\s*\\(([^)]*)\\)")
103
+ when m == nothing
104
+ give out
105
+ each raw in split(m[0], ",")
106
+ let p be trim(raw)
107
+ when p != ""
108
+ let parts be split(p, "=")
109
+ let pn be trim(parts[0])
110
+ let dv be when length(parts) > 1 then trim(join(slice(parts, 1, length(parts)), "=")) otherwise ""
111
+ let ty be when dv == "true" or dv == "false" then "boolean" otherwise (when starts_with(dv, "\"") then "string" otherwise (when matches(dv, "-?[0-9]+(\\.[0-9]+)?") then "number" otherwise (when starts_with(dv, "[") then "array" otherwise (when starts_with(dv, "{") then "object" otherwise ""))))
112
+ set out to append(out, {"name": pn, "optional": length(parts) > 1, "type": ty})
113
+ give out
114
+
115
+ -- una entrada a partir de su archivo → {name, file, description, params, requires, ctx, spend, error}
116
+ task load_one(d, file)
117
+ require exec
118
+ require time
119
+ require file("workspace")
120
+ require file("workspace/*")
121
+ let name be slice(file, 0, length(file) - 4)
122
+ let e be {"name": name, "file": file, "description": "", "params": [], "requires": [], "ctx": false, "spend": false, "error": nothing}
123
+ when not matches(name, "[a-z][a-z0-9_]{0,39}")
124
+ set e["error"] to "the file name is the tool name: lowercase letters, digits and _ (max 40), starting with a letter"
125
+ give e
126
+ when contains(TAKEN, name) or starts_with(name, "plugin_") or starts_with(name, "mcp_")
127
+ set e["error"] to "'" + name + "' is a name Lampson already uses: rename the file"
128
+ give e
129
+ let r be run_proc(["code", "outline", file, "--json"], d, {}, nothing, 20)
130
+ let doc be json_decode(r["out"], nothing)
131
+ when doc == nothing or type_of(doc) != "map" or length(field_list(doc, "files")) == 0
132
+ set e["error"] to "synsema code outline failed: " + trim(r["err"] + " " + r["out"])
133
+ give e
134
+ let f be doc["files"][0]
135
+ when f["parse_error"] != nothing
136
+ set e["error"] to "does not parse (line " + text(f["parse_error"]["line"]) + "): " + text(f["parse_error"]["message"])
137
+ give e
138
+ let sym be where(field_list(f, "symbols"), (s) => s["kind"] == "task" and s["name"] == name)
139
+ when length(sym) == 0 or not sym[0]["exported"]
140
+ set e["error"] to "needs `export task " + name + "(…)` — the task with the file's name is the tool"
141
+ give e
142
+ when f["intent"] == nothing or trim(text(f["intent"])) == ""
143
+ set e["error"] to "needs an `intent: \"…\"` line: it is the description the model sees"
144
+ give e
145
+ set e["description"] to text(f["intent"])
146
+ set e["requires"] to apply((q) => {"cap": text(q["cap"]), "scope": when q["scope"] == nothing then "" otherwise text(q["scope"])}, field_list(f, "requires"))
147
+ each q in e["requires"]
148
+ when q["cap"] == "env" and (not matches(q["scope"], "[A-Za-z_][A-Za-z0-9_]*") or (starts_with(q["scope"], "LAMPSON_") and q["scope"] != "LAMPSON_CTX"))
149
+ set e["error"] to "require env(\"" + q["scope"] + "\"): name each variable exactly; LAMPSON_* is Lampson's own (only LAMPSON_CTX is for tools)"
150
+ give e
151
+ when contains(q["scope"], ",")
152
+ set e["error"] to "require " + q["cap"] + "(\"" + q["scope"] + "\"): a scope with a comma cannot be passed to the tool's ceiling"
153
+ give e
154
+ set e["ctx"] to length(where(e["requires"], (q) => q["cap"] == "env" and q["scope"] == "LAMPSON_CTX")) > 0
155
+ set e["spend"] to length(where(e["requires"], (q) => q["cap"] == "spend")) > 0
156
+ let src be ""
157
+ try
158
+ set src to read_file(d + "/" + file)
159
+ recover err
160
+ set src to ""
161
+ set e["params"] to signature(src, name)
162
+ give e
163
+
164
+ task field_list(m, k)
165
+ when type_of(m) == "map" and contains(m, k) and type_of(m[k]) == "list"
166
+ give m[k]
167
+ give []
168
+
169
+ task digest(path)
170
+ give decode(sha256(read_file(path)), "hex")
171
+
172
+ task approved_map()
173
+ try
174
+ let m be json_decode(read_file(APPROVED))
175
+ give when type_of(m) == "map" then m otherwise {}
176
+ recover err
177
+ give {}
178
+
179
+ -- un recorrido de la carpeta → {files, links, sizes, over}. files: TODA .syn de la carpeta y sus subcarpetas (una
180
+ -- herramienta puede `use "./sub/h.syn"` o `use "./otra.syn"`) y el README.md de arriba, que va al prompt; rutas
181
+ -- relativas a la carpeta. links: links a carpetas (junction, symlink): `use "./ext/o.syn"` los atraviesa (el chequeo
182
+ -- del motor es por el texto de la ruta) y list_dir no entra, así que lo de adentro nunca se aprobaría. list_dir los da
183
+ -- como archivo; file_info sigue el link y dice carpeta (Synsema 0.6.44 no tiene is_link). over: pasó el tope de
184
+ -- entradas o de .syn — se corta ahí, sin recorrer un node_modules entero en cada escaneo.
185
+ task walk(d)
186
+ let acc be walk_into(d, "", {"files": [], "links": [], "sizes": {}, "seen": 0, "over": false})
187
+ when file_exists(d + "/README.md")
188
+ set acc["files"] to append(acc["files"], "README.md")
189
+ set acc["sizes"]["README.md"] to file_info(d + "/README.md")["size"]
190
+ set acc["files"] to sort(acc["files"])
191
+ give acc
192
+
193
+ task walk_into(d, rel, acc)
194
+ try
195
+ each e in list_dir(d + (when rel == "" then "" otherwise "/" + rel))
196
+ when not acc["over"]
197
+ set acc["seen"] to acc["seen"] + 1
198
+ let p be when rel == "" then e["name"] otherwise rel + "/" + e["name"]
199
+ when acc["seen"] > MAX_ENTRIES or length(acc["files"]) > MAX_FILES
200
+ set acc["over"] to true
201
+ otherwise when e["is_dir"]
202
+ set acc to walk_into(d, p, acc)
203
+ otherwise
204
+ let fi be file_info(d + "/" + p)
205
+ when fi["is_dir"]
206
+ set acc["links"] to append(acc["links"], p)
207
+ otherwise when ends_with(e["name"], ".syn")
208
+ set acc["files"] to append(acc["files"], p)
209
+ set acc["sizes"][p] to when fi["size"] == nothing then 0 otherwise fi["size"]
210
+ recover err
211
+ give acc
212
+ give acc
213
+
214
+ task watched(d)
215
+ give walk(d)["files"]
216
+
217
+ -- {archivo: "ok" | "new" | "changed" | "unreadable" | "too_big" | "link" | "missing"}. Lo que no se puede leer (una
218
+ -- junction llamada x.syn, un archivo bloqueado) frena las herramientas pero no el resto: sin el try, tumbaba
219
+ -- registry_of de TODOS los agentes. "missing" (aprobado y borrado) solo se muestra: borrar no hace correr nada sin
220
+ -- aprobar (si vuelve con otro contenido, el hash guardado da "changed"). (approveTools del SDK aprueba UNA vez, al
221
+ -- arrancar `run --stdio`: lo que cambie después, aunque sea el agente, sigue el camino normal.)
222
+ --
223
+ -- Una vez por turno: el escaneo corre varias veces (registry_of, catalog_of, opts_for, missing), así que el
224
+ -- resultado se reusa unos segundos mientras la carpeta tenga los mismos archivos, tamaños y fechas. Pasado ese rato se
225
+ -- vuelve a leer todo; y `call` compara siempre el hash del archivo que va a correr.
226
+ export task approval()
227
+ require exec
228
+ require time
229
+ require file(".lampson")
230
+ require file(".lampson/*")
231
+ require file("workspace")
232
+ require file("workspace/*")
233
+ require env("LAMPSON_*")
234
+ let d be dir()
235
+ let w be walk(d)
236
+ let ok be approved_map()
237
+ let fp be json_encode([d, w["files"], w["links"], w["over"], apply((f) => text(file_info(d + "/" + f)["modified"]), w["files"]), w["sizes"], ok])
238
+ let key be "apptools:approval"
239
+ observe key as memo
240
+ when memo != nothing and memo["fp"] == fp and now() - memo["at"] < MEMO_SECONDS
241
+ give memo["st"]
242
+ let st be compute_approval(d, w, ok)
243
+ share {"fp": fp, "at": now(), "st": st} as key
244
+ give st
245
+
246
+ task compute_approval(d, w, ok)
247
+ when w["over"]
248
+ give {"(more than " + text(MAX_FILES) + " .syn or " + text(MAX_ENTRIES) + " entries)": "too_big"}
249
+ let total be 0
250
+ each f in w["files"]
251
+ set total to total + w["sizes"][f]
252
+ when total > MAX_TOTAL_BYTES
253
+ give {"(" + text(total) + " bytes in total)": "too_big"}
254
+ let out be {}
255
+ each f in w["files"]
256
+ try
257
+ when w["sizes"][f] > MAX_FILE_BYTES
258
+ raise("too big")
259
+ let h be digest(d + "/" + f)
260
+ set out[f] to when not contains(ok, f) then "new" otherwise (when ok[f] == h then "ok" otherwise "changed")
261
+ recover err
262
+ set out[f] to when contains(text(err), "too big") then "too_big" otherwise "unreadable"
263
+ each f in keys(ok)
264
+ when not contains(w["files"], f) and f != "README.md"
265
+ set out[f] to "missing"
266
+ each l in w["links"]
267
+ set out[l] to "link"
268
+ give out
269
+
270
+ -- aprobar lo que está ahora en la carpeta: un archivo (`estado_pedido` o `_comun.syn`) o, con "", todos → los que cambió
271
+ export task approve(name)
272
+ require file(".lampson")
273
+ require file(".lampson/*")
274
+ require file("workspace")
275
+ require file("workspace/*")
276
+ require env("LAMPSON_*")
277
+ let d be dir()
278
+ let ok be approved_map()
279
+ let done be []
280
+ let wk be walk(d)
281
+ when wk["over"]
282
+ give ["(the tools folder is over the limit: " + text(MAX_FILES) + " .syn or " + text(MAX_ENTRIES) + " entries; nothing approved)"]
283
+ let here be wk["files"]
284
+ -- los aprobados que ya no están (el dev los borró): fuera, con "" (aprobar todo) o nombrándolos
285
+ let kept be {}
286
+ each f in keys(ok)
287
+ when contains(here, f) or (name != "" and f != name and f != name + ".syn")
288
+ set kept[f] to ok[f]
289
+ otherwise
290
+ set done to append(done, f + " (removed)")
291
+ set ok to kept
292
+ each f in here
293
+ when name == "" or f == name or f == name + ".syn"
294
+ try
295
+ when file_info(d + "/" + f)["size"] > MAX_FILE_BYTES
296
+ raise("too big")
297
+ let h be digest(d + "/" + f)
298
+ when not contains(ok, f) or ok[f] != h
299
+ set ok[f] to h
300
+ set done to append(done, f)
301
+ recover err
302
+ set done to append(done, f + " (cannot be read: not approved)")
303
+ write_file(APPROVED, json_encode(ok))
304
+ give done
305
+
306
+ -- regla global: si CUALQUIER .syn de la carpeta no está aprobada, ninguna herramienta corre ("si algo cambió, nada
307
+ -- corre hasta que lo mires"): mirar qué importa cada una, transitivamente, es más código para un caso raro
308
+ task gate(e, st)
309
+ when e["error"] != nothing
310
+ give e
311
+ let bad be where(sort(keys(st)), (f) => st[f] != "ok" and st[f] != "missing" and f != "README.md")
312
+ when length(bad) > 0
313
+ let own be where(bad, (f) => f == e["file"])
314
+ let f be when length(own) > 0 then own[0] otherwise bad[0]
315
+ when st[f] == "too_big"
316
+ set e["error"] to (when starts_with(f, "(") then "the tools folder is over the limit " + f otherwise f + " is over " + text(MAX_FILE_BYTES) + " bytes") + " (limits: " + text(MAX_FILE_BYTES) + " bytes per file, " + text(MAX_TOTAL_BYTES) + " in total, " + text(MAX_FILES) + " .syn files): remove files from it (data, node_modules…) — approving does not help"
317
+ give e
318
+ when st[f] == "link"
319
+ set e["error"] to "links are not allowed in the tools folder: " + f + " (a `use` would run what is behind it, never approved). Replace it with the real files and run `lampson tools approve`"
320
+ give e
321
+ set e["error"] to (when f == e["file"] then f otherwise "the tools folder's " + f) + (when st[f] == "new" then " is not approved yet" otherwise (when st[f] == "unreadable" then " cannot be read (a link, or locked)" otherwise " changed since it was approved")) + ": review it and run `lampson tools approve " + (when f == e["file"] then e["name"] otherwise f) + "` (it can touch: " + ceiling(e) + ")"
322
+ give e
323
+
324
+ -- todas las herramientas de la carpeta, con la aprobación al día (también las rotas o sin aprobar, con su error).
325
+ -- Es la puerta de names/get/catalog: si algo de la carpeta falla de una forma que no vimos, es "no hay herramientas
326
+ -- .syn" y un aviso, nunca un error que llegue a registry_of y deje sin turno a todos los agentes.
327
+ export task scan()
328
+ require exec
329
+ require time
330
+ require file(".lampson")
331
+ require file(".lampson/*")
332
+ require file("workspace")
333
+ require file("workspace/*")
334
+ require env("LAMPSON_*")
335
+ try
336
+ let st be approval()
337
+ let out be apply((e) => gate(e, st), scan_files())
338
+ observe "apptools:error" as prev
339
+ when prev != nothing and prev != ""
340
+ share "" as "apptools:error"
341
+ give out
342
+ recover err
343
+ let msg be text(err)
344
+ observe "apptools:error" as prev
345
+ when prev != msg
346
+ eprint("lampson: app tools skipped (" + dir() + "): " + msg)
347
+ share msg as "apptools:error"
348
+ give []
349
+
350
+ -- todas las herramientas de la carpeta (también las rotas, con su error). Caché en disco por nombre+tamaño+fecha.
351
+ export task scan_files()
352
+ require exec
353
+ require time
354
+ require file(".lampson")
355
+ require file(".lampson/*")
356
+ require file("workspace")
357
+ require file("workspace/*")
358
+ require env("LAMPSON_*")
359
+ let d be dir()
360
+ let files be []
361
+ try
362
+ each e in list_dir(d)
363
+ when not e["is_dir"] and ends_with(e["name"], ".syn") and not starts_with(e["name"], "_")
364
+ set files to append(files, e["name"])
365
+ recover err
366
+ give []
367
+ when length(files) == 0
368
+ give []
369
+ set files to sort(files)
370
+ -- v2: load_one valida los env (2026-10-19); una caché vieja no los revisó
371
+ let sig be "v2|" + d
372
+ each fl in sort(apply((e) => e["name"], where(list_dir(d), (e) => not e["is_dir"])))
373
+ let fi be file_info(d + "/" + fl)
374
+ set sig to sig + "|" + fl + ":" + text(fi["size"]) + ":" + text(fi["modified"])
375
+ try
376
+ let c be json_decode(read_file(CACHE))
377
+ when c["sig"] == sig
378
+ give c["tools"]
379
+ recover err
380
+ set sig to sig
381
+ let out be apply((fl) => load_one(d, fl), files)
382
+ try
383
+ write_file(CACHE, json_encode({"sig": sig, "tools": out}))
384
+ recover err
385
+ set sig to sig
386
+ give out
387
+
388
+ -- para la UI (web.syn /api/apptools): cada archivo de la carpeta con su estado y, si es herramienta, qué hace y qué
389
+ -- puede tocar. Aprobar es de la persona (la ruta exige la sesión del dueño); el agente no tiene esta ruta.
390
+ export task summary()
391
+ require exec
392
+ require time
393
+ require file(".lampson")
394
+ require file(".lampson/*")
395
+ require file("workspace")
396
+ require file("workspace/*")
397
+ require env("LAMPSON_*")
398
+ let d be dir()
399
+ let st be {}
400
+ try
401
+ set st to approval()
402
+ recover err
403
+ give {"dir": d, "files": [], "error": text(err)}
404
+ let tools be {}
405
+ each e in scan_files()
406
+ set tools[e["file"]] to e
407
+ let out be []
408
+ each f in sort(keys(st))
409
+ let t be when contains(tools, f) then tools[f] otherwise nothing
410
+ set out to append(out, {"file": f, "status": st[f], "tool": when t == nothing then nothing otherwise {"name": t["name"], "description": t["description"], "ceiling": ceiling(t), "error": t["error"], "params": t["params"]}})
411
+ give {"dir": d, "files": out, "error": load_error()}
412
+
413
+ -- el texto de un archivo de la carpeta, para revisarlo antes de aprobar (solo los que la aprobación mira)
414
+ export task source(f)
415
+ require file(".lampson")
416
+ require file(".lampson/*")
417
+ require file("workspace")
418
+ require file("workspace/*")
419
+ require env("LAMPSON_*")
420
+ let d be dir()
421
+ when not contains(watched(d), f)
422
+ raise("not a file of the tools folder: " + f)
423
+ give slice(read_file(d + "/" + f), 0, MAX_FILE_BYTES)
424
+
425
+ -- por qué no se pudo leer la carpeta en el último escaneo ("" si se pudo): runtime.missing lo dice en vez de
426
+ -- «not a known tool»
427
+ export task load_error()
428
+ observe "apptools:error" as e
429
+ give when e == nothing then "" otherwise text(e)
430
+
431
+ export task names()
432
+ require exec
433
+ require time
434
+ require file(".lampson")
435
+ require file(".lampson/*")
436
+ require file("workspace")
437
+ require file("workspace/*")
438
+ require env("LAMPSON_*")
439
+ give apply((e) => e["name"], where(scan(), (e) => e["error"] == nothing))
440
+
441
+ export task get(name)
442
+ require exec
443
+ require time
444
+ require file(".lampson")
445
+ require file(".lampson/*")
446
+ require file("workspace")
447
+ require file("workspace/*")
448
+ require env("LAMPSON_*")
449
+ let f be where(scan(), (e) => e["name"] == name)
450
+ give when length(f) == 0 then nothing otherwise f[0]
451
+
452
+ -- el esquema que ve el modelo: sin tipos en la firma (Synsema 0.6.44 no los tiene), el tipo sale del default si hay
453
+ task schema(e)
454
+ let props be {}
455
+ let req be []
456
+ each p in e["params"]
457
+ set props[p["name"]] to when p["type"] != "" then {"type": p["type"]} otherwise {}
458
+ when not p["optional"]
459
+ set req to append(req, p["name"])
460
+ give {"type": "object", "properties": props, "required": req}
461
+
462
+ -- el techo del proceso: sus require + leer los argumentos + escribir la respuesta
463
+ task cap_set(e)
464
+ let caps be ["stdout", "env=LAMPSON_TOOL_ARGS"]
465
+ each q in e["requires"]
466
+ set caps to append(caps, q["cap"] + (when q["scope"] != "" then "=" + q["scope"] otherwise ""))
467
+ give join(caps, ",")
468
+
469
+ -- techo legible: "net(api.mitienda.com), env(LAMPSON_CTX)" — lo que puede tocar, para el catálogo y los avisos
470
+ export task ceiling(e)
471
+ when length(e["requires"]) == 0
472
+ give "nothing outside itself"
473
+ give join(apply((q) => q["cap"] + (when q["scope"] != "" then "(" + q["scope"] + ")" otherwise ""), e["requires"]), ", ")
474
+
475
+ export task catalog(allowed_names)
476
+ require exec
477
+ require time
478
+ require file(".lampson")
479
+ require file(".lampson/*")
480
+ require file("workspace")
481
+ require file("workspace/*")
482
+ require env("LAMPSON_*")
483
+ let out be []
484
+ each e in scan()
485
+ when e["error"] == nothing and contains(allowed_names, e["name"])
486
+ set out to append(out, {"name": e["name"], "description": e["description"], "parameters": schema(e)})
487
+ give out
488
+
489
+ -- el README de la carpeta, para el prompt de un agente que tiene alguna de estas tools
490
+ export task instructions(tool_names)
491
+ require exec
492
+ require time
493
+ require file(".lampson")
494
+ require file(".lampson/*")
495
+ require file("workspace")
496
+ require file("workspace/*")
497
+ require env("LAMPSON_*")
498
+ let mine be where(names(), (n) => contains(tool_names, n))
499
+ when length(mine) == 0
500
+ give ""
501
+ let st be {}
502
+ try
503
+ set st to approval()
504
+ recover err
505
+ give ""
506
+ when not contains(st, "README.md") or st["README.md"] != "ok"
507
+ give ""
508
+ try
509
+ let t be read_file(dir() + "/README.md")
510
+ give "\n\n# Your app's tools\n" + slice(t, 0, MAX_README)
511
+ recover err
512
+ give ""
513
+
514
+ -- ejecutar una: el archivo por stdin + leer args + llamar; cwd = la carpeta (sus file(...) son relativos a ella)
515
+ export task call(name, args, ctx)
516
+ require exec
517
+ require time
518
+ require file(".lampson")
519
+ require file(".lampson/*")
520
+ require file("workspace")
521
+ require file("workspace/*")
522
+ require env("LAMPSON_*")
523
+ let e be get(name)
524
+ when e == nothing
525
+ give "ERROR: no tool named '" + name + "'"
526
+ when e["error"] != nothing
527
+ give "ERROR: tool '" + name + "' is broken: " + e["error"]
528
+ let d be dir()
529
+ -- la aprobación de la carpeta otra vez, sin el memo de approval(): lo que corre no usa un resultado de hace 3 s
530
+ let raw be where(scan_files(), (x) => x["name"] == name)
531
+ when length(raw) > 0
532
+ let fresh be gate(raw[0], compute_approval(d, walk(d), approved_map()))
533
+ when fresh["error"] != nothing
534
+ give "ERROR: tool '" + name + "' is broken: " + fresh["error"]
535
+ let src be read_file(d + "/" + e["file"])
536
+ let okm be approved_map()
537
+ when not contains(okm, e["file"]) or okm[e["file"]] != decode(sha256(src), "hex")
538
+ give "ERROR: tool '" + name + "' changed since it was approved: run `lampson tools approve " + name + "`"
539
+ let prog be src + "\n\nrequire env(\"LAMPSON_TOOL_ARGS\")\nlet __lampson_r be call(" + name + ", json_decode(env(\"LAMPSON_TOOL_ARGS\")))\nprint(when type_of(__lampson_r) == \"text\" then __lampson_r otherwise json_encode(__lampson_r))\n"
540
+ let envs be {"LAMPSON_TOOL_ARGS": json_encode(when args == nothing then {} otherwise args)}
541
+ when e["ctx"]
542
+ set envs["LAMPSON_CTX"] to json_encode(when ctx == nothing then {} otherwise ctx)
543
+ let r be run_proc(["run", "--no-env-file", "--cap-set", cap_set(e), "-"], d, envs, prog, TIMEOUT)
544
+ let out be trim(r["out"] + (when trim(r["err"]) != "" then "\n" + r["err"] otherwise ""))
545
+ when r["timed_out"]
546
+ give "ERROR: tool '" + name + "' timed out after " + text(TIMEOUT) + "s (killed). Output so far:\n" + slice(out, 0, MAX_OUT)
547
+ when r["code"] != 0
548
+ give "ERROR: " + regex_replace(slice(out, 0, MAX_OUT), "<stdin>", e["file"])
549
+ give when out == "" then "(no output)" otherwise slice(out, 0, MAX_OUT)
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
@@ -361,6 +364,16 @@ task execute(tc, opts, on_event)
361
364
  -- tools de plugins: un proceso hijo por llamada (lib/plugins.syn)
362
365
  otherwise when registry[name] == "plugin"
363
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))
364
377
  -- equipos: send/board saben quién llama por opts.agent_id (el modelo no lo elige: se pisa lo que mande)
365
378
  otherwise when name == "send" or name == "board" or name == "objective"
366
379
  let targs be args