zerochat 10.51.0__tar.gz → 10.52.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.51.0
3
+ Version: 10.52.0
4
4
  Summary: Personal, private AI workspace and unattended agent runtime: web UI, local tools, MCP services and controller orchestration
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zerochat"
7
- version = "10.51.0"
7
+ version = "10.52.0"
8
8
  description = "Personal, private AI workspace and unattended agent runtime: web UI, local tools, MCP services and controller orchestration"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.51.0
3
+ Version: 10.52.0
4
4
  Summary: Personal, private AI workspace and unattended agent runtime: web UI, local tools, MCP services and controller orchestration
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -1171,7 +1171,7 @@ def parse_nonneg_int(value, label: str, default: int = 0) -> int:
1171
1171
 
1172
1172
 
1173
1173
 
1174
- SOURCE_BACKEND_VERSION = "10.51.0"
1174
+ SOURCE_BACKEND_VERSION = "10.52.0"
1175
1175
 
1176
1176
 
1177
1177
  def _read_source_version(filename: str) -> str | None:
@@ -5892,7 +5892,17 @@ def _approved_call(tool_security) -> tuple[str, dict] | None:
5892
5892
  return tool_name, args
5893
5893
 
5894
5894
 
5895
- class RunSession:
5895
+ class ControllerState:
5896
+ """Lo que un controlador recuerda mientras vive: las conversaciones que lanzó con launch_agent
5897
+ ({id: {agent, project, updatedAt}}), que check_agents ve desde el lanzamiento, antes de que el agente las guarde, y
5898
+ las respuestas finales ya entregadas, por (conversación, run_id) -> (result_chars, partial), que el listado no repite
5899
+ ni relee en conversaciones cortadas. Lo tiene cada ejecución y cada conversación del servidor de la interfaz."""
5900
+ def __init__(self):
5901
+ self.launched_agents: dict[str, dict] = {}
5902
+ self.delivered_results: dict[tuple[str, str], tuple[int, bool]] = {}
5903
+
5904
+
5905
+ class RunSession(ControllerState):
5896
5906
  """Estado de la ejecución: prompt, opciones, último progreso, exportación, resultado y motivo de un final sin él."""
5897
5907
  def __init__(self, prompt: str | None = None, profile: str | None = None, export_path: Path | None = None,
5898
5908
  conversation_id: str | None = None, run_id: str | None = None,
@@ -5901,6 +5911,7 @@ class RunSession:
5901
5911
  max_steps: int | None = None, timeout_seconds: int | None = None, project_mode: bool | None = None,
5902
5912
  agent: str | None = None, launch: dict | None = None, controller: bool = False, disabled_tools: tuple[str, ...] = (),
5903
5913
  track_run: bool = False, reasoning: str | None = None, subagents: bool = False):
5914
+ super().__init__()
5904
5915
  env_run_id = os.environ.get("ZEROCHAT_RUN_ID", "").strip()
5905
5916
  self.run_id = run_id.strip() if (run_id and isinstance(run_id, str) and run_id.strip()) else (env_run_id or secrets.token_urlsafe(24))
5906
5917
  self.conversation_id = conversation_id
@@ -5918,18 +5929,11 @@ class RunSession:
5918
5929
  self.agent = agent
5919
5930
  # Petición de lanzamiento de un agente (--run-file): finish_run la guarda en su conversación.
5920
5931
  self.launch = launch
5921
- # controller: true de --run-file: habilita y autoriza check_agents y launch_agent solo en esta ejecución.
5922
- self.controller = controller
5932
+ # Controladora: la de controller: true de --run-file o la de un chat lanzado en segundo plano con «Subagentes»
5933
+ # (nunca la de un agente). Publica y autoriza las herramientas del controlador solo en esta ejecución.
5934
+ self.controller = bool(controller or (subagents and not agent and not track_run))
5923
5935
  # disabledTools de --run-file: lo que run_project_environment le quita del entorno del proyecto.
5924
5936
  self.disabled_tools = tuple(disabled_tools)
5925
- # Solo una ejecución interactiva en servidor (sin --run-file ni agente) puede heredar «Subagentes».
5926
- self.subagents = bool(subagents and not agent and not track_run)
5927
- # Respuestas finales ya entregadas en esta ejecución, por (conversación, run_id) -> (result_chars, partial): el
5928
- # listado no las repite ni relee conversaciones cortadas.
5929
- self.delivered_results: dict[tuple[str, str], tuple[int, bool]] = {}
5930
- # Conversaciones que este controlador lanzó con launch_agent ({id: {agent, project, updatedAt}}): check_agents las
5931
- # ve desde el lanzamiento, antes de que el agente las guarde en conversations.
5932
- self.launched_agents: dict[str, dict] = {}
5933
5937
  # projectMode de --run-file: si el runner inyecta las normas y el estado del proyecto; None (--prompt y
5934
5938
  # --conversation) deja el modo proyecto por defecto del runner.
5935
5939
  self.project_mode = project_mode
@@ -6125,7 +6129,7 @@ def _rpc_prompt(params: dict, session: RunSession) -> RpcOutcome:
6125
6129
  # El listado no lleva API keys; la del que active la pide con zerochat/run/profile.
6126
6130
  "profiles": list_general_profiles(),
6127
6131
  "export": export_format, "max_steps": session.max_steps, "project_mode": session.project_mode,
6128
- "reasoning": session.reasoning, "subagents": session.subagents, "disabled_tools": list(session.disabled_tools)})
6132
+ "reasoning": session.reasoning, "subagents": session.controller, "disabled_tools": list(session.disabled_tools)})
6129
6133
 
6130
6134
 
6131
6135
  def _rpc_profile(params: dict, session: RunSession) -> RpcOutcome:
@@ -8529,7 +8533,7 @@ class AccessController:
8529
8533
 
8530
8534
  def allows_path(self, access: str, path: str, context: SecurityContext) -> bool:
8531
8535
  """Si las reglas de directorio del proyecto (o su allowAll) dan `access` sobre `path`, sin preguntar: para las
8532
- herramientas que actúan sobre otra carpeta en una ejecución desatendida (check_agents y launch_agent)."""
8536
+ herramientas del controlador que actúan sobre otra carpeta (check_agents, launch_agent, stop_agent y prune_agents)."""
8533
8537
  view = self._effective_state(context)
8534
8538
  return bool(view["allowAll"]) or self.evaluate_directory_rule(access, path, view["directoryRules"], context)["allowed"]
8535
8539
 
@@ -8884,8 +8888,9 @@ class AccessController:
8884
8888
  ACCESS_CONTROLLER = AccessController()
8885
8889
 
8886
8890
  # --- tools.agents ---
8887
- """check_agents, launch_agent, stop_agent y prune_agents: las herramientas de un agente controlador, solo en la
8888
- ejecución --run-file con controller: true.
8891
+ """check_agents, launch_agent, stop_agent y prune_agents: las herramientas de un agente controlador. Lo es una
8892
+ ejecución --run-file con controller: true, una ejecución en segundo plano de un chat con «Subagentes» y cada
8893
+ conversación del servidor de la interfaz, que solo las ofrece al modelo con «Subagentes» encendido.
8889
8894
 
8890
8895
  check_agents lee conversaciones y ejecuciones de SQLite filtrando estrictamente por un proyecto (el de la ejecución o,
8891
8896
  con project, otro sobre el que sus reglas de directorio den lectura) y por tener agente: nunca chats humanos (sin agent)
@@ -8904,7 +8909,8 @@ AGENTS_TOOL = "check_agents"
8904
8909
  LAUNCH_AGENT_TOOL = "launch_agent"
8905
8910
  STOP_AGENT_TOOL = "stop_agent"
8906
8911
  PRUNE_AGENTS_TOOL = "prune_agents"
8907
- # Las herramientas del controlador: se publican y autorizan juntas, solo en una ejecución --run-file con controller: true.
8912
+ # Las herramientas del controlador: se publican juntas en el servidor de la interfaz y en una ejecución controladora,
8913
+ # que además las autoriza; nunca en otra ejecución.
8908
8914
  CONTROLLER_TOOLS = (AGENTS_TOOL, LAUNCH_AGENT_TOOL, STOP_AGENT_TOOL, PRUNE_AGENTS_TOOL)
8909
8915
  # Tope del prompt que launch_agent pone en lugar del del run-file.
8910
8916
  MAX_LAUNCH_PROMPT_LENGTH = 32768
@@ -8932,6 +8938,11 @@ AGENT_STOPPED_ERROR = "Stopped by its controller."
8932
8938
  AGENT_PRUNE_PROTECTED = ("running", "needs_input")
8933
8939
 
8934
8940
 
8941
+ # El del servidor de la interfaz, que es de un solo usuario: uno para todas sus conversaciones y pestañas, en memoria
8942
+ # hasta que el servidor se cierra, como el de una ejecución.
8943
+ INTERFACE_CONTROLLER = ControllerState()
8944
+
8945
+
8935
8946
  def _clip(text: str, limit: int) -> tuple[str, bool]:
8936
8947
  return (text, False) if len(text) <= limit else (text[:limit], True)
8937
8948
 
@@ -8960,15 +8971,14 @@ def _target_project(ctx: SecurityContext, project: str | None, access: str) -> S
8960
8971
  return target
8961
8972
 
8962
8973
 
8963
- def _agent_conversations(ctx: SecurityContext, own_id: str) -> list[dict]:
8974
+ def _agent_conversations(ctx: SecurityContext, own_id: str, state: ControllerState) -> list[dict]:
8964
8975
  """Conversaciones de agentes del proyecto, de la más reciente a la más antigua, sin la del propio controlador.
8965
8976
  Incluye las que este controlador lanzó y el agente aún no ha guardado: su fila de runs ya está en marcha."""
8966
8977
  project = _conversation_project(ctx)
8967
8978
  convs = [conv for conv in list_conversations()
8968
8979
  if conv["id"] != own_id and conv.get("agent") and (conv.get("project") or "") == project]
8969
- session = current_run_session()
8970
8980
  saved = {conv["id"] for conv in convs}
8971
- pending = [{"id": conv_id, **meta} for conv_id, meta in (session.launched_agents if session else {}).items()
8981
+ pending = [{"id": conv_id, **meta} for conv_id, meta in state.launched_agents.items()
8972
8982
  if conv_id not in saved and meta["project"] == project]
8973
8983
  if not pending:
8974
8984
  return convs
@@ -9014,22 +9024,19 @@ def _runs() -> dict:
9014
9024
  return {"running": running_run_count(), "max": MAX_CONCURRENT_RUNS}
9015
9025
 
9016
9026
 
9017
- def _delivered(conv: dict, run: dict) -> tuple[dict[tuple[str, str], tuple[int, bool]], tuple[str, str] | None]:
9018
- """Las respuestas ya entregadas en esta ejecución ((result_chars, partial)) y la clave de esta, que cambia con
9019
- cada ejecución de la conversación (None fuera de una ejecución)."""
9020
- session = current_run_session()
9021
- if session is None:
9022
- return {}, None
9023
- return session.delivered_results, (conv["id"], run.get("run_id") or "")
9027
+ def _delivered_key(conv: dict, run: dict) -> tuple[str, str]:
9028
+ """La clave de una respuesta entregada, que cambia con cada ejecución de la conversación."""
9029
+ return conv["id"], run.get("run_id") or ""
9024
9030
 
9025
9031
 
9026
- def _listing(selected: list[tuple[dict, dict]]) -> dict:
9032
+ def _listing(selected: list[tuple[dict, dict]], state: ControllerState) -> dict:
9027
9033
  """El listado con la respuesta final entera de cada agente mientras quepa (por agente y entre todos); la que no,
9028
9034
  sin texto y con result_chars, y la ya entregada en esta ejecución, sin texto y con result_seen."""
9029
9035
  budget, agents, omitted, seen = AGENT_LIST_TOTAL_CHARS, [], False, False
9036
+ delivered = state.delivered_results
9030
9037
  for conv, run in selected:
9031
9038
  entry = _agent_state(conv, run)
9032
- delivered, key = _delivered(conv, run)
9039
+ key = _delivered_key(conv, run)
9033
9040
  if key in delivered:
9034
9041
  result_chars, partial = delivered[key]
9035
9042
  if partial:
@@ -9044,7 +9051,7 @@ def _listing(selected: list[tuple[dict, dict]]) -> dict:
9044
9051
  if len(result) <= min(AGENT_LIST_RESULT_MAX_CHARS, budget):
9045
9052
  entry["result_text"] = result
9046
9053
  budget -= len(result)
9047
- if result and key:
9054
+ if result:
9048
9055
  delivered[key] = (len(result), partial)
9049
9056
  else:
9050
9057
  entry["result_chars"] = len(result)
@@ -9083,19 +9090,18 @@ def _last_turn(history: list[dict]) -> tuple[list[dict], bool]:
9083
9090
  return messages, truncated
9084
9091
 
9085
9092
 
9086
- def _selected(ctx: SecurityContext, own_id: str, agent: str | None,
9093
+ def _selected(ctx: SecurityContext, own_id: str, state: ControllerState, agent: str | None,
9087
9094
  conversation_id: str | None) -> list[tuple[dict, dict]] | None:
9088
9095
  """Las conversaciones consultadas con su ejecución: sin agent ni conversation_id, todas las que lanzó este
9089
9096
  controlador en esta ejecución (varias del mismo agente si repartió el trabajo) y la más reciente de cada agente;
9090
9097
  si no, la de agent o la de conversation_id. None si agent o conversation_id no es de un agente del proyecto."""
9091
- convs = _agent_conversations(ctx, own_id)
9098
+ convs = _agent_conversations(ctx, own_id, state)
9092
9099
  if conversation_id is not None:
9093
9100
  picked = [conv for conv in convs if conv["id"] == conversation_id][:1]
9094
9101
  elif agent is not None:
9095
9102
  picked = [conv for conv in convs if conv["agent"] == agent][:1]
9096
9103
  else:
9097
- session = current_run_session()
9098
- launched = session.launched_agents if session else {}
9104
+ launched = state.launched_agents
9099
9105
  seen: set[str] = set()
9100
9106
  picked = []
9101
9107
  for conv in convs: # De la más reciente a la más antigua.
@@ -9161,13 +9167,19 @@ def _prune(convs: list[dict], agent: str | None, keep: int) -> str:
9161
9167
  return json.dumps({"success": True, "deleted": deleted, "skipped": skipped}, ensure_ascii=False)
9162
9168
 
9163
9169
 
9164
- def _controller_context(tool_name: str, ctx: SecurityContext | None, project: str | None, access: str):
9165
- """Valida que la herramienta corre bajo un controlador y resuelve su propio id y el proyecto destino."""
9170
+ def _controller_context(tool_name: str, ctx: SecurityContext | None, project: str | None,
9171
+ access: str) -> tuple[ControllerState, str, SecurityContext]:
9172
+ """El estado y el id de la conversación del controlador, y el proyecto destino: en una ejecución, los suyos, que
9173
+ tiene que ser controladora; en el servidor de la interfaz, su estado único y sin conversación propia."""
9174
+ if ctx is None:
9175
+ raise ValueError(f"{tool_name} needs the project of the call.")
9166
9176
  session = current_run_session()
9167
- if session is None or not session.controller or ctx is None:
9168
- raise ValueError(f"{tool_name} is only available in a --run-file run with controller: true.")
9169
- own_id = session.conversation_id or session.new_conversation_id or ""
9170
- return session, own_id, _target_project(ctx, project, access)
9177
+ if session is not None:
9178
+ if not session.controller:
9179
+ raise ValueError(f"{tool_name} is only available to a controller: a --run-file run with controller: true "
9180
+ "or a chat with Subagents on.")
9181
+ return session, session.conversation_id or session.new_conversation_id or "", _target_project(ctx, project, access)
9182
+ return INTERFACE_CONTROLLER, "", _target_project(ctx, project, access)
9171
9183
 
9172
9184
 
9173
9185
  def check_agents(agent: str | None = None, conversation_id: str | None = None, wait_seconds: int = 0,
@@ -9178,7 +9190,7 @@ def check_agents(agent: str | None = None, conversation_id: str | None = None, w
9178
9190
  y, con include_turn, los mensajes de su último turno. Con wait_seconds, antes espera como mucho ese tiempo a que
9179
9191
  cambie. Con project, los agentes de esa carpeta en lugar de los del proyecto de la ejecución."""
9180
9192
  try:
9181
- _session, own_id, target = _controller_context(AGENTS_TOOL, ctx, project, "R")
9193
+ state, own_id, target = _controller_context(AGENTS_TOOL, ctx, project, "R")
9182
9194
  except ValueError as exc:
9183
9195
  return _tool_error(str(exc))
9184
9196
  detail = agent is not None or conversation_id is not None
@@ -9188,7 +9200,7 @@ def check_agents(agent: str | None = None, conversation_id: str | None = None, w
9188
9200
  return _tool_error("offset must be a non-negative integer.")
9189
9201
 
9190
9202
  def read():
9191
- return _selected(target, own_id, agent, conversation_id)
9203
+ return _selected(target, own_id, state, agent, conversation_id)
9192
9204
 
9193
9205
  wait = max(0, min(int(wait_seconds or 0), AGENT_MAX_WAIT))
9194
9206
  extra = {}
@@ -9201,8 +9213,8 @@ def check_agents(agent: str | None = None, conversation_id: str | None = None, w
9201
9213
  if selected is None:
9202
9214
  return _tool_error("That agent or conversation is not an agent of this project.")
9203
9215
  if not detail:
9204
- return json.dumps({"success": True, **_listing(selected), "runs": _runs(), **extra}, ensure_ascii=False)
9205
- return _detail(*selected[0], offset, include_turn, extra)
9216
+ return json.dumps({"success": True, **_listing(selected, state), "runs": _runs(), **extra}, ensure_ascii=False)
9217
+ return _detail(*selected[0], state, offset, include_turn, extra)
9206
9218
 
9207
9219
 
9208
9220
  def stop_agent(conversation_id: str | None = None, project: str | None = None,
@@ -9210,15 +9222,15 @@ def stop_agent(conversation_id: str | None = None, project: str | None = None,
9210
9222
  """Detiene una conversación que este controlador lanzó en esta ejecución: mata su proceso con su árbol (runner y
9211
9223
  servicios MCP) y deja su fila en error, para que check_agents la muestre con lo que avanzó (respuesta parcial)."""
9212
9224
  try:
9213
- session, own_id, target = _controller_context(STOP_AGENT_TOOL, ctx, project, "R")
9225
+ state, own_id, target = _controller_context(STOP_AGENT_TOOL, ctx, project, "R")
9214
9226
  except ValueError as exc:
9215
9227
  return _tool_error(str(exc))
9216
9228
  if not isinstance(conversation_id, str) or not conversation_id.strip():
9217
9229
  return _tool_error("conversation_id must be a non-empty string.")
9218
9230
  conv_id = conversation_id.strip()
9219
- if conv_id not in session.launched_agents:
9231
+ if conv_id not in state.launched_agents:
9220
9232
  return _tool_error("A controller only stops the agents it launched in this run.")
9221
- selected = _selected(target, own_id, None, conv_id)
9233
+ selected = _selected(target, own_id, state, None, conv_id)
9222
9234
  if selected is None:
9223
9235
  return _tool_error("That conversation is not an agent of this project.")
9224
9236
  conv, run = selected[0]
@@ -9228,10 +9240,10 @@ def stop_agent(conversation_id: str | None = None, project: str | None = None,
9228
9240
  # Releer tras el plazo de gracia para conservar usage/warnings recientes o un resultado terminado a tiempo.
9229
9241
  fresh = get_run_state(conv_id) or run
9230
9242
  if fresh.get("status") != "running":
9231
- return _detail(conv, fresh, 0, False, {"stopped": False})
9243
+ return _detail(conv, fresh, state, 0, False, {"stopped": False})
9232
9244
  now = int(time.time() * 1000)
9233
9245
  upsert_run_state({**fresh, "status": "error", "error": AGENT_STOPPED_ERROR, "updated_at": now, "finished_at": now})
9234
- return _detail(conv, get_run_state(conv_id) or {}, 0, False, {"stopped": True})
9246
+ return _detail(conv, get_run_state(conv_id) or {}, state, 0, False, {"stopped": True})
9235
9247
 
9236
9248
 
9237
9249
  def prune_agents(keep: int | None = None, agent: str | None = None, project: str | None = None,
@@ -9239,18 +9251,18 @@ def prune_agents(keep: int | None = None, agent: str | None = None, project: str
9239
9251
  """Borra las conversaciones antiguas de los agentes del proyecto (o solo de agent) conservando las keep más
9240
9252
  recientes, nunca una en marcha o esperando respuesta, y devuelve las borradas y las conservadas."""
9241
9253
  try:
9242
- _session, own_id, target = _controller_context(PRUNE_AGENTS_TOOL, ctx, project, "RW")
9254
+ state, own_id, target = _controller_context(PRUNE_AGENTS_TOOL, ctx, project, "RW")
9243
9255
  except ValueError as exc:
9244
9256
  return _tool_error(str(exc))
9245
9257
  if isinstance(keep, bool) or not isinstance(keep, int) or not 0 <= keep <= AGENT_PRUNE_KEEP_MAX:
9246
9258
  return _tool_error(f"keep must be an integer between 0 and {AGENT_PRUNE_KEEP_MAX}.")
9247
- convs = _agent_conversations(target, own_id)
9259
+ convs = _agent_conversations(target, own_id, state)
9248
9260
  if agent is not None and not any(conv["agent"] == agent for conv in convs):
9249
9261
  return _tool_error("That agent is not an agent of this project.")
9250
9262
  return _prune(convs, agent, keep)
9251
9263
 
9252
9264
 
9253
- def _detail(conv: dict, run: dict, offset: int, include_turn: bool, extra: dict) -> str:
9265
+ def _detail(conv: dict, run: dict, controller: ControllerState, offset: int, include_turn: bool, extra: dict) -> str:
9254
9266
  """El detalle de una conversación: su estado, un bloque de su respuesta final y, con include_turn, su último turno."""
9255
9267
  state = _agent_state(conv, run)
9256
9268
  result, partial = _final_answer(conv, state, run)
@@ -9263,9 +9275,8 @@ def _detail(conv: dict, run: dict, offset: int, include_turn: bool, extra: dict)
9263
9275
  messages, truncated = _last_turn((get_conversation(conv["id"]) or {}).get("history") or [])
9264
9276
  turn = {"last_turn": messages, **({"last_turn_truncated": True} if truncated else {})}
9265
9277
  page = _result_page(result, offset)
9266
- delivered, key = _delivered(conv, run)
9267
- if result and key and page["next_offset"] is None:
9268
- delivered[key] = (len(result), partial)
9278
+ if result and page["next_offset"] is None:
9279
+ controller.delivered_results[_delivered_key(conv, run)] = (len(result), partial)
9269
9280
  return json.dumps({"success": True, **state, **page, **turn, **extra},
9270
9281
  ensure_ascii=False)
9271
9282
 
@@ -9346,18 +9357,19 @@ def launch_agent(run_file: str | None = None, prompt: str | None = None, project
9346
9357
  `run_file` (ruta dentro del proyecto) o, sin él, el que se da en línea (agent, system_prompt y prompt, con profile,
9347
9358
  reasoning, max_steps, timeout, conversation_id y disabled_tools opcionales). Con prompt sustituye el del fichero; con project, el
9348
9359
  agente se lanza en esa carpeta, con su entorno guardado y sus permisos."""
9349
- session = current_run_session()
9350
- if session is None or not session.controller or ctx is None:
9351
- return _tool_error("launch_agent is only available in a --run-file run with controller: true.")
9352
9360
  fields = {key: value for key, value in (("agent", agent), ("system_prompt", system_prompt), ("profile", profile),
9353
9361
  ("reasoning", reasoning), ("max_steps", max_steps), ("timeout", timeout), ("conversation_id", conversation_id),
9354
9362
  ("disabled_tools", disabled_tools))
9355
9363
  if value is not None}
9356
- own_id = session.conversation_id or session.new_conversation_id or ""
9364
+ # Lanzar en otra carpeta es ejecutar en ella: el agente corre con su entorno y sus permisos, y prompt sustituye
9365
+ # las instrucciones del run-file.
9366
+ try:
9367
+ state, own_id, target = _controller_context(LAUNCH_AGENT_TOOL, ctx, project, "X")
9368
+ except ValueError as exc:
9369
+ return _tool_error(str(exc))
9357
9370
  if run_file is None:
9358
9371
  try:
9359
- target = _target_project(ctx, project, "X")
9360
- return _launch(_inline_request(fields, prompt), prompt, target, own_id=own_id)
9372
+ return _launch(_inline_request(fields, prompt), prompt, target, own_id, state)
9361
9373
  except ValueError as exc:
9362
9374
  return _tool_error(str(exc))
9363
9375
  if fields:
@@ -9365,9 +9377,6 @@ def launch_agent(run_file: str | None = None, prompt: str | None = None, project
9365
9377
  if not isinstance(run_file, str) or not run_file.strip():
9366
9378
  return _tool_error("run_file must be the path of the agent's run-file in the project, such as agents/report.md.")
9367
9379
  try:
9368
- # Lanzar en otra carpeta es ejecutar en ella: el agente corre con su entorno y sus permisos, y prompt
9369
- # sustituye las instrucciones del run-file.
9370
- target = _target_project(ctx, project, "X")
9371
9380
  path = target.absolute(run_file.strip())
9372
9381
  if not path.is_relative_to(target.workspace_dir.resolve()):
9373
9382
  raise ValueError(f"run_file must be inside the project folder {target.workspace_dir}.")
@@ -9378,7 +9387,7 @@ def launch_agent(run_file: str | None = None, prompt: str | None = None, project
9378
9387
  request = parse_run_request(handle.read(RUN_FILE_MAX_BYTES + 1))
9379
9388
  except ValueError as exc:
9380
9389
  raise ValueError(_format_run_error(exc, inline=False)) from None
9381
- return _launch(request, prompt, target, own_id=own_id)
9390
+ return _launch(request, prompt, target, own_id, state)
9382
9391
  except OSError as exc:
9383
9392
  return _tool_error(f"Could not read the run-file: {exc}")
9384
9393
  except ValueError as exc:
@@ -9401,7 +9410,7 @@ def _target_conversation(conv_id: str | None, agent: str, target: SecurityContex
9401
9410
  return conv
9402
9411
 
9403
9412
 
9404
- def _launch(request: dict, prompt: str | None, target: SecurityContext, own_id: str) -> str:
9413
+ def _launch(request: dict, prompt: str | None, target: SecurityContext, own_id: str, state: ControllerState) -> str:
9405
9414
  agent = request.get("agent")
9406
9415
  if not agent:
9407
9416
  raise ValueError("The run-file must set an agent.")
@@ -9425,10 +9434,8 @@ def _launch(request: dict, prompt: str | None, target: SecurityContext, own_id:
9425
9434
  except ValueError:
9426
9435
  raise ValueError(f"The conversation {request['conversation_id']} is already running: nothing was launched.") from None
9427
9436
  launched = launch_run_file(request, Path(target.workspace_dir))
9428
- session = current_run_session()
9429
- if session is not None:
9430
- session.launched_agents[request["conversation_id"]] = {
9431
- "agent": agent, "project": _conversation_project(target), "updatedAt": int(time.time() * 1000)}
9437
+ state.launched_agents[request["conversation_id"]] = {
9438
+ "agent": agent, "project": _conversation_project(target), "updatedAt": int(time.time() * 1000)}
9432
9439
  return json.dumps({"success": True, "agent": agent, "conversation_id": request["conversation_id"], "new": conv is None,
9433
9440
  "run_id": launched["run_id"], "project": target.key, "runs": _runs(),
9434
9441
  "note": "It runs on its own: follow it with check_agents (with the same project), which can wait for it."},
@@ -11580,18 +11587,18 @@ LOCAL_TOOLS_DEFINITIONS = [
11580
11587
  }
11581
11588
  }
11582
11589
  ]
11583
- # Solo se publican en una ejecución --run-file con controller: true (server/rpc.py), que además las autoriza; fuera
11584
- # de ella sus manejadores se niegan a responder.
11590
+ # Se publican en el servidor de la interfaz y en una ejecución controladora (server/rpc.py), que además las autoriza;
11591
+ # en otra ejecución sus manejadores se niegan a responder.
11585
11592
  CHECK_AGENTS_DEFINITION = {
11586
11593
  "name": AGENTS_TOOL,
11587
11594
  "description": (
11588
- "Status of the agents of this project, which this run controls, or, with project, of another one. Without arguments, one entry for each "
11589
- "conversation this run launched (several of the same agent if it split the work) and for the latest conversation "
11595
+ "Status of the agents of this project, which you control, or, with project, of another one. Without arguments, one entry for each "
11596
+ "conversation you launched (several of the same agent if it split the work) and for the latest conversation "
11590
11597
  "of every other agent: status (running, needs_input, completed, error, limit), step, pending input, "
11591
11598
  f"error, warnings, token usage of the run and its final answer when it fits ({AGENT_LIST_RESULT_MAX_CHARS} characters each, "
11592
11599
  f"{AGENT_LIST_TOTAL_CHARS} in all; otherwise only result_chars). An agent cut off by limit or error has no final "
11593
11600
  "answer: it then brings its last text with partial=true, which tells where it stopped. An answer already delivered "
11594
- "in full during this run is not repeated in the listing (result_seen, with result_chars). The listing also gives "
11601
+ "in full is not repeated in the listing (result_seen, with result_chars). The listing also gives "
11595
11602
  "runs: how many runs are going on the machine and the most allowed at a time. With agent or conversation_id, the final answer in blocks of "
11596
11603
  f"{AGENT_RESULT_PAGE_CHARS} characters (pass next_offset as offset for the next one) and, with include_turn=true, the messages of its last turn. "
11597
11604
  "To wait for the agents instead of calling it repeatedly, give wait_seconds: it keeps waiting while any of the "
@@ -11605,7 +11612,7 @@ CHECK_AGENTS_DEFINITION = {
11605
11612
  "agent": {"type": "string", "maxLength": MAX_AGENT_ID_LENGTH, "description": "Agent id (<name> or <set>.<name>): details of its latest conversation"},
11606
11613
  "conversation_id": {"type": "string", "maxLength": MAX_CONVERSATION_ID_LENGTH, "description": "Details of this agent conversation"},
11607
11614
  "wait_seconds": {"type": "integer", "description": f"Maximum seconds to wait for a change of the agents asked about before answering (default 0, max {AGENT_MAX_WAIT})", "default": 0},
11608
- "project": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Folder of another project whose agents to check (default: this run's project); its directory rules must give R"},
11615
+ "project": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Folder of another project whose agents to check (default: this project); its directory rules must give R"},
11609
11616
  "offset": {"type": "integer", "description": "With agent or conversation_id: character offset of the final answer to read from (the next_offset of the previous call)", "default": 0},
11610
11617
  "include_turn": {"type": "boolean", "description": "With agent or conversation_id: also return the messages of its last turn, including tool results", "default": False},
11611
11618
  }
@@ -11614,14 +11621,14 @@ CHECK_AGENTS_DEFINITION = {
11614
11621
  STOP_AGENT_DEFINITION = {
11615
11622
  "name": STOP_AGENT_TOOL,
11616
11623
  "description": (
11617
- "Stop a running agent conversation launched by this controller during this run, when it is stuck or no longer "
11624
+ "Stop a running agent conversation you launched, when it is stuck or no longer "
11618
11625
  "needed. Kills its run process and keeps what it finished as error so check_agents shows its partial progress."
11619
11626
  ),
11620
11627
  "inputSchema": {
11621
11628
  "type": "object",
11622
11629
  "properties": {
11623
11630
  "conversation_id": {"type": "string", "maxLength": MAX_CONVERSATION_ID_LENGTH, "description": "Conversation id of the running agent launched by this controller"},
11624
- "project": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Folder of another project where the agent runs (default: this run's project); its directory rules must give R"}
11631
+ "project": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Folder of another project where the agent runs (default: this project); its directory rules must give R"}
11625
11632
  },
11626
11633
  "required": ["conversation_id"]
11627
11634
  }
@@ -11638,7 +11645,7 @@ PRUNE_AGENTS_DEFINITION = {
11638
11645
  "properties": {
11639
11646
  "keep": {"type": "integer", "description": f"How many most recent conversations to keep per agent (0 to {AGENT_PRUNE_KEEP_MAX})"},
11640
11647
  "agent": {"type": "string", "maxLength": MAX_AGENT_ID_LENGTH, "description": "Agent id (<name> or <set>.<name>): prune only this agent's conversations (default: all agents)"},
11641
- "project": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Folder of another project whose agents to prune (default: this run's project); its directory rules must give RW"}
11648
+ "project": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Folder of another project whose agents to prune (default: this project); its directory rules must give RW"}
11642
11649
  },
11643
11650
  "required": ["keep"]
11644
11651
  }
@@ -11646,7 +11653,7 @@ PRUNE_AGENTS_DEFINITION = {
11646
11653
  LAUNCH_AGENT_DEFINITION = {
11647
11654
  "name": LAUNCH_AGENT_TOOL,
11648
11655
  "description": (
11649
- "Start an agent as a separate run that keeps going after this run ends, and return its conversation_id and "
11656
+ "Start an agent as a separate run that keeps going on its own after your turn ends, and return its conversation_id and "
11650
11657
  "run_id: either from its run-file (run_file, for example agents/report.md, which must set an agent) or given "
11651
11658
  "inline without a file (agent, system_prompt with its manual, prompt, and optionally profile, reasoning, "
11652
11659
  "max_steps, timeout, conversation_id and disabled_tools). It runs with the saved environment and permissions of its project and "
@@ -11660,7 +11667,7 @@ LAUNCH_AGENT_DEFINITION = {
11660
11667
  "properties": {
11661
11668
  "run_file": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Path of the agent's run-file (.md) inside the project; leave it out to give the agent inline"},
11662
11669
  "prompt": {"type": "string", "maxLength": MAX_LAUNCH_PROMPT_LENGTH, "description": "Task for this run (optional when continuing an existing conversation_id; with run_file, instead of the run-file's task)"},
11663
- "project": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Folder of another project to launch the agent in (default: this run's project); its directory rules must give X, and R to read run_file"},
11670
+ "project": {"type": "string", "maxLength": MAX_PATH_LENGTH, "description": "Folder of another project to launch the agent in (default: this project); its directory rules must give X, and R to read run_file"},
11664
11671
  "agent": {"type": "string", "maxLength": MAX_AGENT_ID_LENGTH, "description": "Inline: agent id (<name> or <set>.<name>)"},
11665
11672
  "system_prompt": {"type": "string", "maxLength": MAX_PROJECT_PROMPT_LENGTH, "description": "Inline: the agent's manual, instead of the project's system data prompt"},
11666
11673
  "profile": {"type": "string", "maxLength": MAX_PROFILE_NAME_LENGTH, "description": "Inline: server profile name or id (default: local)"},
@@ -11672,7 +11679,7 @@ LAUNCH_AGENT_DEFINITION = {
11672
11679
  }
11673
11680
  }
11674
11681
  }
11675
- # Las de un controlador, que solo se publican en una ejecución --run-file con controller: true.
11682
+ # Las de un controlador: en el servidor de la interfaz y en una ejecución controladora.
11676
11683
  CONTROLLER_TOOL_DEFINITIONS = (CHECK_AGENTS_DEFINITION, LAUNCH_AGENT_DEFINITION, STOP_AGENT_DEFINITION, PRUNE_AGENTS_DEFINITION)
11677
11684
 
11678
11685
  LOCAL_TOOL_HANDLERS = {
@@ -11911,6 +11918,10 @@ def call_tool(params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | N
11911
11918
  # el reto. Con ella se detiene un run_command y se corta la espera de un check_command (zerochat/jobs/*).
11912
11919
  job_key = meta.get("zerochatJobKey") if origin == "local" and tool_name in (COMMAND_TOOL, JOB_CONTROL_TOOL) else None
11913
11920
  conversation_id = str(meta.get("zerochatConversationId") or "")
11921
+ # Las del controlador no piden permiso: lo dio quien lo pidió («Subagentes» en la interfaz o controller: true), y
11922
+ # fuera de un controlador sus manejadores se niegan. Con project, sus reglas de directorio deciden sin preguntar.
11923
+ if origin == "local" and tool_name in CONTROLLER_TOOLS:
11924
+ return execute_tool(origin, tool_name, args, ctx, conversation_id)
11914
11925
  gate = authorize_or_challenge(origin, tool_name, args, ctx, job_key, conversation_id)
11915
11926
  return gate if gate is not None else execute_tool(origin, tool_name, with_job_key(args, job_key), ctx, conversation_id)
11916
11927
 
@@ -11967,10 +11978,12 @@ decide quién atiende cada uno.
11967
11978
 
11968
11979
 
11969
11980
  def _local_tools() -> list[dict]:
11970
- """Las herramientas locales y, solo en la ejecución --run-file con controller: true, las del controlador."""
11981
+ """Las herramientas locales y las del controlador, en el servidor de la interfaz o en una ejecución controladora,
11982
+ marcadas con metadata.controller: la interfaz solo las ofrece al modelo con «Subagentes» encendido."""
11971
11983
  session = current_run_session()
11972
- extra = CONTROLLER_TOOL_DEFINITIONS if session is not None and session.controller else ()
11973
- return [dict(definition) for definition in (*LOCAL_TOOLS_DEFINITIONS, *extra)]
11984
+ extra = CONTROLLER_TOOL_DEFINITIONS if session is None or session.controller else ()
11985
+ return [*(dict(definition) for definition in LOCAL_TOOLS_DEFINITIONS),
11986
+ *({**definition, "metadata": {"controller": True}} for definition in extra)]
11974
11987
 
11975
11988
 
11976
11989
  def rpc_login(params: dict) -> RpcOutcome:
@@ -12919,16 +12932,8 @@ def reset_session_authorizations():
12919
12932
  server_id = GLOBAL_MCP_MANAGER.server_of(tool_name) or ""
12920
12933
  ACCESS_CONTROLLER.apply_tool_decision(tool_decision, ctx, server_id=server_id)
12921
12934
  # Ninguna herramienta se autoriza sola por ser una ejecución desatendida: siguen las reglas guardadas, y lo que
12922
- # pediría permiso pausa la ejecución (needs_input). Solo las del controlador, que el run-file pide con controller: true.
12923
- permanent_tools = ACCESS_CONTROLLER.export_state(ctx).get("tools") or {}
12924
- ACCESS_CONTROLLER.apply_session_overlay({
12925
- "allowAll": False,
12926
- "tools": {
12927
- name: {"policy": POLICY_ALLOW}
12928
- for name in (CONTROLLER_TOOLS if session.controller else ())
12929
- if (permanent_tools.get(name) or {}).get("policy") != POLICY_DENY
12930
- }
12931
- }, ctx)
12935
+ # pediría permiso pausa la ejecución (needs_input). Las del controlador no pasan por permisos (call_tool).
12936
+ ACCESS_CONTROLLER.apply_session_overlay({"allowAll": False}, ctx)
12932
12937
 
12933
12938
 
12934
12939
  def open_server(args) -> ThreadingHTTPServer:
File without changes
File without changes
File without changes