lampson 0.5.4 → 0.5.6

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/bin/lampson.js CHANGED
@@ -22,7 +22,7 @@ const home = process.env.LAMPSON_HOME || path.join(os.homedir(), 'lampson');
22
22
  const marker = path.join(home, '.npm-installed');
23
23
 
24
24
  // what gets copied into the home: the runtime, never state. Keep in sync with "files" in package.json.
25
- const CODE = ['lib', 'public', 'skills', 'chat.syn', 'run.syn', 'web.syn', 'hub.tpl.syn', 'edge.syn', 'cli.syn', 'lampson.ps1', 'lampson.sh', 'lampson.cmd', '.env.example', 'README.md', 'LICENSE'];
25
+ const CODE = ['lib', 'public', 'skills', 'chat.syn', 'run.syn', 'web.syn', 'hub.tpl.syn', 'edge.syn', 'cli.syn', 'synsema.json', 'lampson.ps1', 'lampson.sh', 'lampson.cmd', '.env.example', 'README.md', 'LICENSE'];
26
26
 
27
27
  // copia un archivo; en unix, los scripts de shell y los .syn salen con LF aunque el paquete se haya armado
28
28
  // en Windows (un CRLF en lampson.sh rompe bash: "set: pipefail\r: invalid option")
package/chat.syn CHANGED
@@ -474,7 +474,7 @@ task idle()
474
474
  let pending be false
475
475
  try
476
476
  each c in agents.list_children()
477
- when c["status"] != "running" and not c["delivered"]
477
+ when get(c, "parent", "") == sid and c["status"] != "running" and not c["delivered"]
478
478
  set pending to true
479
479
  recover err
480
480
  set pending to false
@@ -1056,7 +1056,7 @@ let running be true
1056
1056
  -- reinicia con input humano real (anti bucle auto-excitado, deepseek-harness)
1057
1057
  let followups be 0
1058
1058
  while running
1059
- let inbox be when followups < 3 then agents.parent_inbox(0, "") otherwise nothing
1059
+ let inbox be when followups < 3 then agents.parent_inbox(0, "", sid) otherwise nothing
1060
1060
  let line be nothing
1061
1061
  when inbox != nothing
1062
1062
  set followups to followups + 1
package/lampson.ps1 CHANGED
@@ -86,7 +86,7 @@ $Fixed = [version]((Get-Content (Join-Path $here "synsema.json") -Raw | ConvertF
86
86
  $engine = ((& synsema --version 2>$null) -replace '^\D*', '').Trim()
87
87
  if (-not ($engine -as [version])) { Write-Error "no pude leer la versión de synsema (tenés '$engine'): sin synsema en el PATH lampson no arranca"; exit 1 }
88
88
  if ([version]$engine -lt $Fixed) { Write-Error "lampson necesita synsema $Fixed o más nuevo (tenés '$engine'): synsema update"; exit 1 }
89
- if ([version]$engine -gt $Fixed) { Write-Error "tenés synsema $engine y lampson está validado hasta $Fixed: npm i -g synsema@$Fixed (o actualizá lampson al release que la valida)"; exit 1 }
89
+ if ([version]$engine -gt $Fixed) { Write-Error "tenés synsema $engine y lampson está validado hasta ${Fixed}: npm i -g synsema@$Fixed (o actualizá lampson al release que la valida)"; exit 1 }
90
90
 
91
91
  # skills externas globales (npx skills add -g → ~/.agents/skills; Claude Code → ~/.claude/skills), montadas bajo .lampson\
92
92
  # (una capability no puede apuntar a HOME); los workspaces las ven por su junction .lampson\global
package/lib/agents.syn CHANGED
@@ -61,13 +61,13 @@ export let PROFILES be {
61
61
  "addendum": "You are an EXPLORER: read-only. Locate the code relevant to the question (files, functions, line numbers) and report it concisely with paths and short excerpts. Do not propose changes."
62
62
  },
63
63
  "worker": {
64
- "tools": ["read", "write", "edit", "ls", "find", "grep", "lsp", "fetch", "bash", "process", "memory", "todo", "skill", "computer_use"],
64
+ "tools": ["read", "write", "edit", "ls", "find", "grep", "lsp", "fetch", "bash", "process", "memory", "todo", "skill"],
65
65
  "steps": 40,
66
66
  "addendum": "You are a WORKER sub-agent: implement exactly the scoped task you were given (read, edit, run tests), then report what you changed (files) and how you verified it. Stay inside the scope; if something outside it is needed, report it instead of doing it."
67
67
  }
68
68
  }
69
69
 
70
- let CHILD_NOTE be "\n\n# Sub-agent rules\n- You are a delegated sub-agent. Your permission scope was fixed when you started and you cannot ask the user: a denied action stays denied — do not retry it; state the limitation in your report so the delegating agent can handle it.\n- Your final message is your REPORT: concrete, with paths and line numbers (or test output) the parent can verify. No questions."
70
+ let CHILD_NOTE be "\n\n# Sub-agent rules\n- Computer use is reserved for the main agent. If your task needs it, report that requirement to your parent; do not try to bypass the restriction.\n- You are a delegated sub-agent. Your permission scope was fixed when you started and you cannot ask the user: a denied action stays denied — do not retry it; state the limitation in your report so the delegating agent can handle it.\n- Your final message is your REPORT: concrete, with paths and line numbers (or test output) the parent can verify. No questions."
71
71
 
72
72
  -- perfiles que el usuario puede elegir (selector web, /agent). `worker` es interno: el perfil de los
73
73
  -- subagentes que `build` lanza con delegate (sin delegate ni mcp para que un hijo no delegue a su vez).
@@ -94,7 +94,7 @@ export task addendum_for(name)
94
94
  task mcp_readonly_only(name)
95
95
  give not (name == "build" or name == "worker")
96
96
 
97
- -- tools del perfil que entran de verdad: computer_use está en build/worker pero solo cuando el usuario la
97
+ -- tools del perfil que entran de verdad: computer_use está en build pero solo cuando el usuario la
98
98
  -- encendió y el driver existe (lib/computer.syn) — si no, el modelo ni la ve
99
99
  export task tool_names(p)
100
100
  require exec
@@ -227,12 +227,12 @@ export task child_inbox(step, tag)
227
227
  give nothing
228
228
 
229
229
  -- buzón del padre: hijos en background terminados y no entregados
230
- export task parent_inbox(step, tag)
230
+ export task parent_inbox(step, tag, parent = nothing)
231
231
  require file(".lampson")
232
232
  require file(".lampson/**")
233
233
  let msgs be []
234
234
  each c in list_children()
235
- when c["status"] != "running" and not c["delivered"]
235
+ when get(c, "parent", "") == (when parent == nothing then "" otherwise parent) and c["status"] != "running" and not c["delivered"]
236
236
  set msgs to append(msgs, notice_text(c))
237
237
  let m be read_json(c["id"])
238
238
  set m["delivered"] to true
@@ -241,6 +241,23 @@ export task parent_inbox(step, tag)
241
241
  give {"messages": msgs, "stop": false}
242
242
  give nothing
243
243
 
244
+ -- El padre web puede terminar su trabajo independiente antes que sus hijos. El harness espera aquí,
245
+ -- sin llamadas al modelo, y entrega cada informe en el mismo turno y bajo su presupuesto original.
246
+ export task wait_parent_inbox(step, tag, parent, timeout)
247
+ require time
248
+ require file(".lampson")
249
+ require file(".lampson/**")
250
+ let deadline be now() + timeout
251
+ while true
252
+ let inbox be parent_inbox(step, tag, parent)
253
+ when inbox != nothing
254
+ give inbox
255
+ let pending be where(list_children(), (c) => get(c, "parent", "") == parent and c["status"] == "running" and not c["delivered"])
256
+ when length(pending) == 0 or now() >= deadline
257
+ -- Puede haber terminado entre las dos lecturas: recogerlo antes de cerrar el turno.
258
+ give parent_inbox(step, tag, parent)
259
+ sleep(0.25)
260
+
244
261
  export task notice_text(c)
245
262
  give "[harness] Sub-agent " + c["id"] + " (" + c["agent"] + ") finished: " + c["status"] + " · " + text(c["steps"]) + " steps · " + text(c["tokens"]) + " tokens.\nTask: " + one_line(c["brief"], 200) + "\nReport (self-report — verify before relying on it):\n" + c["text"]
246
263
 
@@ -274,7 +291,7 @@ export task prune(keep, max_age_s)
274
291
  require file(".lampson")
275
292
  require file(".lampson/**")
276
293
  -- un "running" de hace más de 6 h es un fantasma (lampson cerrado con el hijo vivo, o un crash viejo)
277
- let finished be where(list_children(), (c) => c["status"] != "running" or now() - c["started"] > 21600)
294
+ let finished be where(list_children(), (c) => (c["status"] != "running" and c["delivered"]) or now() - c["started"] > 21600)
278
295
  let victims be []
279
296
  let n be length(finished)
280
297
  let i be 0
@@ -327,13 +344,13 @@ export task run_child(spec)
327
344
  let agent be spec["agent"]
328
345
  let p be PROFILES[agent]
329
346
  let cfg be provider.config()
330
- write_json(id, {"id": id, "agent": agent, "brief": spec["brief"], "status": "running", "steps": 0, "tokens": 0, "started": spec["started"], "finished": nothing, "delivered": not spec["background"], "text": "", "background": spec["background"]})
347
+ write_json(id, {"id": id, "parent": get(spec, "parent", ""), "agent": agent, "brief": spec["brief"], "status": "running", "steps": 0, "tokens": 0, "started": spec["started"], "finished": nothing, "delivered": not spec["background"], "text": "", "background": spec["background"]})
331
348
  write_file(path(id, "log"), "# sub-agent " + id + " (" + agent + ")\n# " + one_line(spec["brief"], 300) + "\n")
332
349
  -- TODO lo que puede fallar va dentro del try: si algo revienta (prompt, provider, loop) el hijo queda
333
350
  -- en status "error" y no como un "running" fantasma (pasó 2026-08-28 con un prompt.syn roto)
334
351
  let result be nothing
335
352
  try
336
- let system be {"role": "system", "content": prompt.build(env_info(cfg), p["addendum"] + CHILD_NOTE)}
353
+ let system be {"role": "system", "content": prompt.build(env_info(cfg), p["addendum"] + CHILD_NOTE, false)}
337
354
  let full_brief be when spec["context"] == nothing or spec["context"] == "" then spec["brief"] otherwise spec["brief"] + "\n\nContext from the delegating agent:\n" + spec["context"]
338
355
  let messages be [system, {"role": "user", "content": full_brief}]
339
356
  let opts be loop.default_opts(tools.registry_subset(tool_names(p)), tools.catalog_subset(tool_names(p)), nothing)
@@ -346,7 +363,7 @@ export task run_child(spec)
346
363
  set result to {"text": "(the sub-agent crashed: " + one_line(err, 300) + ")", "steps": 0, "usage": {"input": 0, "output": 0}, "stopped": "error"}
347
364
  let status be when result["stopped"] == "done" then "done" otherwise result["stopped"]
348
365
  let tokens be result["usage"]["input"] + result["usage"]["output"]
349
- let final be {"id": id, "agent": agent, "brief": spec["brief"], "status": status, "steps": result["steps"], "tokens": tokens, "started": spec["started"], "finished": now(), "delivered": not spec["background"], "text": when result["text"] == "" then "(the sub-agent produced no final text)" otherwise result["text"], "background": spec["background"]}
366
+ let final be {"id": id, "parent": get(spec, "parent", ""), "agent": agent, "brief": spec["brief"], "status": status, "steps": result["steps"], "tokens": tokens, "started": spec["started"], "finished": now(), "delivered": not spec["background"], "text": when result["text"] == "" then "(the sub-agent produced no final text)" otherwise result["text"], "background": spec["background"]}
350
367
  write_json(id, final)
351
368
  append_file(path(id, "log"), "# finished: " + status + " · " + text(result["steps"]) + " steps · " + text(tokens) + " tokens\n")
352
369
  bus_publish("subagent.done", {"id": id, "status": status})
@@ -407,7 +424,7 @@ task new_id(agent, i)
407
424
 
408
425
  -- ---------- delegate (tool) ----------
409
426
 
410
- export task delegate(agent, brief, context, tasks, background, action, id, message)
427
+ export task delegate(agent, brief, context, tasks, background, action, id, message, _parent)
411
428
  require net
412
429
  require net("0.0.0.0/0")
413
430
  require net("::/0")
@@ -464,11 +481,11 @@ export task delegate(agent, brief, context, tasks, background, action, id, messa
464
481
  raise("cannot delegate to 'build' (a child never gets `delegate`): use worker for scoped implementation, or explore/plan/review")
465
482
  when not contains(t, "brief") or trim(text(t["brief"])) == ""
466
483
  raise("every task needs a brief")
467
- set specs to append(specs, {"id": new_id(a, i), "agent": a, "brief": text(t["brief"]), "context": when contains(t, "context") then text(t["context"]) otherwise "", "mode": child_mode(), "background": background == true, "started": now()})
484
+ set specs to append(specs, {"id": new_id(a, i), "parent": when _parent == nothing then "" otherwise _parent, "agent": a, "brief": text(t["brief"]), "context": when contains(t, "context") then text(t["context"]) otherwise "", "mode": child_mode(), "background": background == true, "started": now()})
468
485
  when background == true
469
486
  let lines be []
470
487
  each sp in specs
471
- write_json(sp["id"], {"id": sp["id"], "agent": sp["agent"], "brief": sp["brief"], "status": "running", "steps": 0, "tokens": 0, "started": sp["started"], "finished": nothing, "delivered": false, "text": "", "background": true})
488
+ write_json(sp["id"], {"id": sp["id"], "parent": sp["parent"], "agent": sp["agent"], "brief": sp["brief"], "status": "running", "steps": 0, "tokens": 0, "started": sp["started"], "finished": nothing, "delivered": false, "text": "", "background": true})
472
489
  write_file(path(sp["id"], "log"), "# starting…\n")
473
490
  spawn Child with spec_json = json_encode(sp)
474
491
  bus_publish("subagent.started", {"id": sp["id"], "agent": sp["agent"]})
@@ -482,7 +499,7 @@ export task delegate(agent, brief, context, tasks, background, action, id, messa
482
499
 
483
500
  export let DELEGATE_SPEC be {
484
501
  "name": "delegate",
485
- "description": "Run sub-agents: each gets its own fresh context, a restricted toolset and returns only its final report (it does not see your conversation — give it a self-contained brief). Agents: `explore` (read-only; find where things are), `plan` (read-only; implementation plan), `review` (read-only files, can run tests/commands; find bugs), `worker` (can edit files and run commands: a scoped implementation task). Several tasks in one call run IN PARALLEL and come back consolidated — use that for independent questions or independent changes in different files. background=true returns immediately with ids; each report arrives later as a message in your context (do not poll). action=list|steer|stop|result manages background sub-agents (steer sends a message the child reads before its next step; stop returns its partial report). Reports are SELF-REPORTS: verify what matters (read the file, run the test) before telling the user it is done. Sub-agents cannot ask the user and cannot delegate.",
502
+ "description": "Run sub-agents: each gets its own fresh context, a restricted toolset and returns only its final report (it does not see your conversation — give it a self-contained brief). Agents: `explore` (read-only; find where things are), `plan` (read-only; implementation plan), `review` (read-only files, can run tests/commands; find bugs), `worker` (can edit files and run commands: a scoped implementation task). Several tasks in one call run IN PARALLEL and come back consolidated — use that for independent questions or independent changes in different files. background=true returns immediately with ids; each report arrives later as a message in your context (do not poll). action=list|steer|stop|result manages background sub-agents (steer sends a message the child reads before its next step; stop returns its partial report). Reports are SELF-REPORTS: verify what matters (read the file, run the test) before telling the user it is done. Sub-agents cannot ask the user, cannot delegate and cannot use computer_use. Keep desktop and browser tasks that require computer_use in the main agent; delegate only work the child can complete with its available tools.",
486
503
  "parameters": {"type": "object", "properties": {
487
504
  "tasks": {"type": "array", "description": "Batch: [{agent, brief, context?}] — they run in parallel (max 6)", "items": {"type": "object", "properties": {
488
505
  "agent": {"type": "string", "enum": ["explore", "plan", "review", "worker"]},
package/lib/approvals.syn CHANGED
@@ -114,13 +114,16 @@ task notify(meta, links)
114
114
  give false
115
115
 
116
116
  -- espera (polling) hasta que alguien responda o venza el plazo. Devuelve true/false; sin respuesta = false.
117
- export task wait(id, timeout_s)
117
+ export task wait(id, timeout_s, cancel_fn = nothing)
118
118
  require time
119
119
  let deadline be now() + timeout_s
120
120
  let answer be nothing
121
121
  while answer == nothing and now() < deadline
122
122
  observe "approval:answer:" + id as a
123
123
  set answer to a
124
+ when answer == nothing and cancel_fn != nothing
125
+ when call(cancel_fn, {})
126
+ set answer to "no"
124
127
  when answer == nothing
125
128
  sleep(0.5)
126
129
  let meta be meta_of(id)
package/lib/loop.syn CHANGED
@@ -13,6 +13,8 @@
13
13
  -- al modelo. Es el buzón: al padre le trae los avisos de subagentes terminados; al hijo, los
14
14
  -- `steer` del padre y la orden de `stop` (que corta el turno devolviendo lo parcial).
15
15
  -- Los avisos entran como mensajes `user` nuevos, nunca se muta el contexto pasado (cache intacto).
16
+ -- control_fn : input humano entre herramientas. Un mensaje normal no cancela las llamadas ya solicitadas;
17
+ -- solo stop omite las restantes. Los mensajes entran tras cerrar el lote de resultados.
16
18
  --
17
19
  -- Garantías (las mismas que documenta llm.md de Synsema):
18
20
  -- * Solo se ejecutan tools del allow-list (registry). Un nombre alucinado → error devuelto al modelo.
@@ -369,6 +371,11 @@ task execute(tc, opts, on_event)
369
371
  -- (salvo que haya dicho «solo esta vez»)
370
372
  when grant and not once
371
373
  worktree.grant_integration(seat)
374
+ -- Una aprobación puede haber esperado al humano: comprobar de nuevo antes de iniciar la operación.
375
+ let stop_pending_fn be get(opts, "stop_pending_fn", nothing)
376
+ when stop_pending_fn != nothing
377
+ when call(stop_pending_fn, {})
378
+ give "NOT RUN: stop was requested before this operation started."
372
379
  emit(on_event, "busy", {"label": permission.describe_call(name, args), "kind": "tool", "name": name}, tag)
373
380
  -- su copia: las tools de archivos y bash operan ahí; los paths que ve el modelo son relativos a ella
374
381
  when wroot != "" and (name == "bash" or name == "process" or contains(worktree.FILE_TOOLS, name))
@@ -391,6 +398,11 @@ task execute(tc, opts, on_event)
391
398
  -- funciones de la app en modo servidor (lib/remotetools.syn): POST firmado a tools_url, bajo sandbox under
392
399
  otherwise when registry[name] == remotetools.MARK
393
400
  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))
401
+ -- La sesión padre es contexto de confianza; el modelo no puede elegir otro destinatario del informe.
402
+ otherwise when name == "delegate"
403
+ let dargs be args
404
+ set dargs["_parent"] to get(opts, "parent_session", "")
405
+ set out to text(call_tool(registry[name], dargs))
394
406
  -- equipos: send/board saben quién llama por opts.agent_id (el modelo no lo elige: se pisa lo que mande)
395
407
  otherwise when name == "send" or name == "board" or name == "objective"
396
408
  let targs be args
@@ -406,6 +418,17 @@ task execute(tc, opts, on_event)
406
418
  set out to replace(out, wroot + "/", "")
407
419
  give out
408
420
 
421
+ -- El buzón admite avisos de texto y mensajes de usuario con imágenes, sin mutar contexto anterior.
422
+ task add_inbox(msgs, incoming, on_event, tag)
423
+ let out be msgs
424
+ each m in incoming["messages"]
425
+ when type_of(m) == "map"
426
+ set out to append(out, {"role": "user", "content": m["content"], "images": get(m, "images", [])})
427
+ otherwise
428
+ emit(on_event, "inbox", m, tag)
429
+ set out to append(out, {"role": "user", "content": m})
430
+ give out
431
+
409
432
  export task run_turn(cfg, messages, opts, on_event)
410
433
  require net
411
434
  require net("0.0.0.0/0")
@@ -454,11 +477,9 @@ export task run_turn(cfg, messages, opts, on_event)
454
477
  when opts["inbox_fn"] != nothing
455
478
  let inb be call(opts["inbox_fn"], {"step": steps, "tag": tag})
456
479
  when inb != nothing
457
- each m in inb["messages"]
458
- emit(on_event, "inbox", m, tag)
459
- set msgs to append(msgs, {"role": "user", "content": m})
480
+ set msgs to add_inbox(msgs, inb, on_event, tag)
460
481
  when inb["stop"]
461
- emit(on_event, "error", "stopped by the parent agent", tag)
482
+ emit(on_event, "inbox", "detenido al terminar la operación en curso", tag)
462
483
  give {"messages": msgs, "text": final_text, "steps": steps, "usage": usage, "stopped": "stopped"}
463
484
  -- último paso: sin tools + instrucción explícita → respuesta final (truco de llm.md: catálogo vacío)
464
485
  -- presupuesto de tokens (visto 2026-08-28: 16 pasos leyendo 30 archivos, 420k tokens, 0 ediciones):
@@ -510,71 +531,97 @@ export task run_turn(cfg, messages, opts, on_event)
510
531
  when r["reasoning"] != ""
511
532
  set assistant["reasoning"] to r["reasoning"]
512
533
  set msgs to append(msgs, assistant)
513
- when clean_text != ""
534
+ when clean_text != "" and length(calls) > 0
514
535
  emit(on_event, "assistant", clean_text, tag)
515
536
  -- buzón de conversación (opts.inbox_final): si mientras el modelo escribía la respuesta llegaron mensajes
516
537
  -- nuevos, esa respuesta ya está vieja (visto 2026-10-16: «soy Lucía» llegó a mitad de turno y salió «decime
517
538
  -- tu nombre»). Se descarta el borrador, entran los mensajes y el modelo responde de nuevo — un paso más.
518
539
  let late be nothing
519
540
  when length(calls) == 0 and not last_step and contains(opts, "inbox_final") and opts["inbox_final"] == true and opts["inbox_fn"] != nothing
520
- set late to call(opts["inbox_fn"], {"step": steps, "tag": tag})
521
- when late != nothing and length(late["messages"]) > 0
541
+ let final_inbox be get(opts, "final_inbox_fn", opts["inbox_fn"])
542
+ set late to call(final_inbox, {"step": steps, "tag": tag})
543
+ when late != nothing and late["stop"]
544
+ set msgs to slice(msgs, 0, length(msgs) - 1)
545
+ set msgs to add_inbox(msgs, late, on_event, tag)
546
+ give {"messages": msgs, "text": "", "steps": steps, "usage": usage, "stopped": "stopped"}
547
+ otherwise when late != nothing and length(late["messages"]) > 0
522
548
  set msgs to slice(msgs, 0, length(msgs) - 1)
523
549
  emit(on_event, "inbox", "llegaron mensajes mientras respondía: rehago la respuesta", tag)
524
- each m in late["messages"]
525
- emit(on_event, "inbox", m, tag)
526
- set msgs to append(msgs, {"role": "user", "content": m})
550
+ set msgs to add_inbox(msgs, late, on_event, tag)
527
551
  otherwise when length(calls) == 0
552
+ when clean_text != ""
553
+ emit(on_event, "assistant", clean_text, tag)
528
554
  set final_text to clean_text
529
555
  give {"messages": msgs, "text": final_text, "steps": steps, "usage": usage, "stopped": when over_budget then "budget" otherwise (when last_step then "max_steps" otherwise "done")}
556
+ let steering be nothing
530
557
  each tc in calls
531
- emit(on_event, "tool_call", tc, tag)
532
- -- repetición: misma tool + mismos args (JSON canónico); 3 y 5 → recordatorio en el resultado; 8 → rechazo
533
- let sig be tc["name"] + " " + canon(tc["args"])
534
- set repeats to when sig == last_sig then repeats + 1 otherwise 1
535
- set last_sig to sig
536
- let out be ""
537
- let ex be explore_verdict(explore_streak, tc["name"], cap)
538
- set explore_streak to ex["streak"]
539
- when repeats >= REPEAT_HARD
540
- set out to "ERROR: you already called " + tc["name"] + " with these exact arguments " + text(repeats) + " times in a row. The result will not change; try a different approach or report the problem."
541
- emit(on_event, "tool_denied", {"call": tc, "reason": "repeated call (" + text(repeats) + "x)"}, tag)
542
- otherwise when ex["refuse"]
543
- set out to "ERROR: exploration cap reached — " + text(explore_streak) + " read-only calls in a row (read/ls/find/grep) without a single change. Reading more will not help. Do one of: (1) edit/write the files you already read; (2) run a command (bash/process) that moves the task; (3) delegate ONE focused question to an `explore` sub-agent; (4) tell the user what you need. read/ls/find/grep/fetch are refused until you do."
544
- emit(on_event, "tool_denied", {"call": tc, "reason": "exploration cap (" + text(explore_streak) + " read-only calls without acting)"}, tag)
545
- otherwise when contains(READ_ONLY_TOOLS, tc["name"]) and reads_total >= turn_cap
546
- set out to "ERROR: this turn already made " + text(reads_total) + " read-only calls (limit " + text(turn_cap) + "). Everything you read is in your context. Act on it now (edit/write/run), delegate ONE focused question to an `explore` sub-agent, or report to the user."
547
- emit(on_event, "tool_denied", {"call": tc, "reason": "read-only calls per turn (" + text(reads_total) + ")"}, tag)
548
- otherwise
549
- set out to spill(tc["name"], safe_id(tc["id"], steps), execute(tc, opts, on_event))
550
- when contains(READ_ONLY_TOOLS, tc["name"])
551
- set reads_total to reads_total + 1
552
- let rk be tc["name"] + " " + canon(tc["args"])
553
- let h be decode(sha256(out), "hex")
554
- when contains(seen_reads, rk) and seen_reads[rk]["hash"] == h and not starts_with(out, "ERROR")
555
- set out to "[unchanged: identical to your " + tc["name"] + " at step " + text(seen_reads[rk]["step"]) + " this turn — the content is already in your context above; do not re-read files you already have]"
556
- emit(on_event, "inbox", "lectura repetida (" + tc["name"] + " " + one_line_args(tc["args"]) + "): recibo en vez de re-enviar el contenido", tag)
558
+ -- Recoger input sin descartar el plan existente. Solo Detener cancela acciones pendientes.
559
+ let halted be when steering == nothing then false otherwise steering["stop"]
560
+ when not halted and get(opts, "control_fn", nothing) != nothing
561
+ let incoming be call(opts["control_fn"], {"step": steps, "tag": tag})
562
+ when incoming != nothing
563
+ when steering == nothing
564
+ set steering to incoming
557
565
  otherwise
558
- set seen_reads[rk] to {"hash": h, "step": steps}
559
- when contains(REPEAT_TIERS, repeats)
560
- set out to out + repeat_note(tc, repeats)
561
- when ex["note"] != ""
562
- set out to out + ex["note"]
563
- emit(on_event, "inbox", "tope de exploración a la mitad (" + text(explore_streak) + "/" + text(cap) + " lecturas seguidas sin actuar): aviso al modelo", tag)
564
- -- solo cuentan los errores REALES de la tool; los rechazos del harness (tope de lecturas,
565
- -- repeticiones) ya castigan con el rechazo y no deben además cortar el turno
566
- when (starts_with(out, "ERROR") or starts_with(out, "DENIED")) and not starts_with(out, "ERROR: exploration cap") and not starts_with(out, "ERROR: this turn already made") and not starts_with(out, "ERROR: you already called")
567
- set errors to errors + 1
568
- emit(on_event, "tool_result", {"call": tc, "output": out}, tag)
569
- set msgs to append(msgs, tool_result_msg(tc, out))
570
- -- captura de pantalla pendiente (computer_use): adjunta como imagen si el proveedor tiene visión
571
- observe "computer:screenshot" as shot
572
- when shot != nothing
573
- share nothing as "computer:screenshot"
574
- when provider.supports_vision(cfg)
575
- set msgs to drop_old_screenshots(msgs)
576
- set msgs to append(msgs, {"role": "user", "content": SHOT_PREFIX + shot["label"] + ". Look at it, then continue the task.", "images": shot["images"]})
577
- emit(on_event, "inbox", "captura de pantalla adjunta al modelo (" + shot["label"] + ")", tag)
566
+ set steering to {"messages": steering["messages"] + incoming["messages"], "stop": incoming["stop"]}
567
+ let stop_requested be when steering == nothing then false otherwise steering["stop"]
568
+ when stop_requested
569
+ let skipped be "NOT RUN: the user requested Stop before this tool started."
570
+ emit(on_event, "tool_skipped", {"call": tc, "reason": skipped}, tag)
571
+ set msgs to append(msgs, tool_result_msg(tc, skipped))
572
+ otherwise
573
+ emit(on_event, "tool_call", tc, tag)
574
+ -- repetición: misma tool + mismos args (JSON canónico); 3 y 5 → recordatorio en el resultado; 8 → rechazo
575
+ let sig be tc["name"] + " " + canon(tc["args"])
576
+ set repeats to when sig == last_sig then repeats + 1 otherwise 1
577
+ set last_sig to sig
578
+ let out be ""
579
+ let ex be explore_verdict(explore_streak, tc["name"], cap)
580
+ set explore_streak to ex["streak"]
581
+ when repeats >= REPEAT_HARD
582
+ set out to "ERROR: you already called " + tc["name"] + " with these exact arguments " + text(repeats) + " times in a row. The result will not change; try a different approach or report the problem."
583
+ emit(on_event, "tool_denied", {"call": tc, "reason": "repeated call (" + text(repeats) + "x)"}, tag)
584
+ otherwise when ex["refuse"]
585
+ set out to "ERROR: exploration cap reached — " + text(explore_streak) + " read-only calls in a row (read/ls/find/grep) without a single change. Reading more will not help. Do one of: (1) edit/write the files you already read; (2) run a command (bash/process) that moves the task; (3) delegate ONE focused question to an `explore` sub-agent; (4) tell the user what you need. read/ls/find/grep/fetch are refused until you do."
586
+ emit(on_event, "tool_denied", {"call": tc, "reason": "exploration cap (" + text(explore_streak) + " read-only calls without acting)"}, tag)
587
+ otherwise when contains(READ_ONLY_TOOLS, tc["name"]) and reads_total >= turn_cap
588
+ set out to "ERROR: this turn already made " + text(reads_total) + " read-only calls (limit " + text(turn_cap) + "). Everything you read is in your context. Act on it now (edit/write/run), delegate ONE focused question to an `explore` sub-agent, or report to the user."
589
+ emit(on_event, "tool_denied", {"call": tc, "reason": "read-only calls per turn (" + text(reads_total) + ")"}, tag)
590
+ otherwise
591
+ set out to spill(tc["name"], safe_id(tc["id"], steps), execute(tc, opts, on_event))
592
+ when contains(READ_ONLY_TOOLS, tc["name"])
593
+ set reads_total to reads_total + 1
594
+ let rk be tc["name"] + " " + canon(tc["args"])
595
+ let h be decode(sha256(out), "hex")
596
+ when contains(seen_reads, rk) and seen_reads[rk]["hash"] == h and not starts_with(out, "ERROR")
597
+ set out to "[unchanged: identical to your " + tc["name"] + " at step " + text(seen_reads[rk]["step"]) + " this turn — the content is already in your context above; do not re-read files you already have]"
598
+ emit(on_event, "inbox", "lectura repetida (" + tc["name"] + " " + one_line_args(tc["args"]) + "): recibo en vez de re-enviar el contenido", tag)
599
+ otherwise
600
+ set seen_reads[rk] to {"hash": h, "step": steps}
601
+ when contains(REPEAT_TIERS, repeats)
602
+ set out to out + repeat_note(tc, repeats)
603
+ when ex["note"] != ""
604
+ set out to out + ex["note"]
605
+ emit(on_event, "inbox", "tope de exploración a la mitad (" + text(explore_streak) + "/" + text(cap) + " lecturas seguidas sin actuar): aviso al modelo", tag)
606
+ -- solo cuentan los errores REALES de la tool; los rechazos del harness (tope de lecturas,
607
+ -- repeticiones) ya castigan con el rechazo y no deben además cortar el turno
608
+ when (starts_with(out, "ERROR") or starts_with(out, "DENIED")) and not starts_with(out, "ERROR: exploration cap") and not starts_with(out, "ERROR: this turn already made") and not starts_with(out, "ERROR: you already called")
609
+ set errors to errors + 1
610
+ emit(on_event, "tool_result", {"call": tc, "output": out}, tag)
611
+ set msgs to append(msgs, tool_result_msg(tc, out))
612
+ -- captura de pantalla pendiente (computer_use): adjunta como imagen si el proveedor tiene visión
613
+ observe "computer:screenshot" as shot
614
+ when shot != nothing
615
+ share nothing as "computer:screenshot"
616
+ when provider.supports_vision(cfg)
617
+ set msgs to drop_old_screenshots(msgs)
618
+ set msgs to append(msgs, {"role": "user", "content": SHOT_PREFIX + shot["label"] + ". Look at it, then continue the task.", "images": shot["images"]})
619
+ emit(on_event, "inbox", "captura de pantalla adjunta al modelo (" + shot["label"] + ")", tag)
620
+ when steering != nothing
621
+ -- Cada tool_call conserva su resultado (también las omitidas); después entra el mensaje del usuario.
622
+ set msgs to add_inbox(msgs, steering, on_event, tag)
623
+ when steering["stop"]
624
+ give {"messages": msgs, "text": "", "steps": steps, "usage": usage, "stopped": "stopped"}
578
625
  when errors >= MAX_ERRORS_PER_TURN
579
626
  set msgs to append(msgs, {"role": "user", "content": "[harness] Too many tool errors this turn. Stop calling tools and report what happened."})
580
627
  emit(on_event, "busy", {"label": "pensando", "kind": "llm"}, tag)
package/lib/mailbox.syn CHANGED
@@ -107,7 +107,7 @@ export task working(agent, thread)
107
107
  give false
108
108
 
109
109
  -- saca todo lo encolado
110
- task take(k)
110
+ export task take(k)
111
111
  lock(k)
112
112
  let q be state_get("mb:q:" + k, [])
113
113
  state_set("mb:q:" + k, [])
@@ -116,7 +116,7 @@ task take(k)
116
116
  give q
117
117
 
118
118
  -- el worker se va solo si la fila está vacía (bajo el lock: nadie encola en el medio)
119
- task release(k)
119
+ export task release(k)
120
120
  lock(k)
121
121
  let q be state_get("mb:q:" + k, [])
122
122
  let gone be length(q) == 0
@@ -125,6 +125,33 @@ task release(k)
125
125
  unlock(k)
126
126
  give gone
127
127
 
128
+ -- La puerta web conserva su SSE y sus aprobaciones, pero comparte la misma cola y el mismo lock.
129
+ -- Un solo handler es dueño de la conversación; otro puede encolar input sin lanzar un segundo turno.
130
+ export task begin_inline(k)
131
+ lock(k)
132
+ let claim be not state_get("mb:w:" + k, false)
133
+ when claim
134
+ state_set("mb:w:" + k, true)
135
+ unlock(k)
136
+ give claim
137
+
138
+ export task enqueue_active(k, item)
139
+ lock(k)
140
+ let active be state_get("mb:w:" + k, false)
141
+ when active
142
+ state_set("mb:q:" + k, append(state_get("mb:q:" + k, []), item))
143
+ unlock(k)
144
+ give active
145
+
146
+ export task has_pending(k)
147
+ give length(state_get("mb:q:" + k, [])) > 0
148
+
149
+ export task peek(k)
150
+ give state_get("mb:q:" + k, [])
151
+
152
+ export task is_active(k)
153
+ give state_get("mb:w:" + k, false)
154
+
128
155
  -- espera de silencio: quiet_s sin mensajes nuevos, o max_s desde el primero
129
156
  task settle(k, buf)
130
157
  require time
package/lib/prompt.syn CHANGED
@@ -22,7 +22,7 @@ task read_context_files()
22
22
  set out to out
23
23
  give out
24
24
 
25
- export task build(env_info, addendum)
25
+ export task build(env_info, addendum, computer_allowed = true)
26
26
  require exec
27
27
  require time
28
28
  require file.read("workspace")
@@ -35,8 +35,8 @@ export task build(env_info, addendum)
35
35
  require file.read(".lampson/**")
36
36
  require env("LAMPSON_*")
37
37
  require env("OS")
38
- -- computer_use solo se menciona cuando está en el catálogo (encendida + driver): vacío si no
39
- let cu be computer.prompt_line()
38
+ -- Los hijos no reciben instrucciones para usar una herramienta reservada al principal.
39
+ let cu be when computer_allowed then computer.prompt_line() otherwise ""
40
40
  let core be `You are Lampson, a coding agent that works inside the user's project through tools.
41
41
  Operate like a careful senior engineer: precise, honest, and economical with words.
42
42
 
package/lib/runtime.syn CHANGED
@@ -709,10 +709,26 @@ export task open(sobre, hooks)
709
709
  set aopts["catalog"] to aopts["catalog"] + remotetools.catalog(remote, rnames)
710
710
  set aopts["remote_tools"] to remote
711
711
  set ctx["opts"] to aopts
712
+ set ctx to session_inbox(ctx, sid, hooks)
712
713
  -- sesión actual (blackboard): la tool todo guarda su lista por sesión (lib/tools/todo.syn)
713
714
  share {"id": sid} as "lampson:session"
714
715
  give {"ctx": ctx, "session": sid, "thread": thread, "messages": messages, "mode": ctx["opts"]["permission_mode"], "note": note, "space": space}
715
716
 
717
+ -- El buzón pertenece a una sesión, nunca al blackboard global (varios chats pueden estar vivos a la vez).
718
+ task session_inbox(ctx, sid, hooks)
719
+ let opts be ctx["opts"]
720
+ set opts["parent_session"] to sid
721
+ when opts["inbox_fn"] != nothing
722
+ task inbox(step, tag)
723
+ give agents.parent_inbox(step, tag, sid)
724
+ set opts to loop.with_final_inbox(loop.with_inbox(opts, inbox, ""))
725
+ when field(hooks, "await_subagents", false)
726
+ task final_inbox(step, tag)
727
+ give agents.wait_parent_inbox(step, tag, sid, 900)
728
+ set opts["final_inbox_fn"] to final_inbox
729
+ set ctx["opts"] to opts
730
+ give ctx
731
+
716
732
  -- guarda la sesión con su agente y thread (y el índice del thread)
717
733
  export task save(o, messages)
718
734
  require time
@@ -779,6 +795,9 @@ export task turn(o, messages, label, hooks)
779
795
  require secret("LAMPSON_*")
780
796
  let sid be o["session"]
781
797
  let user_cb be field(hooks, "on_event", nothing)
798
+ -- La terminal arma su contexto sin open(); conserva también el buzón por sesión.
799
+ when not contains(o["ctx"]["opts"], "parent_session")
800
+ set o["ctx"] to session_inbox(o["ctx"], sid, hooks)
782
801
  let th0 be text(field(o, "thread", ""))
783
802
  let me be o["ctx"]["agent"]
784
803
  task on_event(kind, data, tag)