zerochat 10.16.0__tar.gz → 10.17.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.17.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.17.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.17.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
@@ -1381,7 +1381,7 @@ def _pid_alive(pid: int) -> bool:
1381
1381
 
1382
1382
 
1383
1383
 
1384
- SOURCE_BACKEND_VERSION = "10.16.0"
1384
+ SOURCE_BACKEND_VERSION = "10.17.0"
1385
1385
 
1386
1386
 
1387
1387
  def _read_source_version(filename: str) -> str | None:
@@ -3371,7 +3371,7 @@ def update_security_policy_data(mutator: typing.Callable[[dict | None], dict]) -
3371
3371
 
3372
3372
  # Plazo total y sin progreso de la interfaz.
3373
3373
  RUN_TOTAL_TIMEOUT = 900.0
3374
- RUN_IDLE_SECONDS = 180.0
3374
+ RUN_IDLE_SECONDS = 600.0
3375
3375
  RUN_POLL_SECONDS = 0.2
3376
3376
  RUN_PROGRESS_TEXT_MAX = 500
3377
3377
  RUN_STREAM_TEXT_MAX = 8000
@@ -3647,6 +3647,9 @@ class RunSession:
3647
3647
  self.tool_security = None
3648
3648
  self.lock = threading.Lock()
3649
3649
  self.last_activity = time.monotonic()
3650
+ # Esperas de check_command: no cuentan como inactividad y alargan el plazo total.
3651
+ self._waiting_since: float | None = None
3652
+ self._waited = 0.0
3650
3653
  self.prompt_delivered = False
3651
3654
  self.result: dict | None = None
3652
3655
  self.stop_reason: str | None = None
@@ -3671,8 +3674,28 @@ class RunSession:
3671
3674
 
3672
3675
  def idle_seconds(self) -> float:
3673
3676
  with self.lock:
3677
+ if self._waiting_since is not None:
3678
+ return 0.0
3674
3679
  return time.monotonic() - self.last_activity
3675
3680
 
3681
+ def begin_wait(self):
3682
+ with self.lock:
3683
+ self._waiting_since = time.monotonic()
3684
+
3685
+ def end_wait(self):
3686
+ with self.lock:
3687
+ now = time.monotonic()
3688
+ if self._waiting_since is not None:
3689
+ self._waited += now - self._waiting_since
3690
+ self._waiting_since = None
3691
+ self.last_activity = now
3692
+
3693
+ def waited_seconds(self) -> float:
3694
+ """Tiempo total en esperas de check_command, incluida la que esté en curso."""
3695
+ with self.lock:
3696
+ ongoing = time.monotonic() - self._waiting_since if self._waiting_since is not None else 0.0
3697
+ return self._waited + ongoing
3698
+
3676
3699
 
3677
3700
  RUN_SESSION: RunSession | None = None
3678
3701
 
@@ -3977,6 +4000,9 @@ try {
3977
4000
  if (req.url && req.url !== page.url()) {
3978
4001
  await page.goto(req.url, { waitUntil: 'domcontentloaded', timeout: 30000 });
3979
4002
  }
4003
+ // Con la máquina cargada, Chromium puede no haber pintado aún ningún fotograma:
4004
+ // esperar dos fotogramas garantiza que hay algo que capturar.
4005
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
3980
4006
  const buf = await page.screenshot({ fullPage: false });
3981
4007
  console.log(JSON.stringify({
3982
4008
  success: true,
@@ -5310,6 +5336,13 @@ MODEL_OUTPUT_READ_BYTES = 64 * 1024
5310
5336
  CARD_TAIL_BYTES = 2048
5311
5337
  JOB_LOG_PAGE_BYTES = 256 * 1024
5312
5338
  REPORT_TAIL_LINES = 20
5339
+ # check_command(pattern): longitud máxima de la expresión y de la línea que se devuelve al coincidir.
5340
+ CHECK_PATTERN_MAX_CHARS = 200
5341
+ MATCHED_LINE_MAX_CHARS = 500
5342
+ # Última línea de salida de cada comando en marcha en el latido, para su tarjeta plegada.
5343
+ LAST_LINE_MAX_CHARS = 200
5344
+ # Cada cuánto comprueba una espera de check_command si la persona la ha cortado.
5345
+ WAIT_SLICE_SECONDS = 0.25
5313
5346
  REPORT_TAIL_BYTES = 4096
5314
5347
 
5315
5348
 
@@ -5512,6 +5545,8 @@ class CommandJob:
5512
5545
  self.runner_path: Path | None = None
5513
5546
  self.done = threading.Event()
5514
5547
  self._lock = threading.Lock()
5548
+ # Avisa a quien espera en check_command de que hay salida nueva o de que el comando terminó.
5549
+ self._changed = threading.Condition(self._lock)
5515
5550
  self._log = open(log_path, "wb")
5516
5551
  self._head_len = 0
5517
5552
  self._tail = bytearray()
@@ -5540,6 +5575,7 @@ class CommandJob:
5540
5575
  if overflow > 0:
5541
5576
  del self._tail[:overflow]
5542
5577
  self._tail_start += overflow
5578
+ self._changed.notify_all()
5543
5579
 
5544
5580
  def _read_output(self, stream):
5545
5581
  try:
@@ -5625,9 +5661,26 @@ class CommandJob:
5625
5661
  omitted = total - start - 2 * MODEL_OUTPUT_READ_BYTES
5626
5662
  return head + f"\n[... {omitted} bytes omitted ...]\n" + tail
5627
5663
 
5664
+ def wait_change(self, seen_total: int, timeout: float):
5665
+ """Espera como mucho timeout segundos a que haya salida más allá de seen_total o a que el comando termine."""
5666
+ with self._changed:
5667
+ self._changed.wait_for(lambda: self._total > seen_total or self.done.is_set(), timeout)
5668
+
5669
+ def notify_finished(self):
5670
+ with self._changed:
5671
+ self._changed.notify_all()
5672
+
5628
5673
  def tail_text(self, max_bytes: int = CARD_TAIL_BYTES) -> str:
5629
5674
  return self.read_range(max(0, self._total - max_bytes), max_bytes)[0]
5630
5675
 
5676
+ def last_line(self) -> str:
5677
+ """Última línea no vacía de la salida; de una barra de progreso que se reescribe con \\r, su último tramo."""
5678
+ for line in reversed(self.tail_text().split("\n")):
5679
+ text = line.rstrip("\r").rsplit("\r", 1)[-1].strip()
5680
+ if text:
5681
+ return text if len(text) <= LAST_LINE_MAX_CHARS else text[:LAST_LINE_MAX_CHARS - 1] + "…"
5682
+ return ""
5683
+
5631
5684
  # --- Estado -------------------------------------------------------------
5632
5685
 
5633
5686
  def elapsed(self) -> float:
@@ -5663,6 +5716,10 @@ class JobManager:
5663
5716
  self._lock = threading.Lock()
5664
5717
  self._dir: Path | None = None
5665
5718
  self._windows_job: _WindowsKillOnCloseJob | None = None
5719
+ # Avisa a check_command sin job_id de que ha terminado algún comando.
5720
+ self._finished = threading.Condition()
5721
+ # Esperas de check_command en curso, por la clave de su invocación: la persona puede cortarlas.
5722
+ self._waits: dict[str, threading.Event] = {}
5666
5723
  atexit.register(self.shutdown)
5667
5724
 
5668
5725
  def _session_dir(self) -> Path:
@@ -5788,6 +5845,39 @@ class JobManager:
5788
5845
  job.status = "exited"
5789
5846
  self._write_registry()
5790
5847
  job.done.set()
5848
+ job.notify_finished()
5849
+ with self._finished:
5850
+ self._finished.notify_all()
5851
+
5852
+ def wait_any_finished(self, jobs: list[CommandJob], timeout: float, cancel: threading.Event) -> list[CommandJob]:
5853
+ """Espera como mucho timeout segundos a que termine alguno de jobs o se corte la espera; devuelve los terminados."""
5854
+ with self._finished:
5855
+ self._finished.wait_for(lambda: cancel.is_set() or any(job.done.is_set() for job in jobs), timeout)
5856
+ return [job for job in jobs if job.done.is_set()]
5857
+
5858
+ def open_wait(self, key: str | None) -> threading.Event:
5859
+ """Registra una espera que se puede cortar con cancel_wait(key); sin clave no se puede cortar."""
5860
+ event = threading.Event()
5861
+ if key:
5862
+ with self._lock:
5863
+ self._waits[key] = event
5864
+ return event
5865
+
5866
+ def close_wait(self, key: str | None):
5867
+ if key:
5868
+ with self._lock:
5869
+ self._waits.pop(key, None)
5870
+
5871
+ def cancel_wait(self, key) -> bool:
5872
+ """Corta la espera de check_command con esa clave; devuelve si había una en curso."""
5873
+ with self._lock:
5874
+ event = self._waits.get(key) if isinstance(key, str) else None
5875
+ if event is None:
5876
+ return False
5877
+ event.set()
5878
+ with self._finished:
5879
+ self._finished.notify_all()
5880
+ return True
5791
5881
 
5792
5882
  def get(self, project: str, job_id=None, key=None) -> CommandJob | None:
5793
5883
  jobs = self.list(project)
@@ -5868,7 +5958,7 @@ def _clamp_seconds(value, default: int, minimum: int, maximum: int) -> int:
5868
5958
  return max(minimum, min(number, maximum))
5869
5959
 
5870
5960
 
5871
- def _job_result(job: CommandJob, note: str | None = None, output_field: str = "output") -> str:
5961
+ def _job_result(job: CommandJob, note: str | None = None, output_field: str = "output", extra: dict | None = None) -> str:
5872
5962
  """Resultado para el modelo con la salida que aún no ha visto."""
5873
5963
  start = job.model_cursor
5874
5964
  total = job.total
@@ -5891,6 +5981,8 @@ def _job_result(job: CommandJob, note: str | None = None, output_field: str = "o
5891
5981
  result["log_file"] = str(job.log_path)
5892
5982
  if job.status == "stopped":
5893
5983
  result["stopped_by"] = job.stop_reason
5984
+ if extra:
5985
+ result.update(extra)
5894
5986
  if note:
5895
5987
  result["note"] = note
5896
5988
  return json.dumps(result, ensure_ascii=False, indent=2)
@@ -5920,18 +6012,100 @@ def run_command(command: str, timeout_seconds: int = COMMAND_DEFAULT_TIMEOUT, ba
5920
6012
  return _job_result(job)
5921
6013
 
5922
6014
 
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."""
6015
+ def _wait_job(job: CommandJob, wait: float, regex: re.Pattern | None, cancel: threading.Event) -> tuple[str, str | None]:
6016
+ """Espera a que termine el comando, a que una línea nueva de su salida cumpla regex o a que pase wait.
6017
+
6018
+ Recorre la salida que el modelo aún no ha visto, línea a línea; la última línea, si no está completa,
6019
+ solo se compara cuando el comando termina. Devuelve el motivo y la línea que coincidió.
6020
+ """
6021
+ deadline = time.monotonic() + wait
6022
+ pos = job.model_cursor
6023
+ partial = ""
6024
+ while True:
6025
+ finished = job.done.is_set()
6026
+ total = job.total
6027
+ if regex is not None and total > pos:
6028
+ text, pos = job.read_range(pos, total - pos)
6029
+ lines = (partial + text).split("\n")
6030
+ partial = lines.pop()
6031
+ for line in lines:
6032
+ if regex.search(line):
6033
+ return "pattern_matched", line
6034
+ if finished and (regex is None or pos >= job.total):
6035
+ if regex is not None and partial and regex.search(partial):
6036
+ return "pattern_matched", partial
6037
+ return "command_finished", None
6038
+ if cancel.is_set():
6039
+ return "wait_ended_by_user", None
6040
+ remaining = deadline - time.monotonic()
6041
+ if remaining <= 0:
6042
+ return "wait_elapsed", None
6043
+ if regex is None:
6044
+ job.done.wait(min(remaining, WAIT_SLICE_SECONDS))
6045
+ else:
6046
+ job.wait_change(pos, min(remaining, WAIT_SLICE_SECONDS))
6047
+
6048
+
6049
+ def _plain_wait(wait_seconds, cancel: threading.Event, ctx: SecurityContext) -> str:
6050
+ """check_command sin job_id: espera sin lanzar ningún proceso; vuelve antes si termina un comando del proyecto."""
6051
+ wait = _clamp_seconds(wait_seconds, 0, 0, COMMAND_MAX_WAIT)
6052
+ if not wait:
6053
+ return _tool_error(f"Without job_id, check_command waits: give wait_seconds (1 to {COMMAND_MAX_WAIT}).", os=DETECTED_OS)
6054
+ running = JOBS.running(ctx.key)
6055
+ started = time.monotonic()
6056
+ finished = JOBS.wait_any_finished(running, wait, cancel)
6057
+ reason = "command_finished" if finished else ("wait_ended_by_user" if cancel.is_set() else "wait_elapsed")
6058
+ result = {
6059
+ "success": True,
6060
+ "waited_s": round(time.monotonic() - started, 1),
6061
+ "returned_because": reason,
6062
+ }
6063
+ if finished:
6064
+ result["finished_jobs"] = [
6065
+ {"job_id": job.id, "command": job.command.split("\n")[0][:200], "status": job.status, "exit_code": job.exit_code}
6066
+ for job in finished
6067
+ ]
6068
+ result["note"] = "Read their output with check_command(job_id=...)."
6069
+ return json.dumps(result, ensure_ascii=False, indent=2)
6070
+
6071
+
6072
+ def check_command(job_id: int | None = None, wait_seconds: int = 0, stop: bool = False, pattern: str | None = None,
6073
+ job_key: str | None = None, *, ctx: SecurityContext) -> str:
6074
+ """Estado y salida nueva de un comando lanzado por run_command; puede esperarlo, con un patrón, o detenerlo.
6075
+ Sin job_id, solo espera. La persona puede cortar la espera con zerochat/jobs/end_wait y la clave de la invocación."""
6076
+ if job_id is None:
6077
+ if stop or pattern:
6078
+ return _tool_error("stop and pattern need the job_id of a command.", os=DETECTED_OS)
6079
+ cancel = JOBS.open_wait(job_key)
6080
+ try:
6081
+ return _plain_wait(wait_seconds, cancel, ctx)
6082
+ finally:
6083
+ JOBS.close_wait(job_key)
5925
6084
  job = JOBS.get(ctx.key, job_id=job_id)
5926
6085
  if job is None:
5927
6086
  return _tool_error(f"Unknown job_id {job_id}. It may belong to a previous ZeroChat session or to another project.", os=DETECTED_OS)
6087
+ regex = None
6088
+ if pattern:
6089
+ try:
6090
+ regex = re.compile(pattern, re.IGNORECASE)
6091
+ except re.error as exc:
6092
+ return _tool_error(f"Invalid pattern: {exc}. Use a regular expression such as 'error|listening on'.", os=DETECTED_OS)
5928
6093
  if stop:
5929
6094
  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")
6095
+ return _job_result(job, output_field="new_output")
6096
+ wait = _clamp_seconds(wait_seconds, 0, 0, COMMAND_MAX_WAIT)
6097
+ if not wait and regex is None:
6098
+ return _job_result(job, output_field="new_output")
6099
+ cancel = JOBS.open_wait(job_key)
6100
+ started = time.monotonic()
6101
+ try:
6102
+ reason, line = _wait_job(job, wait, regex, cancel)
6103
+ finally:
6104
+ JOBS.close_wait(job_key)
6105
+ extra = {"returned_because": reason, "waited_s": round(time.monotonic() - started, 1)}
6106
+ if line is not None:
6107
+ extra["matched_line"] = line if len(line) <= MATCHED_LINE_MAX_CHARS else line[:MATCHED_LINE_MAX_CHARS] + "…"
6108
+ return _job_result(job, output_field="new_output", extra=extra)
5935
6109
 
5936
6110
 
5937
6111
  def job_details(job: CommandJob) -> dict:
@@ -6582,7 +6756,7 @@ def live_state(ctx: SecurityContext, focus_conversation_id: str | None = None) -
6582
6756
  """
6583
6757
  Estado del servidor que la interfaz sigue en vivo, en initialize y en cada zerochat/heartbeat:
6584
6758
  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
6759
+ 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
6760
  se puede navegar aunque se haya instalado o quitado durante la sesión; servers, los servicios
6587
6761
  MCP externos aunque otra pestaña los cambie o su proceso muera; runs, lista ligera de ejecuciones
6588
6762
  en segundo plano; y focus_run, estado detallado de la ejecución enfocada por el usuario.
@@ -6590,7 +6764,7 @@ def live_state(ctx: SecurityContext, focus_conversation_id: str | None = None) -
6590
6764
  runs, focus_run = list_server_runs(focus_conversation_id)
6591
6765
  return {
6592
6766
  "cwd": str(ctx.workspace_dir),
6593
- "jobs": [job.summary() for job in JOBS.running(ctx.key)],
6767
+ "jobs": [{**job.summary(), "last_line": job.last_line()} for job in JOBS.running(ctx.key)],
6594
6768
  "exit_on_close": EXIT_ON_CLOSE,
6595
6769
  "playwright": playwright_status(),
6596
6770
  "servers": GLOBAL_MCP_MANAGER.list_servers(),
@@ -6855,15 +7029,25 @@ LOCAL_TOOLS_DEFINITIONS = [
6855
7029
  },
6856
7030
  {
6857
7031
  "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.",
7032
+ "description": (
7033
+ "Check a command started by run_command: returns its status and the output produced since the last check. "
7034
+ "Use wait_seconds to wait for it to finish, add pattern to return as soon as a new output line matches it "
7035
+ "(for example 'error|listening on'), or stop=true to terminate it. "
7036
+ "Without job_id it just waits wait_seconds, with no shell, and returns early if a background command finishes: "
7037
+ "use it instead of sleep."
7038
+ ),
6859
7039
  "inputSchema": {
6860
7040
  "type": "object",
6861
7041
  "properties": {
6862
- "job_id": {"type": "integer", "description": "job_id returned by run_command"},
7042
+ "job_id": {"type": "integer", "description": "job_id returned by run_command; omit it to just wait"},
6863
7043
  "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"]
7044
+ "stop": {"type": "boolean", "description": "Terminate the command and its child processes", "default": False},
7045
+ "pattern": {
7046
+ "type": "string",
7047
+ "maxLength": CHECK_PATTERN_MAX_CHARS,
7048
+ "description": "Case-insensitive regular expression matched against each new output line; with wait_seconds, returns as soon as a line matches"
7049
+ }
7050
+ }
6867
7051
  }
6868
7052
  },
6869
7053
  {
@@ -7395,8 +7579,8 @@ def run_supervisor(server: ThreadingHTTPServer, session: RunSession, runner_proc
7395
7579
  return
7396
7580
  if proc is not None and proc.poll() is not None and not session.finished.wait(0.2):
7397
7581
  break
7398
- if time.monotonic() >= deadline:
7399
- session.stop_reason = f"Plazo total agotado ({RUN_TOTAL_TIMEOUT:.0f}s)."
7582
+ if time.monotonic() >= deadline + session.waited_seconds():
7583
+ session.stop_reason = f"Plazo total agotado ({RUN_TOTAL_TIMEOUT:.0f}s, sin contar las esperas)."
7400
7584
  break
7401
7585
  if session.idle_seconds() > RUN_IDLE_SECONDS:
7402
7586
  session.stop_reason = f"Sin progreso de la interfaz durante {RUN_IDLE_SECONDS:.0f}s."
@@ -7857,9 +8041,15 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
7857
8041
  message = (f"The browser is in use by another conversation. It is released after {int(BROWSER_LEASE_IDLE_SECONDS)} "
7858
8042
  "seconds without use; tell the user or try again later.")
7859
8043
  return {"content": [{"type": "text", "text": _tool_error(message)}], "isError": True}, None, message
8044
+ # En una ejecución desatendida, esperar en check_command no es inactividad ni gasta el plazo total.
8045
+ session = current_run_session() if origin == "local" and tool_name == JOB_CONTROL_TOOL else None
8046
+ if session is not None:
8047
+ session.begin_wait()
7860
8048
  try:
7861
8049
  return cls._run_tool(origin, tool_name, args, ctx)
7862
8050
  finally:
8051
+ if session is not None:
8052
+ session.end_wait()
7863
8053
  # El plazo cuenta desde que la acción termina: lo que tarde no acorta lo que el modelo puede razonar después.
7864
8054
  if browser:
7865
8055
  BROWSER_LEASES.acquire(browser, conversation_id)
@@ -8239,6 +8429,8 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
8239
8429
  if not isinstance(ids, list) or len(ids) > 100 or any(isinstance(i, bool) or not isinstance(i, int) for i in ids):
8240
8430
  return None, {"code": -32602, "message": "ids debe ser una lista de hasta 100 enteros."}, ""
8241
8431
  return {"reports": JOBS.report_finished(ids, project)}, None, ""
8432
+ if method == "zerochat/jobs/end_wait":
8433
+ return {"ended": JOBS.cancel_wait(params.get("key"))}, None, ""
8242
8434
  job = JOBS.get(project, job_id=params.get("id"), key=params.get("key"))
8243
8435
  if method in ("zerochat/jobs/get", "zerochat/jobs/log", "zerochat/jobs/stop") and job is None:
8244
8436
  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