zerochat 10.16.0__tar.gz → 10.18.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.16.0
3
+ Version: 10.18.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
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.16.0"
7
+ version = "10.18.0"
8
8
  description = "Private local web client for AI models, tools and MCP services"
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.16.0
3
+ Version: 10.18.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -14,6 +14,7 @@ from __future__ import annotations
14
14
  import argparse
15
15
  import atexit
16
16
  import base64
17
+ import codecs
17
18
  import contextlib
18
19
  import ctypes
19
20
  import ctypes.util
@@ -1381,7 +1382,7 @@ def _pid_alive(pid: int) -> bool:
1381
1382
 
1382
1383
 
1383
1384
 
1384
- SOURCE_BACKEND_VERSION = "10.16.0"
1385
+ SOURCE_BACKEND_VERSION = "10.18.0"
1385
1386
 
1386
1387
 
1387
1388
  def _read_source_version(filename: str) -> str | None:
@@ -3371,7 +3372,7 @@ def update_security_policy_data(mutator: typing.Callable[[dict | None], dict]) -
3371
3372
 
3372
3373
  # Plazo total y sin progreso de la interfaz.
3373
3374
  RUN_TOTAL_TIMEOUT = 900.0
3374
- RUN_IDLE_SECONDS = 180.0
3375
+ RUN_IDLE_SECONDS = 600.0
3375
3376
  RUN_POLL_SECONDS = 0.2
3376
3377
  RUN_PROGRESS_TEXT_MAX = 500
3377
3378
  RUN_STREAM_TEXT_MAX = 8000
@@ -3647,6 +3648,9 @@ class RunSession:
3647
3648
  self.tool_security = None
3648
3649
  self.lock = threading.Lock()
3649
3650
  self.last_activity = time.monotonic()
3651
+ # Esperas de check_command: no cuentan como inactividad y alargan el plazo total.
3652
+ self._waiting_since: float | None = None
3653
+ self._waited = 0.0
3650
3654
  self.prompt_delivered = False
3651
3655
  self.result: dict | None = None
3652
3656
  self.stop_reason: str | None = None
@@ -3671,8 +3675,28 @@ class RunSession:
3671
3675
 
3672
3676
  def idle_seconds(self) -> float:
3673
3677
  with self.lock:
3678
+ if self._waiting_since is not None:
3679
+ return 0.0
3674
3680
  return time.monotonic() - self.last_activity
3675
3681
 
3682
+ def begin_wait(self):
3683
+ with self.lock:
3684
+ self._waiting_since = time.monotonic()
3685
+
3686
+ def end_wait(self):
3687
+ with self.lock:
3688
+ now = time.monotonic()
3689
+ if self._waiting_since is not None:
3690
+ self._waited += now - self._waiting_since
3691
+ self._waiting_since = None
3692
+ self.last_activity = now
3693
+
3694
+ def waited_seconds(self) -> float:
3695
+ """Tiempo total en esperas de check_command, incluida la que esté en curso."""
3696
+ with self.lock:
3697
+ ongoing = time.monotonic() - self._waiting_since if self._waiting_since is not None else 0.0
3698
+ return self._waited + ongoing
3699
+
3676
3700
 
3677
3701
  RUN_SESSION: RunSession | None = None
3678
3702
 
@@ -3977,6 +4001,9 @@ try {
3977
4001
  if (req.url && req.url !== page.url()) {
3978
4002
  await page.goto(req.url, { waitUntil: 'domcontentloaded', timeout: 30000 });
3979
4003
  }
4004
+ // Con la máquina cargada, Chromium puede no haber pintado aún ningún fotograma:
4005
+ // esperar dos fotogramas garantiza que hay algo que capturar.
4006
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
3980
4007
  const buf = await page.screenshot({ fullPage: false });
3981
4008
  console.log(JSON.stringify({
3982
4009
  success: true,
@@ -4949,8 +4976,69 @@ def list_directory(path: str = ".", recursive: bool = False, *, ctx: SecurityCon
4949
4976
  return _tool_error(str(e))
4950
4977
 
4951
4978
 
4952
- def read_file(path: str, start_line: int = 1, end_line: int = None, max_lines: int = 500, max_bytes: int = 100000, *, ctx: SecurityContext) -> str:
4953
- """Read text content from a local file in streaming mode with safe ranges and bounds."""
4979
+ # Códigos de control de terminal (colores, movimiento del cursor) que un log trae y el modelo no necesita.
4980
+ ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b[@-Z\\-_]")
4981
+ READ_TAIL_BLOCK_BYTES = 64 * 1024
4982
+ MAX_READ_LINES = 2000
4983
+
4984
+
4985
+ def _terminal_line(line: str) -> str:
4986
+ """Una línea como la deja una terminal: sin códigos de color y, si se reescribe con \\r, su último tramo."""
4987
+ ending = "\n" if line.endswith("\n") else ""
4988
+ text = ANSI_ESCAPE_RE.sub("", line[:-1] if ending else line).rstrip("\r")
4989
+ return text[text.rfind("\r") + 1:] + ending
4990
+
4991
+
4992
+ def _count_lines(target: Path) -> int:
4993
+ lines = 0
4994
+ last = b""
4995
+ with open(target, "rb") as handle:
4996
+ while chunk := handle.read(1024 * 1024):
4997
+ lines += chunk.count(b"\n")
4998
+ last = chunk[-1:]
4999
+ return lines + (1 if last and last != b"\n" else 0)
5000
+
5001
+
5002
+ def _read_tail(target: Path, tail_lines: int, max_bytes: int) -> str:
5003
+ """Las últimas tail_lines líneas, leyendo el fichero desde el final por bloques y sin pasar de max_bytes."""
5004
+ file_size = target.stat().st_size
5005
+ wanted = max(1, min(int(tail_lines), MAX_READ_LINES))
5006
+ data = b""
5007
+ with open(target, "rb") as handle:
5008
+ position = file_size
5009
+ # Una línea más de las pedidas: la primera del bloque puede estar a medias.
5010
+ while position > 0 and data.count(b"\n") <= wanted and len(data) < max_bytes:
5011
+ step = min(READ_TAIL_BLOCK_BYTES, position)
5012
+ position -= step
5013
+ handle.seek(position)
5014
+ data = handle.read(step) + data
5015
+ truncated_bytes = len(data) > max_bytes
5016
+ if truncated_bytes:
5017
+ data = data[-max_bytes:]
5018
+ # Solo \n separa líneas: splitlines también parte en \r y desharía las barras de progreso.
5019
+ parts = data.decode("utf-8", errors="replace").split("\n")
5020
+ lines = [part + "\n" for part in parts[:-1]] + ([parts[-1]] if parts[-1] else [])
5021
+ if (position > 0 or truncated_bytes) and lines:
5022
+ lines = lines[1:]
5023
+ lines = lines[-wanted:]
5024
+ total_lines = _count_lines(target)
5025
+ start_line = total_lines - len(lines) + 1
5026
+ return json.dumps({
5027
+ "success": True,
5028
+ "path": str(target),
5029
+ "size_bytes": file_size,
5030
+ "total_lines": total_lines,
5031
+ "start_line": start_line,
5032
+ "end_line": total_lines,
5033
+ "lines_returned": len(lines),
5034
+ "truncated": start_line > 1,
5035
+ "content": "".join(_terminal_line(line) for line in lines)
5036
+ }, ensure_ascii=False, indent=2)
5037
+
5038
+
5039
+ def read_file(path: str, start_line: int = 1, end_line: int = None, max_lines: int = 500, max_bytes: int = 100000,
5040
+ tail_lines: int | None = None, *, ctx: SecurityContext) -> str:
5041
+ """Read text content from a local file in streaming mode with safe ranges and bounds, or its last lines."""
4954
5042
  try:
4955
5043
  target = ctx.absolute(path)
4956
5044
  if not target.exists():
@@ -4960,15 +5048,17 @@ def read_file(path: str, start_line: int = 1, end_line: int = None, max_lines: i
4960
5048
 
4961
5049
  file_size = target.stat().st_size
4962
5050
  safe_max_bytes = max(1024, min(int(max_bytes), 2000000))
5051
+ if tail_lines is not None:
5052
+ return _read_tail(target, tail_lines, safe_max_bytes)
4963
5053
  safe_start_line = max(1, int(start_line))
4964
5054
 
4965
5055
  if end_line is not None:
4966
5056
  safe_end_line = max(safe_start_line, int(end_line))
4967
- target_line_count = min(safe_end_line - safe_start_line + 1, 2000)
5057
+ target_line_count = min(safe_end_line - safe_start_line + 1, MAX_READ_LINES)
4968
5058
  safe_end_line = safe_start_line + target_line_count - 1
4969
5059
  else:
4970
5060
  safe_end_line = None
4971
- target_line_count = max(1, min(int(max_lines), 2000))
5061
+ target_line_count = max(1, min(int(max_lines), MAX_READ_LINES))
4972
5062
 
4973
5063
  selected_lines = []
4974
5064
  current_bytes = 0
@@ -5310,6 +5400,13 @@ MODEL_OUTPUT_READ_BYTES = 64 * 1024
5310
5400
  CARD_TAIL_BYTES = 2048
5311
5401
  JOB_LOG_PAGE_BYTES = 256 * 1024
5312
5402
  REPORT_TAIL_LINES = 20
5403
+ # check_command(pattern): longitud máxima de la expresión y de la línea que se devuelve al coincidir.
5404
+ CHECK_PATTERN_MAX_CHARS = 200
5405
+ MATCHED_LINE_MAX_CHARS = 500
5406
+ # Última línea de salida de cada comando en marcha en el latido, para su tarjeta plegada.
5407
+ LAST_LINE_MAX_CHARS = 200
5408
+ # Cada cuánto comprueba una espera de check_command si la persona la ha cortado.
5409
+ WAIT_SLICE_SECONDS = 0.25
5313
5410
  REPORT_TAIL_BYTES = 4096
5314
5411
 
5315
5412
 
@@ -5503,7 +5600,6 @@ class CommandJob:
5503
5600
  self.exit_code: int | None = None
5504
5601
  self.status = "running"
5505
5602
  self.stop_reason: str | None = None
5506
- self.timeout_seconds: int | None = None
5507
5603
  # Hasta dónde ha leído el modelo la salida, y si ya ha visto el final.
5508
5604
  self.model_cursor = 0
5509
5605
  self.reported = False
@@ -5512,6 +5608,8 @@ class CommandJob:
5512
5608
  self.runner_path: Path | None = None
5513
5609
  self.done = threading.Event()
5514
5610
  self._lock = threading.Lock()
5611
+ # Avisa a quien espera en check_command de que hay salida nueva o de que el comando terminó.
5612
+ self._changed = threading.Condition(self._lock)
5515
5613
  self._log = open(log_path, "wb")
5516
5614
  self._head_len = 0
5517
5615
  self._tail = bytearray()
@@ -5540,6 +5638,7 @@ class CommandJob:
5540
5638
  if overflow > 0:
5541
5639
  del self._tail[:overflow]
5542
5640
  self._tail_start += overflow
5641
+ self._changed.notify_all()
5543
5642
 
5544
5643
  def _read_output(self, stream):
5545
5644
  try:
@@ -5625,9 +5724,26 @@ class CommandJob:
5625
5724
  omitted = total - start - 2 * MODEL_OUTPUT_READ_BYTES
5626
5725
  return head + f"\n[... {omitted} bytes omitted ...]\n" + tail
5627
5726
 
5727
+ def wait_change(self, seen_total: int, timeout: float):
5728
+ """Espera como mucho timeout segundos a que haya salida más allá de seen_total o a que el comando termine."""
5729
+ with self._changed:
5730
+ self._changed.wait_for(lambda: self._total > seen_total or self.done.is_set(), timeout)
5731
+
5732
+ def notify_finished(self):
5733
+ with self._changed:
5734
+ self._changed.notify_all()
5735
+
5628
5736
  def tail_text(self, max_bytes: int = CARD_TAIL_BYTES) -> str:
5629
5737
  return self.read_range(max(0, self._total - max_bytes), max_bytes)[0]
5630
5738
 
5739
+ def last_line(self) -> str:
5740
+ """Última línea no vacía de la salida; de una barra de progreso que se reescribe con \\r, su último tramo."""
5741
+ for line in reversed(self.tail_text().split("\n")):
5742
+ text = line.rstrip("\r").rsplit("\r", 1)[-1].strip()
5743
+ if text:
5744
+ return text if len(text) <= LAST_LINE_MAX_CHARS else text[:LAST_LINE_MAX_CHARS - 1] + "…"
5745
+ return ""
5746
+
5631
5747
  # --- Estado -------------------------------------------------------------
5632
5748
 
5633
5749
  def elapsed(self) -> float:
@@ -5663,6 +5779,10 @@ class JobManager:
5663
5779
  self._lock = threading.Lock()
5664
5780
  self._dir: Path | None = None
5665
5781
  self._windows_job: _WindowsKillOnCloseJob | None = None
5782
+ # Avisa a check_command sin job_id de que ha terminado algún comando.
5783
+ self._finished = threading.Condition()
5784
+ # Esperas de check_command en curso, por la clave de su invocación: la persona puede cortarlas.
5785
+ self._waits: dict[str, threading.Event] = {}
5666
5786
  atexit.register(self.shutdown)
5667
5787
 
5668
5788
  def _session_dir(self) -> Path:
@@ -5703,6 +5823,16 @@ class JobManager:
5703
5823
  if key is not None and not (isinstance(key, str) and JOB_KEY_PATTERN.fullmatch(key)):
5704
5824
  key = None
5705
5825
  with self._lock:
5826
+ # Relanzar lo que ya está en marcha duplica el trabajo (dos envíos a la misma cola, dos
5827
+ # servidores en el mismo puerto): se sigue el que hay.
5828
+ same = next((job for job in self._jobs.values()
5829
+ if job.status == "running" and job.project == project.key and job.command.strip() == command.strip()), None)
5830
+ if same is not None:
5831
+ raise ValueError(
5832
+ f"This command is already running as job_id {same.id} (for {int(same.elapsed())} s). Do not run it again: "
5833
+ f"follow it with check_command(job_id={same.id}, wait_seconds=600), or stop it first with "
5834
+ f"check_command(job_id={same.id}, stop=true) if you really need a new run."
5835
+ )
5706
5836
  if sum(1 for job in self._jobs.values() if job.status == "running") >= MAX_RUNNING_JOBS:
5707
5837
  raise ValueError(
5708
5838
  f"Too many commands running ({MAX_RUNNING_JOBS}). "
@@ -5737,6 +5867,9 @@ class JobManager:
5737
5867
  stdout=subprocess.PIPE,
5738
5868
  # Una sola salida, en el orden en que la escribe el comando, como en una terminal.
5739
5869
  stderr=subprocess.STDOUT,
5870
+ # La salida va a un pipe, no a una terminal: sin esto Python la retiene en el búfer hasta salir
5871
+ # y ni la tarjeta, ni check_command, ni su pattern ven nada mientras el programa trabaja.
5872
+ env={**os.environ, "PYTHONUNBUFFERED": "1"},
5740
5873
  start_new_session=DETECTED_OS != "windows" and hasattr(os, "setsid")
5741
5874
  )
5742
5875
  if DETECTED_OS == "windows":
@@ -5780,14 +5913,45 @@ class JobManager:
5780
5913
  job.ended_mono = time.monotonic()
5781
5914
  job.ended_at = time.time()
5782
5915
  job.exit_code = returncode
5783
- if job.stop_reason == "timeout":
5784
- job.status = "timeout"
5785
- elif job.stop_reason:
5916
+ if job.stop_reason:
5786
5917
  job.status = "stopped"
5787
5918
  else:
5788
5919
  job.status = "exited"
5789
5920
  self._write_registry()
5790
5921
  job.done.set()
5922
+ job.notify_finished()
5923
+ with self._finished:
5924
+ self._finished.notify_all()
5925
+
5926
+ def wait_any_finished(self, jobs: list[CommandJob], timeout: float, cancel: threading.Event) -> list[CommandJob]:
5927
+ """Espera como mucho timeout segundos a que termine alguno de jobs o se corte la espera; devuelve los terminados."""
5928
+ with self._finished:
5929
+ self._finished.wait_for(lambda: cancel.is_set() or any(job.done.is_set() for job in jobs), timeout)
5930
+ return [job for job in jobs if job.done.is_set()]
5931
+
5932
+ def open_wait(self, key: str | None) -> threading.Event:
5933
+ """Registra una espera que se puede cortar con cancel_wait(key); sin clave no se puede cortar."""
5934
+ event = threading.Event()
5935
+ if key:
5936
+ with self._lock:
5937
+ self._waits[key] = event
5938
+ return event
5939
+
5940
+ def close_wait(self, key: str | None):
5941
+ if key:
5942
+ with self._lock:
5943
+ self._waits.pop(key, None)
5944
+
5945
+ def cancel_wait(self, key) -> bool:
5946
+ """Corta la espera de check_command con esa clave; devuelve si había una en curso."""
5947
+ with self._lock:
5948
+ event = self._waits.get(key) if isinstance(key, str) else None
5949
+ if event is None:
5950
+ return False
5951
+ event.set()
5952
+ with self._finished:
5953
+ self._finished.notify_all()
5954
+ return True
5791
5955
 
5792
5956
  def get(self, project: str, job_id=None, key=None) -> CommandJob | None:
5793
5957
  jobs = self.list(project)
@@ -5868,17 +6032,15 @@ def _clamp_seconds(value, default: int, minimum: int, maximum: int) -> int:
5868
6032
  return max(minimum, min(number, maximum))
5869
6033
 
5870
6034
 
5871
- def _job_result(job: CommandJob, note: str | None = None, output_field: str = "output") -> str:
6035
+ def _job_result(job: CommandJob, note: str | None = None, output_field: str = "output", extra: dict | None = None) -> str:
5872
6036
  """Resultado para el modelo con la salida que aún no ha visto."""
5873
6037
  start = job.model_cursor
5874
6038
  total = job.total
5875
6039
  output, truncated = truncate_terminal_output(job.output_since(start))
5876
6040
  job.model_cursor = total
5877
6041
  # Detener un comando a propósito no es un fallo; sí lo son salir con error o agotar el plazo.
5878
- failed = job.status == "timeout" or (job.status == "exited" and job.exit_code != 0)
6042
+ failed = job.status == "exited" and job.exit_code != 0
5879
6043
  result = {"success": not failed, "status": job.status, "job_id": job.id}
5880
- if job.status == "timeout":
5881
- result["error"] = f"Command timed out after {job.timeout_seconds} s and was killed."
5882
6044
  if job.status == "running":
5883
6045
  result["elapsed_s"] = job.elapsed()
5884
6046
  else:
@@ -5891,6 +6053,8 @@ def _job_result(job: CommandJob, note: str | None = None, output_field: str = "o
5891
6053
  result["log_file"] = str(job.log_path)
5892
6054
  if job.status == "stopped":
5893
6055
  result["stopped_by"] = job.stop_reason
6056
+ if extra:
6057
+ result.update(extra)
5894
6058
  if note:
5895
6059
  result["note"] = note
5896
6060
  return json.dumps(result, ensure_ascii=False, indent=2)
@@ -5905,33 +6069,121 @@ def run_command(command: str, timeout_seconds: int = COMMAND_DEFAULT_TIMEOUT, ba
5905
6069
  if background:
5906
6070
  if not job.done.wait(BACKGROUND_STARTUP_WAIT):
5907
6071
  return _job_result(job, note=(
5908
- f"Running in background. Follow it with check_command(job_id={job.id}, wait_seconds=...) "
5909
- f"and stop it with check_command(job_id={job.id}, stop=true)."
6072
+ f"Running in background. Follow it with check_command(job_id={job.id}, wait_seconds=600, pattern='error|Traceback'), "
6073
+ f"which returns when it finishes, prints an error or after 600 s, and stop it with check_command(job_id={job.id}, stop=true)."
5910
6074
  ))
5911
6075
  return _job_result(job)
5912
6076
  timeout = _clamp_seconds(timeout_seconds, COMMAND_DEFAULT_TIMEOUT, 1, COMMAND_MAX_TIMEOUT)
5913
6077
  if not job.done.wait(timeout):
5914
- job.timeout_seconds = timeout
5915
- JOBS.stop(job, "timeout")
6078
+ # No se mata: lo hecho no se pierde y relanzarlo no lo duplica.
6079
+ job.background = True
5916
6080
  return _job_result(job, note=(
5917
- f"Killed after {timeout} s. If this command is expected to take longer, re-run it with "
5918
- f"a larger timeout_seconds (max {COMMAND_MAX_TIMEOUT}) or with background=true."
6081
+ f"Still running after {timeout} s, so it was moved to the background instead of being killed. "
6082
+ f"Do not run it again. Follow it with check_command(job_id={job.id}, wait_seconds=600) "
6083
+ f"and stop it with check_command(job_id={job.id}, stop=true)."
5919
6084
  ))
5920
6085
  return _job_result(job)
5921
6086
 
5922
6087
 
5923
- def check_command(job_id: int, wait_seconds: int = 0, stop: bool = False, *, ctx: SecurityContext) -> str:
5924
- """Estado y salida nueva de un comando lanzado por run_command; puede esperarlo o detenerlo."""
6088
+ def _wait_job(job: CommandJob, wait: float, regex: re.Pattern | None, cancel: threading.Event) -> tuple[str, str | None]:
6089
+ """Espera a que termine el comando, a que una línea nueva de su salida cumpla regex o a que pase wait.
6090
+
6091
+ Recorre la salida que el modelo aún no ha visto, línea a línea; la última línea, si no está completa,
6092
+ solo se compara cuando el comando termina. Devuelve el motivo y la línea que coincidió.
6093
+ """
6094
+ deadline = time.monotonic() + wait
6095
+ pos = job.model_cursor
6096
+ partial = ""
6097
+ while True:
6098
+ finished = job.done.is_set()
6099
+ total = job.total
6100
+ if regex is not None and total > pos:
6101
+ text, pos = job.read_range(pos, total - pos)
6102
+ lines = (partial + text).split("\n")
6103
+ partial = lines.pop()
6104
+ for line in lines:
6105
+ if regex.search(line):
6106
+ return "pattern_matched", line
6107
+ if finished and (regex is None or pos >= job.total):
6108
+ if regex is not None and partial and regex.search(partial):
6109
+ return "pattern_matched", partial
6110
+ return "command_finished", None
6111
+ if cancel.is_set():
6112
+ return "wait_ended_by_user", None
6113
+ remaining = deadline - time.monotonic()
6114
+ if remaining <= 0:
6115
+ return "wait_elapsed", None
6116
+ if regex is None:
6117
+ job.done.wait(min(remaining, WAIT_SLICE_SECONDS))
6118
+ else:
6119
+ job.wait_change(pos, min(remaining, WAIT_SLICE_SECONDS))
6120
+
6121
+
6122
+ def _plain_wait(wait_seconds, cancel: threading.Event, ctx: SecurityContext) -> str:
6123
+ """check_command sin job_id: espera sin lanzar ningún proceso; vuelve antes si termina un comando del proyecto."""
6124
+ wait = _clamp_seconds(wait_seconds, 0, 0, COMMAND_MAX_WAIT)
6125
+ if not wait:
6126
+ return _tool_error(f"Without job_id, check_command waits: give wait_seconds (1 to {COMMAND_MAX_WAIT}).", os=DETECTED_OS)
6127
+ running = JOBS.running(ctx.key)
6128
+ started = time.monotonic()
6129
+ finished = JOBS.wait_any_finished(running, wait, cancel)
6130
+ reason = "command_finished" if finished else ("wait_ended_by_user" if cancel.is_set() else "wait_elapsed")
6131
+ result = {
6132
+ "success": True,
6133
+ "waited_s": round(time.monotonic() - started, 1),
6134
+ "returned_because": reason,
6135
+ }
6136
+ if finished:
6137
+ result["finished_jobs"] = [
6138
+ {"job_id": job.id, "command": job.command.split("\n")[0][:200], "status": job.status, "exit_code": job.exit_code}
6139
+ for job in finished
6140
+ ]
6141
+ result["note"] = "Read their output with check_command(job_id=...)."
6142
+ return json.dumps(result, ensure_ascii=False, indent=2)
6143
+
6144
+
6145
+ def check_command(job_id: int | None = None, wait_seconds: int = 0, stop: bool = False, pattern: str | None = None,
6146
+ job_key: str | None = None, *, ctx: SecurityContext) -> str:
6147
+ """Estado y salida nueva de un comando lanzado por run_command; puede esperarlo, con un patrón, o detenerlo.
6148
+ Sin job_id, solo espera. La persona puede cortar la espera con zerochat/jobs/end_wait y la clave de la invocación."""
6149
+ if job_id is None:
6150
+ if stop or pattern:
6151
+ return _tool_error("stop and pattern need the job_id of a command.", os=DETECTED_OS)
6152
+ cancel = JOBS.open_wait(job_key)
6153
+ try:
6154
+ return _plain_wait(wait_seconds, cancel, ctx)
6155
+ finally:
6156
+ JOBS.close_wait(job_key)
5925
6157
  job = JOBS.get(ctx.key, job_id=job_id)
5926
6158
  if job is None:
5927
6159
  return _tool_error(f"Unknown job_id {job_id}. It may belong to a previous ZeroChat session or to another project.", os=DETECTED_OS)
6160
+ regex = None
6161
+ if pattern:
6162
+ try:
6163
+ regex = re.compile(pattern, re.IGNORECASE)
6164
+ except re.error as exc:
6165
+ return _tool_error(f"Invalid pattern: {exc}. Use a regular expression such as 'error|listening on'.", os=DETECTED_OS)
5928
6166
  if stop:
5929
6167
  JOBS.stop(job, "model")
5930
- else:
5931
- wait = _clamp_seconds(wait_seconds, 0, 0, COMMAND_MAX_WAIT)
5932
- if wait:
5933
- job.done.wait(wait)
5934
- return _job_result(job, output_field="new_output")
6168
+ return _job_result(job, output_field="new_output")
6169
+ wait = _clamp_seconds(wait_seconds, 0, 0, COMMAND_MAX_WAIT)
6170
+ if not wait and regex is None:
6171
+ return _job_result(job, output_field="new_output")
6172
+ cancel = JOBS.open_wait(job_key)
6173
+ started = time.monotonic()
6174
+ try:
6175
+ reason, line = _wait_job(job, wait, regex, cancel)
6176
+ finally:
6177
+ JOBS.close_wait(job_key)
6178
+ extra = {"returned_because": reason, "waited_s": round(time.monotonic() - started, 1)}
6179
+ if reason == "wait_elapsed" and job.total == job.model_cursor and not job.done.is_set():
6180
+ extra["note"] = (
6181
+ "No new output while waiting. The command may still be working without printing, or write its progress "
6182
+ "to a log file: read that file with read_file. It is still running: wait again or check that file."
6183
+ )
6184
+ if line is not None:
6185
+ extra["matched_line"] = line if len(line) <= MATCHED_LINE_MAX_CHARS else line[:MATCHED_LINE_MAX_CHARS] + "…"
6186
+ return _job_result(job, output_field="new_output", extra=extra)
5935
6187
 
5936
6188
 
5937
6189
  def job_details(job: CommandJob) -> dict:
@@ -6582,7 +6834,7 @@ def live_state(ctx: SecurityContext, focus_conversation_id: str | None = None) -
6582
6834
  """
6583
6835
  Estado del servidor que la interfaz sigue en vivo, en initialize y en cada zerochat/heartbeat:
6584
6836
  cwd, el proyecto de la pestaña que pregunta (su cabecera X-ZeroChat-Project); jobs, los comandos en
6585
- marcha, para mostrarlos y avisar antes de cerrar si se detendrían; exit_on_close; playwright, si
6837
+ marcha con su última línea de salida, para mostrarlos y avisar antes de cerrar si se detendrían; exit_on_close; playwright, si
6586
6838
  se puede navegar aunque se haya instalado o quitado durante la sesión; servers, los servicios
6587
6839
  MCP externos aunque otra pestaña los cambie o su proceso muera; runs, lista ligera de ejecuciones
6588
6840
  en segundo plano; y focus_run, estado detallado de la ejecución enfocada por el usuario.
@@ -6590,7 +6842,7 @@ def live_state(ctx: SecurityContext, focus_conversation_id: str | None = None) -
6590
6842
  runs, focus_run = list_server_runs(focus_conversation_id)
6591
6843
  return {
6592
6844
  "cwd": str(ctx.workspace_dir),
6593
- "jobs": [job.summary() for job in JOBS.running(ctx.key)],
6845
+ "jobs": [{**job.summary(), "last_line": job.last_line()} for job in JOBS.running(ctx.key)],
6594
6846
  "exit_on_close": EXIT_ON_CLOSE,
6595
6847
  "playwright": playwright_status(),
6596
6848
  "servers": GLOBAL_MCP_MANAGER.list_servers(),
@@ -6743,6 +6995,143 @@ class ConsoleControl:
6743
6995
  return
6744
6996
  self._handle_command(line)
6745
6997
 
6998
+ # --- tools.project_files ---
6999
+ """Navegador de ficheros del proyecto para la interfaz: lista, lee y descarga sin salir de su carpeta.
7000
+
7001
+ Lo usa la persona, no el modelo: lo limita la carpeta del proyecto de la petición, no el motor de permisos.
7002
+ """
7003
+
7004
+
7005
+
7006
+
7007
+ # Entradas de una carpeta en una respuesta: una carpeta con más (node_modules) avisa de las que faltan.
7008
+ MAX_LIST_ENTRIES = 2000
7009
+ # Bytes del comienzo que deciden si un fichero es texto: un byte nulo o un UTF-8 no válido lo hacen binario.
7010
+ TEXT_SNIFF_BYTES = 8192
7011
+ # Un texto más grande no se abre en una pestaña: se descarga.
7012
+ MAX_TEXT_VIEW_BYTES = 2 * 1024 * 1024
7013
+ DOWNLOAD_PAGE_BYTES = 512 * 1024
7014
+ MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024
7015
+
7016
+
7017
+ def _project_root(ctx: SecurityContext) -> Path:
7018
+ return ctx.workspace_dir.resolve()
7019
+
7020
+
7021
+ def _inside(ctx: SecurityContext, path) -> tuple[Path, Path]:
7022
+ """La ruta pedida, resuelta con sus enlaces simbólicos, y la raíz; ValueError si sale de la carpeta del proyecto."""
7023
+ root = _project_root(ctx)
7024
+ if path in (None, ""):
7025
+ return root, root
7026
+ if not isinstance(path, str):
7027
+ raise ValueError("path debe ser una cadena.")
7028
+ target = ctx.absolute(path)
7029
+ if target != root and root not in target.parents:
7030
+ raise ValueError("La ruta queda fuera de la carpeta del proyecto.")
7031
+ return target, root
7032
+
7033
+
7034
+ def _relative(target: Path, root: Path) -> str:
7035
+ return "" if target == root else target.relative_to(root).as_posix()
7036
+
7037
+
7038
+ def list_project_dir(params: dict, ctx: SecurityContext) -> dict:
7039
+ """Carpetas primero y después ficheros, por nombre, con su tamaño y fecha; como mucho MAX_LIST_ENTRIES."""
7040
+ target, root = _inside(ctx, params.get("path"))
7041
+ if not target.is_dir():
7042
+ raise ValueError("La carpeta no existe.")
7043
+ entries = []
7044
+ with os.scandir(target) as items:
7045
+ for item in items:
7046
+ try:
7047
+ is_dir = item.is_dir()
7048
+ info = item.stat()
7049
+ except OSError:
7050
+ continue
7051
+ entries.append({
7052
+ "name": item.name,
7053
+ "type": "dir" if is_dir else "file",
7054
+ "size": None if is_dir else info.st_size,
7055
+ "modified": int(info.st_mtime * 1000),
7056
+ })
7057
+ entries.sort(key=lambda entry: (entry["type"] != "dir", entry["name"].lower(), entry["name"]))
7058
+ return {
7059
+ "path": _relative(target, root),
7060
+ "entries": entries[:MAX_LIST_ENTRIES],
7061
+ "total": len(entries),
7062
+ "truncated": len(entries) > MAX_LIST_ENTRIES,
7063
+ }
7064
+
7065
+
7066
+ def _regular_file(params: dict, ctx: SecurityContext) -> tuple[Path, Path]:
7067
+ target, root = _inside(ctx, params.get("path"))
7068
+ if not target.is_file():
7069
+ raise ValueError("El fichero no existe.")
7070
+ return target, root
7071
+
7072
+
7073
+ def read_project_file(params: dict, ctx: SecurityContext) -> dict:
7074
+ """El texto de un fichero, o que es binario o demasiado grande para abrirlo (entonces se descarga)."""
7075
+ target, root = _regular_file(params, ctx)
7076
+ size = target.stat().st_size
7077
+ result = {"path": _relative(target, root), "size": size}
7078
+ with open(target, "rb") as handle:
7079
+ head = handle.read(TEXT_SNIFF_BYTES)
7080
+ try:
7081
+ # Incremental: un carácter de varios bytes cortado al final del comienzo no lo hace binario.
7082
+ codecs.getincrementaldecoder("utf-8")().decode(head, final=len(head) == size)
7083
+ except UnicodeDecodeError:
7084
+ return {**result, "binary": True}
7085
+ if b"\0" in head:
7086
+ return {**result, "binary": True}
7087
+ if size > MAX_TEXT_VIEW_BYTES:
7088
+ return {**result, "binary": False, "too_large": True}
7089
+ try:
7090
+ text = target.read_bytes().decode("utf-8")
7091
+ except UnicodeDecodeError:
7092
+ return {**result, "binary": True}
7093
+ return {**result, "binary": False, "text": text}
7094
+
7095
+
7096
+ def download_project_file(params: dict, ctx: SecurityContext) -> dict:
7097
+ """Una página del fichero en base64 desde offset; la interfaz las pide hasta done."""
7098
+ target, root = _regular_file(params, ctx)
7099
+ size = target.stat().st_size
7100
+ if size > MAX_DOWNLOAD_BYTES:
7101
+ raise ValueError(f"El fichero ocupa más de {MAX_DOWNLOAD_BYTES // (1024 * 1024)} MB y no se descarga desde aquí.")
7102
+ offset = params.get("offset", 0)
7103
+ if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0 or offset > size:
7104
+ raise ValueError("offset debe ser un entero entre 0 y el tamaño del fichero.")
7105
+ with open(target, "rb") as handle:
7106
+ handle.seek(offset)
7107
+ chunk = handle.read(DOWNLOAD_PAGE_BYTES)
7108
+ following = offset + len(chunk)
7109
+ return {
7110
+ "path": _relative(target, root),
7111
+ "name": target.name,
7112
+ "size": size,
7113
+ "data": base64.b64encode(chunk).decode("ascii"),
7114
+ "next": following,
7115
+ "done": following >= size,
7116
+ }
7117
+
7118
+
7119
+ def dispatch_files(method: str, params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | None, str]:
7120
+ """zerochat/files/list, zerochat/files/read y zerochat/files/download sobre la carpeta del proyecto."""
7121
+ params = params if isinstance(params, dict) else {}
7122
+ handlers = {
7123
+ "zerochat/files/list": list_project_dir,
7124
+ "zerochat/files/read": read_project_file,
7125
+ "zerochat/files/download": download_project_file,
7126
+ }
7127
+ handler = handlers.get(method)
7128
+ if handler is None:
7129
+ return None, {"code": -32601, "message": f"Método '{method}' no soportado."}, ""
7130
+ try:
7131
+ return handler(params, ctx), None, ""
7132
+ except (ValueError, OSError) as exc:
7133
+ return None, {"code": -32602, "message": str(exc)}, str(exc)
7134
+
6746
7135
  # --- tools.registry ---
6747
7136
  """Registro de las herramientas locales: definiciones publicadas al modelo, manejadores y validación de argumentos contra su esquema."""
6748
7137
 
@@ -6762,7 +7151,7 @@ LOCAL_TOOLS_DEFINITIONS = [
6762
7151
  },
6763
7152
  {
6764
7153
  "name": "read_file",
6765
- "description": "Read a text file, whole or by line range.",
7154
+ "description": "Read a text file, whole or by line range, or only its last lines with tail_lines (like tail -n): use tail_lines for logs that keep growing.",
6766
7155
  "inputSchema": {
6767
7156
  "type": "object",
6768
7157
  "properties": {
@@ -6770,7 +7159,11 @@ LOCAL_TOOLS_DEFINITIONS = [
6770
7159
  "start_line": {"type": "integer", "description": "First line (1-based)", "default": 1},
6771
7160
  "end_line": {"type": "integer", "description": "Last line (inclusive)"},
6772
7161
  "max_lines": {"type": "integer", "description": "Line cap if no end_line", "default": 500},
6773
- "max_bytes": {"type": "integer", "description": "Byte cap", "default": 100000}
7162
+ "max_bytes": {"type": "integer", "description": "Byte cap", "default": 100000},
7163
+ "tail_lines": {
7164
+ "type": "integer",
7165
+ "description": "Return only the last N lines (max 2000), without terminal color codes and keeping the last state of progress bars; start_line and end_line are ignored"
7166
+ }
6774
7167
  },
6775
7168
  "required": ["path"]
6776
7169
  }
@@ -6831,9 +7224,11 @@ LOCAL_TOOLS_DEFINITIONS = [
6831
7224
  "Each call starts a fresh shell in the project directory: cd, export or source/activate do not carry over to later calls, "
6832
7225
  "so chain them with && in the same command. "
6833
7226
  ) + (
6834
- "By default it waits up to timeout_seconds and kills the command if it has not finished. "
6835
- "Use background=true for servers, watchers or anything that does not finish on its own; "
6836
- f"then follow or stop it with check_command. Host OS: {DETECTED_OS}."
7227
+ "It waits up to timeout_seconds; a command still running then is not killed: it keeps running in the background "
7228
+ "and the result gives its job_id. "
7229
+ "Use background=true from the start for anything that takes minutes (generations, builds, training, long test suites) "
7230
+ "and for servers or watchers that do not finish on its own; then follow it with check_command. "
7231
+ f"Never run a command again while it is still running. Host OS: {DETECTED_OS}."
6837
7232
  ),
6838
7233
  "inputSchema": {
6839
7234
  "type": "object",
@@ -6847,7 +7242,7 @@ LOCAL_TOOLS_DEFINITIONS = [
6847
7242
  else "Shell command to run (e.g. git status, npm test)"
6848
7243
  )
6849
7244
  },
6850
- "timeout_seconds": {"type": "integer", "description": f"Seconds to wait before killing the command (default {COMMAND_DEFAULT_TIMEOUT}, max {COMMAND_MAX_TIMEOUT}). Ignored with background=true.", "default": COMMAND_DEFAULT_TIMEOUT},
7245
+ "timeout_seconds": {"type": "integer", "description": f"Seconds to wait for the command before moving it to the background (default {COMMAND_DEFAULT_TIMEOUT}, max {COMMAND_MAX_TIMEOUT}). Ignored with background=true.", "default": COMMAND_DEFAULT_TIMEOUT},
6851
7246
  "background": {"type": "boolean", "description": "Return after a few seconds and keep the command running; returns a job_id for check_command.", "default": False}
6852
7247
  },
6853
7248
  "required": ["command"]
@@ -6855,15 +7250,27 @@ LOCAL_TOOLS_DEFINITIONS = [
6855
7250
  },
6856
7251
  {
6857
7252
  "name": "check_command",
6858
- "description": "Check a command started by run_command: returns its status and the output produced since the last check. Use wait_seconds to wait for it to finish, or stop=true to terminate it.",
7253
+ "description": (
7254
+ "Check a command started by run_command: returns its status and the output produced since the last check. "
7255
+ "Use wait_seconds to wait for it to finish, add pattern to return as soon as a new output line matches it, "
7256
+ "or stop=true to terminate it. Example: check_command(job_id=4, wait_seconds=600, pattern='error|Traceback') "
7257
+ "returns when the command finishes, prints an error, or after 600 s. To follow a long command until it finishes "
7258
+ "(also when the user asks to be told when it ends), call it again with wait_seconds=600 each time it returns still running. "
7259
+ "Without job_id it just waits wait_seconds, with no shell, and returns early if a background command finishes: "
7260
+ "use it instead of sleep."
7261
+ ),
6859
7262
  "inputSchema": {
6860
7263
  "type": "object",
6861
7264
  "properties": {
6862
- "job_id": {"type": "integer", "description": "job_id returned by run_command"},
7265
+ "job_id": {"type": "integer", "description": "job_id returned by run_command; omit it to just wait"},
6863
7266
  "wait_seconds": {"type": "integer", "description": f"Seconds to wait for the command to finish before returning (default 0, max {COMMAND_MAX_WAIT})", "default": 0},
6864
- "stop": {"type": "boolean", "description": "Terminate the command and its child processes", "default": False}
6865
- },
6866
- "required": ["job_id"]
7267
+ "stop": {"type": "boolean", "description": "Terminate the command and its child processes", "default": False},
7268
+ "pattern": {
7269
+ "type": "string",
7270
+ "maxLength": CHECK_PATTERN_MAX_CHARS,
7271
+ "description": "Case-insensitive regular expression matched against each new output line; with wait_seconds, returns as soon as a line matches"
7272
+ }
7273
+ }
6867
7274
  }
6868
7275
  },
6869
7276
  {
@@ -7395,8 +7802,8 @@ def run_supervisor(server: ThreadingHTTPServer, session: RunSession, runner_proc
7395
7802
  return
7396
7803
  if proc is not None and proc.poll() is not None and not session.finished.wait(0.2):
7397
7804
  break
7398
- if time.monotonic() >= deadline:
7399
- session.stop_reason = f"Plazo total agotado ({RUN_TOTAL_TIMEOUT:.0f}s)."
7805
+ if time.monotonic() >= deadline + session.waited_seconds():
7806
+ session.stop_reason = f"Plazo total agotado ({RUN_TOTAL_TIMEOUT:.0f}s, sin contar las esperas)."
7400
7807
  break
7401
7808
  if session.idle_seconds() > RUN_IDLE_SECONDS:
7402
7809
  session.stop_reason = f"Sin progreso de la interfaz durante {RUN_IDLE_SECONDS:.0f}s."
@@ -7623,9 +8030,10 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
7623
8030
  except ValueError:
7624
8031
  return False
7625
8032
 
7626
- # Whitelist de archivos y carpetas autorizados para servir la interfaz web
8033
+ # Whitelist de archivos y carpetas autorizados para servir la interfaz web: sus dos páginas
8034
+ # (el chat y el navegador de ficheros del proyecto) y sus recursos.
7627
8035
  is_allowed_static = (
7628
- clean_rel == "zerochat.html" or
8036
+ clean_rel in ("zerochat.html", "files.html") or
7629
8037
  clean_rel in ("manifest.webmanifest", "sw.js", "favicon.ico") or
7630
8038
  clean_rel.startswith("js/") or
7631
8039
  clean_rel.startswith("css/") or
@@ -7857,9 +8265,15 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
7857
8265
  message = (f"The browser is in use by another conversation. It is released after {int(BROWSER_LEASE_IDLE_SECONDS)} "
7858
8266
  "seconds without use; tell the user or try again later.")
7859
8267
  return {"content": [{"type": "text", "text": _tool_error(message)}], "isError": True}, None, message
8268
+ # En una ejecución desatendida, esperar en check_command no es inactividad ni gasta el plazo total.
8269
+ session = current_run_session() if origin == "local" and tool_name == JOB_CONTROL_TOOL else None
8270
+ if session is not None:
8271
+ session.begin_wait()
7860
8272
  try:
7861
8273
  return cls._run_tool(origin, tool_name, args, ctx)
7862
8274
  finally:
8275
+ if session is not None:
8276
+ session.end_wait()
7863
8277
  # El plazo cuenta desde que la acción termina: lo que tarde no acorta lo que el modelo puede razonar después.
7864
8278
  if browser:
7865
8279
  BROWSER_LEASES.acquire(browser, conversation_id)
@@ -8020,6 +8434,8 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
8020
8434
  return None, {"code": -32603, "message": f"Error en sandbox JS: {exc}"}, str(exc)
8021
8435
  if method.startswith("zerochat/jobs/"):
8022
8436
  return self._dispatch_jobs(method, params, ctx)
8437
+ if method.startswith("zerochat/files/"):
8438
+ return dispatch_files(method, params, ctx)
8023
8439
  if method.startswith("zerochat/run/"):
8024
8440
  return dispatch_run(method, params, ctx)
8025
8441
  if method in ("zerochat/external/servers/start", "zerochat/external/servers/stop", "zerochat/external/servers/configure"):
@@ -8239,6 +8655,8 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
8239
8655
  if not isinstance(ids, list) or len(ids) > 100 or any(isinstance(i, bool) or not isinstance(i, int) for i in ids):
8240
8656
  return None, {"code": -32602, "message": "ids debe ser una lista de hasta 100 enteros."}, ""
8241
8657
  return {"reports": JOBS.report_finished(ids, project)}, None, ""
8658
+ if method == "zerochat/jobs/end_wait":
8659
+ return {"ended": JOBS.cancel_wait(params.get("key"))}, None, ""
8242
8660
  job = JOBS.get(project, job_id=params.get("id"), key=params.get("key"))
8243
8661
  if method in ("zerochat/jobs/get", "zerochat/jobs/log", "zerochat/jobs/stop") and job is None:
8244
8662
  return None, {"code": -32602, "message": "Comando no encontrado: puede pertenecer a una sesión anterior de ZeroChat."}, ""
File without changes
File without changes
File without changes