zerochat 10.43.0__tar.gz → 10.44.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.
Potentially problematic release.
This version of zerochat might be problematic. Click here for more details.
- {zerochat-10.43.0/zerochat.egg-info → zerochat-10.44.0}/PKG-INFO +1 -1
- {zerochat-10.43.0 → zerochat-10.44.0}/pyproject.toml +1 -1
- {zerochat-10.43.0 → zerochat-10.44.0/zerochat.egg-info}/PKG-INFO +1 -1
- {zerochat-10.43.0 → zerochat-10.44.0}/zerochat.py +163 -26
- {zerochat-10.43.0 → zerochat-10.44.0}/LICENSE +0 -0
- {zerochat-10.43.0 → zerochat-10.44.0}/README.md +0 -0
- {zerochat-10.43.0 → zerochat-10.44.0}/setup.cfg +0 -0
- {zerochat-10.43.0 → zerochat-10.44.0}/zerochat.egg-info/SOURCES.txt +0 -0
- {zerochat-10.43.0 → zerochat-10.44.0}/zerochat.egg-info/dependency_links.txt +0 -0
- {zerochat-10.43.0 → zerochat-10.44.0}/zerochat.egg-info/entry_points.txt +0 -0
- {zerochat-10.43.0 → zerochat-10.44.0}/zerochat.egg-info/top_level.txt +0 -0
|
@@ -43,6 +43,7 @@ import shlex
|
|
|
43
43
|
import shutil
|
|
44
44
|
import signal
|
|
45
45
|
import socket
|
|
46
|
+
import socketserver
|
|
46
47
|
import sqlite3
|
|
47
48
|
import subprocess
|
|
48
49
|
import sys
|
|
@@ -1163,7 +1164,7 @@ def parse_nonneg_int(value, label: str, default: int = 0) -> int:
|
|
|
1163
1164
|
|
|
1164
1165
|
|
|
1165
1166
|
|
|
1166
|
-
SOURCE_BACKEND_VERSION = "10.
|
|
1167
|
+
SOURCE_BACKEND_VERSION = "10.44.0"
|
|
1167
1168
|
|
|
1168
1169
|
|
|
1169
1170
|
def _read_source_version(filename: str) -> str | None:
|
|
@@ -3698,6 +3699,21 @@ def upsert_run_state(payload: dict) -> None:
|
|
|
3698
3699
|
notify_live_change()
|
|
3699
3700
|
|
|
3700
3701
|
|
|
3702
|
+
def delete_orphan_run_states() -> list[str]:
|
|
3703
|
+
"""Borra las filas de runs que ya no están en marcha y cuya conversación no existe (una ejecución que falló antes
|
|
3704
|
+
de guardarla); devuelve sus conversation_id. Las que siguen en marcha se conservan: su agente aún no la ha guardado."""
|
|
3705
|
+
with open_storage() as conn:
|
|
3706
|
+
with _immediate_transaction(conn):
|
|
3707
|
+
ids = [row["conversation_id"] for row in conn.execute(
|
|
3708
|
+
"SELECT conversation_id FROM runs WHERE status != 'running' "
|
|
3709
|
+
"AND conversation_id NOT IN (SELECT id FROM conversations);")]
|
|
3710
|
+
if ids:
|
|
3711
|
+
conn.executemany("DELETE FROM runs WHERE conversation_id = ?;", [(conv_id,) for conv_id in ids])
|
|
3712
|
+
if ids:
|
|
3713
|
+
notify_live_change()
|
|
3714
|
+
return ids
|
|
3715
|
+
|
|
3716
|
+
|
|
3701
3717
|
def get_run_state(conversation_id: str) -> dict | None:
|
|
3702
3718
|
"""Recupera de SQLite el estado en vivo de la ejecución de una conversación."""
|
|
3703
3719
|
clean_id = _validate_conversation_id(conversation_id)
|
|
@@ -4575,6 +4591,7 @@ class McpServiceRecord:
|
|
|
4575
4591
|
|
|
4576
4592
|
# Nombre de la variable de entorno de un secreto que declara un servicio en su service.json ("secrets").
|
|
4577
4593
|
SERVICE_SECRET_NAME_PATTERN = re.compile(r"[A-Z][A-Z0-9_]{0,63}")
|
|
4594
|
+
MAX_OPTION_TEXT_LENGTH = 1024
|
|
4578
4595
|
|
|
4579
4596
|
|
|
4580
4597
|
def service_secrets(server: dict) -> list[dict]:
|
|
@@ -4917,7 +4934,13 @@ class McpServiceManager:
|
|
|
4917
4934
|
if not opt_id:
|
|
4918
4935
|
continue
|
|
4919
4936
|
val = user_opts.get(opt_id, opt.get("default"))
|
|
4920
|
-
|
|
4937
|
+
if opt.get("type") == "text":
|
|
4938
|
+
text_val = "" if val is None else str(val).strip()
|
|
4939
|
+
if opt.get("required") and not text_val:
|
|
4940
|
+
raise RuntimeError(f"Falta configurar {opt_id} en Ajustes › MCP.")
|
|
4941
|
+
values[f"option:{opt_id}"] = text_val
|
|
4942
|
+
else:
|
|
4943
|
+
values[f"option:{opt_id}"] = "" if val is None else str(val)
|
|
4921
4944
|
if opt.get("type") == "boolean":
|
|
4922
4945
|
option_args.extend(opt.get("argsWhenTrue", []) if val else opt.get("argsWhenFalse", []))
|
|
4923
4946
|
|
|
@@ -4999,16 +5022,46 @@ class McpServiceManager:
|
|
|
4999
5022
|
self._notify_state_changed()
|
|
5000
5023
|
return self.list_servers()
|
|
5001
5024
|
|
|
5025
|
+
@staticmethod
|
|
5026
|
+
def _normalize_option_value(spec: dict, key: str, value):
|
|
5027
|
+
opt_type = spec.get("type")
|
|
5028
|
+
if opt_type == "boolean":
|
|
5029
|
+
if not isinstance(value, bool):
|
|
5030
|
+
raise ValueError(f"La opción {key} debe ser booleana.")
|
|
5031
|
+
return value
|
|
5032
|
+
if opt_type == "text":
|
|
5033
|
+
if not isinstance(value, str):
|
|
5034
|
+
raise ValueError(f"La opción {key} debe ser texto.")
|
|
5035
|
+
normalized = value.strip()
|
|
5036
|
+
if len(normalized) > MAX_OPTION_TEXT_LENGTH:
|
|
5037
|
+
raise ValueError(f"La opción {key} supera {MAX_OPTION_TEXT_LENGTH} caracteres.")
|
|
5038
|
+
return normalized
|
|
5039
|
+
return value
|
|
5040
|
+
|
|
5002
5041
|
def configure(self, server_id: str, options: dict | None = None) -> list[dict]:
|
|
5003
5042
|
with self._lock:
|
|
5004
5043
|
self.services = self._load_services()
|
|
5005
|
-
|
|
5044
|
+
server = self.services.get(server_id)
|
|
5045
|
+
if not server:
|
|
5006
5046
|
raise KeyError(f"Servidor MCP desconocido: {server_id}")
|
|
5007
5047
|
entry = self.preferences.setdefault(server_id, {})
|
|
5048
|
+
changed = False
|
|
5008
5049
|
if options is not None:
|
|
5050
|
+
declared = {opt["id"]: opt for opt in server.get("options", []) if isinstance(opt, dict) and opt.get("id")}
|
|
5009
5051
|
opts = entry.setdefault("options", {})
|
|
5010
|
-
|
|
5052
|
+
for key, value in options.items():
|
|
5053
|
+
spec = declared.get(key)
|
|
5054
|
+
if not spec:
|
|
5055
|
+
raise ValueError(f"Opción desconocida para {server_id}: {key}")
|
|
5056
|
+
normalized = self._normalize_option_value(spec, key, value)
|
|
5057
|
+
if opts.get(key) != normalized:
|
|
5058
|
+
opts[key] = normalized
|
|
5059
|
+
changed = True
|
|
5011
5060
|
self._save_preferences()
|
|
5061
|
+
if changed:
|
|
5062
|
+
record = self.records.pop(server_id, None)
|
|
5063
|
+
if record and record.client:
|
|
5064
|
+
record.client.stop()
|
|
5012
5065
|
self._notify_state_changed()
|
|
5013
5066
|
return self.list_servers()
|
|
5014
5067
|
|
|
@@ -5248,9 +5301,12 @@ RUN_EXPORT_MAX_BODY_BYTES = 64 * 1024 * 1024
|
|
|
5248
5301
|
RUN_FILE_TEXT_KEYS = ("conversation_id", "prompt", "profile", "agent")
|
|
5249
5302
|
# Límites opcionales de la ejecución: llamadas al modelo y segundos desde el arranque del proceso, con su máximo.
|
|
5250
5303
|
RUN_FILE_LIMIT_KEYS = {"maxSteps": 1000, "timeout": 24 * 60 * 60}
|
|
5251
|
-
RUN_FILE_KEYS = frozenset(RUN_FILE_TEXT_KEYS + ("systemDataPrompt", "projectMode", "watchAgents") + tuple(RUN_FILE_LIMIT_KEYS))
|
|
5304
|
+
RUN_FILE_KEYS = frozenset(RUN_FILE_TEXT_KEYS + ("systemDataPrompt", "projectMode", "watchAgents", "reasoning") + tuple(RUN_FILE_LIMIT_KEYS))
|
|
5252
5305
|
# Lo que una conversación de agente guarda de su lanzamiento (además del perfil) y repite al continuarla.
|
|
5253
|
-
RUN_LAUNCH_KEYS = ("systemDataPrompt", "projectMode", "watchAgents") + tuple(RUN_FILE_LIMIT_KEYS)
|
|
5306
|
+
RUN_LAUNCH_KEYS = ("systemDataPrompt", "projectMode", "watchAgents", "reasoning") + tuple(RUN_FILE_LIMIT_KEYS)
|
|
5307
|
+
# Niveles de razonamiento de --run-file (los del selector de la interfaz) y el que usa si no indica ninguno.
|
|
5308
|
+
RUN_REASONING_LEVELS = ("none", "low", "medium", "high", "xhigh")
|
|
5309
|
+
DEFAULT_RUN_REASONING = "medium"
|
|
5254
5310
|
# Patrones de watchAgents que admite una ejecución (agentes que vigila con check_agents).
|
|
5255
5311
|
MAX_WATCH_AGENTS = 32
|
|
5256
5312
|
# El prompt acaba en la conversación, que se guarda por HTTP: no cabe uno mayor que el cuerpo admitido.
|
|
@@ -5281,11 +5337,16 @@ def _run_request_object(raw: bytes) -> dict:
|
|
|
5281
5337
|
|
|
5282
5338
|
|
|
5283
5339
|
def _agent_options(data: dict) -> dict:
|
|
5284
|
-
"""projectMode (sin él, --run-file no inyecta AGENTS.md ni .zerochat/state.md: el agente sigue su propio manual)
|
|
5285
|
-
|
|
5340
|
+
"""projectMode (sin él, --run-file no inyecta AGENTS.md ni .zerochat/state.md: el agente sigue su propio manual),
|
|
5341
|
+
reasoning (el nivel de razonamiento de la ejecución, DEFAULT_RUN_REASONING si no lo indica) y watchAgents (los
|
|
5342
|
+
agentes que la ejecución puede consultar con check_agents)."""
|
|
5286
5343
|
if "projectMode" in data and not isinstance(data["projectMode"], bool):
|
|
5287
5344
|
raise ValueError("projectMode debe ser true o false")
|
|
5288
5345
|
options = {"projectMode": data.get("projectMode", False)}
|
|
5346
|
+
reasoning = data.get("reasoning", DEFAULT_RUN_REASONING)
|
|
5347
|
+
if reasoning not in RUN_REASONING_LEVELS:
|
|
5348
|
+
raise ValueError(f"reasoning debe ser uno de: {', '.join(RUN_REASONING_LEVELS)}")
|
|
5349
|
+
options["reasoning"] = reasoning
|
|
5289
5350
|
if "watchAgents" in data:
|
|
5290
5351
|
patterns = data["watchAgents"]
|
|
5291
5352
|
if not isinstance(patterns, list) or not 1 <= len(patterns) <= MAX_WATCH_AGENTS:
|
|
@@ -5394,6 +5455,19 @@ def write_run_state(session: RunSession) -> None:
|
|
|
5394
5455
|
upsert_run_state(payload)
|
|
5395
5456
|
|
|
5396
5457
|
|
|
5458
|
+
def discard_unstarted_run(session: RunSession | None) -> None:
|
|
5459
|
+
"""Una ejecución que sale antes de lanzar su runner (proyecto sin entorno guardado, sin Node, sin puerto...) no deja
|
|
5460
|
+
fila en runs: borra la suya (la de su run_id; la de otra ejecución de la conversación no se toca)."""
|
|
5461
|
+
if session is None or session.runner_started or not session.state_conversation_id:
|
|
5462
|
+
return
|
|
5463
|
+
try:
|
|
5464
|
+
row = get_run_state(session.state_conversation_id)
|
|
5465
|
+
except (ValueError, sqlite3.Error, OSError):
|
|
5466
|
+
return
|
|
5467
|
+
if row and row.get("run_id") == session.run_id:
|
|
5468
|
+
remove_run_state(session.state_conversation_id)
|
|
5469
|
+
|
|
5470
|
+
|
|
5397
5471
|
def remove_run_state(conversation_id: str | None) -> None:
|
|
5398
5472
|
"""Elimina de SQLite el estado de la ejecución de la conversación al cancelarla."""
|
|
5399
5473
|
if not conversation_id:
|
|
@@ -5449,6 +5523,13 @@ def list_server_runs(focus_conversation_id: str | None = None) -> tuple[list[dic
|
|
|
5449
5523
|
started_at = data.get("started_at", 0)
|
|
5450
5524
|
entries.append((started_at, light, data))
|
|
5451
5525
|
|
|
5526
|
+
# Filas sin conversación de ejecuciones que ya no siguen (fallaron antes de guardarla): no son de nadie.
|
|
5527
|
+
try:
|
|
5528
|
+
orphans = set(delete_orphan_run_states())
|
|
5529
|
+
except (sqlite3.Error, OSError) as err:
|
|
5530
|
+
log_event(f"[zerochat] No se pudieron limpiar las ejecuciones sin conversación: {err}")
|
|
5531
|
+
orphans = set()
|
|
5532
|
+
entries = [entry for entry in entries if entry[1]["conversation_id"] not in orphans]
|
|
5452
5533
|
entries.sort(key=lambda item: item[0])
|
|
5453
5534
|
# Las completadas solo interesan a quien sigue su conversación: el latido no las arrastra todas.
|
|
5454
5535
|
runs = [item[1] for item in entries if item[1]["status"] != "completed"]
|
|
@@ -5634,7 +5715,7 @@ class RunSession:
|
|
|
5634
5715
|
new_conversation_id: str | None = None, system_data_prompt: str | None = None,
|
|
5635
5716
|
max_steps: int | None = None, timeout_seconds: int | None = None, project_mode: bool | None = None,
|
|
5636
5717
|
agent: str | None = None, launch: dict | None = None, watch_agents: tuple[str, ...] = (),
|
|
5637
|
-
track_run: bool = False):
|
|
5718
|
+
track_run: bool = False, reasoning: str | None = None):
|
|
5638
5719
|
env_run_id = os.environ.get("ZEROCHAT_RUN_ID", "").strip()
|
|
5639
5720
|
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))
|
|
5640
5721
|
self.conversation_id = conversation_id
|
|
@@ -5654,9 +5735,15 @@ class RunSession:
|
|
|
5654
5735
|
self.launch = launch
|
|
5655
5736
|
# watchAgents de --run-file: habilita y autoriza check_agents solo en esta ejecución.
|
|
5656
5737
|
self.watch_agents = tuple(watch_agents)
|
|
5738
|
+
# Conversaciones que este master lanzó con launch_agent ({id: {agent, project, updatedAt}}): check_agents las
|
|
5739
|
+
# ve desde el lanzamiento, antes de que el agente las guarde en conversations.
|
|
5740
|
+
self.launched_agents: dict[str, dict] = {}
|
|
5657
5741
|
# projectMode de --run-file: si el runner inyecta las normas y el estado del proyecto; None (--prompt y
|
|
5658
5742
|
# --conversation) deja el modo proyecto por defecto del runner.
|
|
5659
5743
|
self.project_mode = project_mode
|
|
5744
|
+
# reasoning de --run-file (o de su lanzamiento al continuarla): el runner lo aplica tras activar el perfil;
|
|
5745
|
+
# None (--prompt, --conversation de un chat) deja el del perfil.
|
|
5746
|
+
self.reasoning = reasoning
|
|
5660
5747
|
# Límites de --run-file: el de pasos lo aplica el bucle del runner y el de tiempo, run_supervisor.
|
|
5661
5748
|
self.max_steps = max_steps
|
|
5662
5749
|
self.timeout_seconds = timeout_seconds
|
|
@@ -5697,6 +5784,8 @@ class RunSession:
|
|
|
5697
5784
|
# Tokens acumulados que informa el runner (zerochat/run/usage); None hasta su primera llamada al modelo.
|
|
5698
5785
|
self.usage: dict | None = None
|
|
5699
5786
|
self.runner_token: str | None = None
|
|
5787
|
+
# Si llegó a lanzarse el runner de Node: antes de eso, salir no deja fila (discard_unstarted_run).
|
|
5788
|
+
self.runner_started = False
|
|
5700
5789
|
write_run_state(self)
|
|
5701
5790
|
|
|
5702
5791
|
def set_wake_event(self, event: threading.Event | None) -> None:
|
|
@@ -5834,7 +5923,8 @@ def _rpc_prompt(params: dict, session: RunSession) -> RpcOutcome:
|
|
|
5834
5923
|
# Para switch_model, que busca por nombre: el runner no puede listar los perfiles con su credencial.
|
|
5835
5924
|
# El listado no lleva API keys; la del que active la pide con zerochat/run/profile.
|
|
5836
5925
|
"profiles": list_general_profiles(),
|
|
5837
|
-
"export": export_format, "max_steps": session.max_steps, "project_mode": session.project_mode
|
|
5926
|
+
"export": export_format, "max_steps": session.max_steps, "project_mode": session.project_mode,
|
|
5927
|
+
"reasoning": session.reasoning})
|
|
5838
5928
|
|
|
5839
5929
|
|
|
5840
5930
|
def _rpc_profile(params: dict, session: RunSession) -> RpcOutcome:
|
|
@@ -9214,6 +9304,8 @@ AGENT_MAX_WAIT = TOOL_WAIT_MAX_SECONDS
|
|
|
9214
9304
|
# Los agentes corren en otros procesos: su final llega sin sondeo (se espera su PID, watch_run_exit), pero una
|
|
9215
9305
|
# ejecución nueva (lanzada por cron o por un script) solo se ve en SQLite, así que la espera la relee cada tanto.
|
|
9216
9306
|
AGENT_WAIT_RECHECK_SECONDS = 5.0
|
|
9307
|
+
# Estados que cortan una espera aunque otros agentes sigan en marcha: alguien tiene que mirarlos.
|
|
9308
|
+
AGENT_ATTENTION_STATUSES = ("needs_input", "error")
|
|
9217
9309
|
# Tope de prune_keep: cuántas conversaciones recientes de cada agente puede pedir conservar el master.
|
|
9218
9310
|
AGENT_PRUNE_KEEP_MAX = 1000
|
|
9219
9311
|
# Estados que la limpieza nunca borra: una ejecución en marcha o una pausa que espera a una persona.
|
|
@@ -9249,10 +9341,18 @@ def _target_project(ctx: SecurityContext, project: str | None, access: str) -> S
|
|
|
9249
9341
|
|
|
9250
9342
|
|
|
9251
9343
|
def _watched_conversations(ctx: SecurityContext, patterns: tuple[str, ...], own_id: str) -> list[dict]:
|
|
9252
|
-
"""Conversaciones de agentes vigilados del proyecto, de la más reciente a la más antigua, sin la del propio master.
|
|
9344
|
+
"""Conversaciones de agentes vigilados del proyecto, de la más reciente a la más antigua, sin la del propio master.
|
|
9345
|
+
Incluye las que este master lanzó y el agente aún no ha guardado: su fila de runs ya está en marcha."""
|
|
9253
9346
|
project = _conversation_project(ctx)
|
|
9254
|
-
|
|
9255
|
-
|
|
9347
|
+
convs = [conv for conv in list_conversations()
|
|
9348
|
+
if conv["id"] != own_id and (conv.get("project") or "") == project and agent_matches(conv.get("agent"), patterns)]
|
|
9349
|
+
session = current_run_session()
|
|
9350
|
+
saved = {conv["id"] for conv in convs}
|
|
9351
|
+
pending = [{"id": conv_id, **meta} for conv_id, meta in (session.launched_agents if session else {}).items()
|
|
9352
|
+
if conv_id not in saved and meta["project"] == project and agent_matches(meta["agent"], patterns)]
|
|
9353
|
+
if not pending:
|
|
9354
|
+
return convs
|
|
9355
|
+
return sorted(convs + pending, key=lambda conv: conv.get("updatedAt") or 0, reverse=True)
|
|
9256
9356
|
|
|
9257
9357
|
|
|
9258
9358
|
def _agent_state(conv: dict, run: dict) -> dict:
|
|
@@ -9334,17 +9434,31 @@ def _selected(ctx: SecurityContext, patterns: tuple[str, ...], own_id: str, agen
|
|
|
9334
9434
|
return [(conv, get_run_state(conv["id"]) or {}) for conv in picked] or None
|
|
9335
9435
|
|
|
9336
9436
|
|
|
9337
|
-
def
|
|
9338
|
-
"""
|
|
9339
|
-
|
|
9340
|
-
|
|
9341
|
-
return
|
|
9437
|
+
def _wait_reason(selected: list[tuple[dict, dict]] | None, attention: dict[str, str]) -> str | None:
|
|
9438
|
+
"""Por qué deja de esperar con lo leído, o None para seguir: ninguna consultada en marcha (not_running), o una
|
|
9439
|
+
que pasa a needs_input o error durante la espera (needs_attention); attention es el estado de cada una al empezar."""
|
|
9440
|
+
if selected is None:
|
|
9441
|
+
return "not_running"
|
|
9442
|
+
statuses = {conv["id"]: _agent_state(conv, run)["status"] for conv, run in selected}
|
|
9443
|
+
if any(status in AGENT_ATTENTION_STATUSES and attention.get(conv_id) != status for conv_id, status in statuses.items()):
|
|
9444
|
+
return "needs_attention"
|
|
9445
|
+
if all(status != "running" for status in statuses.values()):
|
|
9446
|
+
return "not_running"
|
|
9447
|
+
return None
|
|
9448
|
+
|
|
9342
9449
|
|
|
9450
|
+
def _wait_for_change(read, wait: float) -> tuple[list[tuple[dict, dict]] | None, str]:
|
|
9451
|
+
"""Relee con read() mientras alguna conversación consultada siga en marcha, como mucho wait: vuelve en cuanto
|
|
9452
|
+
ninguna lo está (también al empezar, sin esperar) o cuando una pasa a necesitar a alguien. Devuelve lo último
|
|
9453
|
+
leído y el motivo (not_running, needs_attention o wait_elapsed)."""
|
|
9343
9454
|
deadline = time.monotonic() + wait
|
|
9344
9455
|
seq = live_change_seq()
|
|
9345
9456
|
selected = read()
|
|
9346
|
-
|
|
9457
|
+
attention = {conv["id"]: _agent_state(conv, run)["status"] for conv, run in selected or ()}
|
|
9347
9458
|
while True:
|
|
9459
|
+
reason = _wait_reason(selected, attention)
|
|
9460
|
+
if reason:
|
|
9461
|
+
return selected, reason
|
|
9348
9462
|
for _conv, run in selected or ():
|
|
9349
9463
|
if run.get("status") == "running" and run.get("pid"):
|
|
9350
9464
|
watch_run_exit(run["pid"], run.get("pid_start"))
|
|
@@ -9353,8 +9467,6 @@ def _wait_for_change(read, wait: float) -> tuple[list[tuple[dict, dict]] | None,
|
|
|
9353
9467
|
return selected, "wait_elapsed"
|
|
9354
9468
|
seq = wait_live_change(seq, min(remaining, AGENT_WAIT_RECHECK_SECONDS))
|
|
9355
9469
|
selected = read()
|
|
9356
|
-
if signature(selected) != initial:
|
|
9357
|
-
return selected, "agent_changed"
|
|
9358
9470
|
|
|
9359
9471
|
|
|
9360
9472
|
def _prune(convs: list[dict], agent: str | None, keep: int) -> str:
|
|
@@ -9493,6 +9605,10 @@ def _launch(request: dict, prompt: str | None, target: SecurityContext, patterns
|
|
|
9493
9605
|
except ValueError:
|
|
9494
9606
|
raise ValueError(f"The conversation {request['conversation_id']} is already running: nothing was launched.") from None
|
|
9495
9607
|
launched = launch_run_file(request, Path(target.workspace_dir))
|
|
9608
|
+
session = current_run_session()
|
|
9609
|
+
if session is not None:
|
|
9610
|
+
session.launched_agents[request["conversation_id"]] = {
|
|
9611
|
+
"agent": agent, "project": _conversation_project(target), "updatedAt": int(time.time() * 1000)}
|
|
9496
9612
|
return json.dumps({"success": True, "agent": agent, "conversation_id": request["conversation_id"], "new": conv is None,
|
|
9497
9613
|
"run_id": launched["run_id"], "project": target.key,
|
|
9498
9614
|
"note": "It runs on its own: follow it with check_agents (with the same project), which can wait for it."},
|
|
@@ -10501,9 +10617,10 @@ CHECK_AGENTS_DEFINITION = {
|
|
|
10501
10617
|
f"error, warnings, token usage of the run and its final answer when it fits ({AGENT_LIST_RESULT_MAX_CHARS} characters each, "
|
|
10502
10618
|
f"{AGENT_LIST_TOTAL_CHARS} in all; otherwise only result_chars). With agent or conversation_id, the final answer in blocks of "
|
|
10503
10619
|
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. "
|
|
10504
|
-
"To wait for the agents instead of calling it repeatedly, give wait_seconds: it
|
|
10505
|
-
"
|
|
10506
|
-
"
|
|
10620
|
+
"To wait for the agents instead of calling it repeatedly, give wait_seconds: it keeps waiting while any of the "
|
|
10621
|
+
"agents asked about is running and returns at once when none is (returned_because: not_running), as soon as one "
|
|
10622
|
+
"of them turns needs_input or error (needs_attention) or when the time is up (wait_elapsed); call it again with "
|
|
10623
|
+
"wait_seconds while they are still running. Agents started with launch_agent are listed from the start. To clean up old conversations of the watched agents "
|
|
10507
10624
|
"(for example, one per scheduled run), give prune_keep=N, optionally with agent: it deletes all but the N most recent "
|
|
10508
10625
|
"conversations of each agent, never one that is running or waiting for the user, and lists what it deleted and skipped."
|
|
10509
10626
|
),
|
|
@@ -11806,6 +11923,14 @@ class ZeroChatHTTPServer(ThreadingHTTPServer):
|
|
|
11806
11923
|
plazo de conexión) y Windows las reinicia."""
|
|
11807
11924
|
request_queue_size = 128
|
|
11808
11925
|
|
|
11926
|
+
def server_bind(self):
|
|
11927
|
+
"""Como HTTPServer.server_bind, sin socket.getfqdn: su resolución inversa del host puede tardar decenas de
|
|
11928
|
+
segundos (en macOS sin DNS inverso, ~35 s) y el nombre del servidor no se usa."""
|
|
11929
|
+
socketserver.TCPServer.server_bind(self)
|
|
11930
|
+
host, port = self.server_address[:2]
|
|
11931
|
+
self.server_name = str(host)
|
|
11932
|
+
self.server_port = port
|
|
11933
|
+
|
|
11809
11934
|
# --- cli.main ---
|
|
11810
11935
|
"""Punto de entrada de zerochat: argumentos de la línea de órdenes, arranque del servidor, interfaz, ejecución desatendida y cierre."""
|
|
11811
11936
|
|
|
@@ -11845,7 +11970,7 @@ def build_parser() -> ZeroChatArgumentParser:
|
|
|
11845
11970
|
parser.add_argument("--list-profiles", action="store_true", help="Listar los perfiles de conexión generales almacenados en el servidor local")
|
|
11846
11971
|
parser.add_argument("--prompt", default=None, help="Ejecutar este prompt sin interfaz gráfica con Node.js, imprimir solo la respuesta final y terminar (salida 0 terminado, 1 error de generación, 2 runner cerrado sin resultado, 3 fallo de arranque, 4 argumentos no válidos, 5 pausada a la espera del usuario, con su pregunta en la salida, 6 límite de --run-file alcanzado)")
|
|
11847
11972
|
parser.add_argument("--conversation", default=None, help="Con --prompt o para continuar, id de la conversación almacenada en SQLite")
|
|
11848
|
-
parser.add_argument("--run-file", default=None, metavar="FICHERO", help="Ejecutar la petición del fichero JSON (- para leerla de stdin) en lugar de --prompt, --conversation y --profile: prompt, conversation_id (la continúa o, si no existe, la crea con ese id), profile, agent (<subconjunto>.<nombre>: marca la conversación nueva como de ese agente), systemDataPrompt, watchAgents (patrones de agentes del proyecto que vigila con check_agents), projectMode (true inyecta AGENTS.md y .zerochat/state.md; por defecto no), maxSteps y timeout (segundos); exige un entorno de proyecto guardado, del que salen siempre herramientas y permisos")
|
|
11973
|
+
parser.add_argument("--run-file", default=None, metavar="FICHERO", help="Ejecutar la petición del fichero JSON (- para leerla de stdin) en lugar de --prompt, --conversation y --profile: prompt, conversation_id (la continúa o, si no existe, la crea con ese id), profile, agent (<subconjunto>.<nombre>: marca la conversación nueva como de ese agente), systemDataPrompt, watchAgents (patrones de agentes del proyecto que vigila con check_agents), projectMode (true inyecta AGENTS.md y .zerochat/state.md; por defecto no), reasoning (none, low, medium, high o xhigh; medium por defecto), maxSteps y timeout (segundos); exige un entorno de proyecto guardado, del que salen siempre herramientas y permisos")
|
|
11849
11974
|
parser.add_argument("--profile", default=None, help=f"Con --prompt o --conversation, perfil (nombre o id) que se usa solo en esta ejecución, sin cambiar el activo (por defecto: {DEFAULT_RUN_PROFILE} del servidor)")
|
|
11850
11975
|
parser.add_argument("--log", choices=("on", "off"), default=None, help="Mostrar la cabecera y el registro del servidor (default: on; off en modo ejecución)")
|
|
11851
11976
|
parser.add_argument("--export", default=None, metavar="FICHERO", help=f"Con --prompt, --conversation o --run-file, guardar la conversación en FICHERO; el formato sale de la extensión ({', '.join(RUN_EXPORT_FORMATS)})")
|
|
@@ -11992,7 +12117,8 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
|
|
|
11992
12117
|
new_conversation_id=new_conversation_id, system_data_prompt=options.get("systemDataPrompt"),
|
|
11993
12118
|
max_steps=options.get("maxSteps"), timeout_seconds=options.get("timeout"),
|
|
11994
12119
|
project_mode=options.get("projectMode"), agent=options.get("agent"), launch=launch,
|
|
11995
|
-
watch_agents=tuple(options.get("watchAgents") or ()), track_run=args.run_file is not None
|
|
12120
|
+
watch_agents=tuple(options.get("watchAgents") or ()), track_run=args.run_file is not None,
|
|
12121
|
+
reasoning=options.get("reasoning"))
|
|
11996
12122
|
|
|
11997
12123
|
|
|
11998
12124
|
def _require_no_active_run(conversation_id: str | None):
|
|
@@ -12177,6 +12303,7 @@ def start_interface(args, parser, server: ThreadingHTTPServer, ui_url: str):
|
|
|
12177
12303
|
mute_console()
|
|
12178
12304
|
sys.exit(RUN_EXIT_SETUP)
|
|
12179
12305
|
runner_proc, runner_log = runner
|
|
12306
|
+
session.runner_started = True
|
|
12180
12307
|
threading.Thread(target=run_supervisor, args=(server, session, runner_proc, runner_log), daemon=True).start()
|
|
12181
12308
|
|
|
12182
12309
|
|
|
@@ -12278,6 +12405,16 @@ def main():
|
|
|
12278
12405
|
reset_notices()
|
|
12279
12406
|
session = run_session_from_args(parser, args)
|
|
12280
12407
|
set_run_session(session)
|
|
12408
|
+
try:
|
|
12409
|
+
_start(parser, args, session)
|
|
12410
|
+
except SystemExit:
|
|
12411
|
+
# Salir antes de lanzar el runner (entorno sin guardar, sin Node, puerto ocupado...) no deja fila en runs.
|
|
12412
|
+
discard_unstarted_run(session)
|
|
12413
|
+
raise
|
|
12414
|
+
|
|
12415
|
+
|
|
12416
|
+
def _start(parser: ZeroChatArgumentParser, args, session: RunSession | None):
|
|
12417
|
+
"""Prepara y arranca el servidor y, en modo ejecución, el runner de Node; vuelve al detenerse el servidor."""
|
|
12281
12418
|
_prepare_run_environment(parser, args, session)
|
|
12282
12419
|
result_out = redirect_log(args)
|
|
12283
12420
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|