diff --git a/docs/system-specs/common/error-handling.md b/docs/system-specs/common/error-handling.md index e34ae81a7759..cc5eaae70be4 100644 --- a/docs/system-specs/common/error-handling.md +++ b/docs/system-specs/common/error-handling.md @@ -97,6 +97,7 @@ instead of the row simply disappearing. | Integer field in a dashboard JSON body | Read through `dashboard/body_numbers.body_int`, which raises `ValueError` for `1e999`/`-1e999` (infinite floats after `json.loads`) where `int()` raises `OverflowError`. The handler's own `except (TypeError, ValueError)` then gives the infinite value the same 400 or fallback any other malformed value gets there, never a 500. A site does not add `OverflowError` to its own except clause instead | | Skill index (`list_skills`) | One global SKILL.md that is not UTF-8 or cannot be opened → one warning naming the file, that row dropped, every other row listed. Never a failed listing: the index feeds every chat turn and `GET /api/skills`. Rationale: [memory-skills-hooks](../modules/memory-skills-hooks.md) | | Process spawn | Backend-specific executable resolver, including trusted-path checks where required; clear error if missing | +| A host that does not answer (`kirocrew kas login`, the KAS engine manifest fetch) | The message names the host and leads with the cause in plain words. `asset_downloader.network_failure_cause` reads it from the exception types (urllib's `URLError.reason`, aiohttp's `os_error`), never their text: `connection refused`, `the host name could not be resolved` or `timed out`. Any other failure keeps the library's own text, which is then the only clue there is, and so does an aiohttp exception with no `host` (a connect timeout names its host only in its text) | | Notes git subprocess (`md_notebook/git_ops.py`) | A non-zero exit reports git's last 3 stderr lines PLUS the first transport-caused line when one sits outside that tail. git ends every fetch/push failure with the same access-rights boilerplate and prints an SSH diagnosis first, so a tail alone reports a permission problem the operator does not have (a host reachable only via `~/.ssh/config` never resolved at all). The extra line widens what the message reports; it does not decide whether the command failed. | | Auto-Improvement git step (`auto_improvement/backend/clone_setup.py`) | A failed clone, branch list, checkout or fetch reports git's last 2 stderr lines after dropping blank lines and git's access-rights advisory (`Please make sure you have the correct access rights` / `and the repository exists.`), redacted and then bounded. The advisory follows every transport or auth fatal, so keeping it reports a repository problem in place of the `Permission denied (publickey).` line above it. | | App Store install clone, pinned fetch and pull (`apps/registry_pipeline/checkout.py`) | A credential-free (catalog or `index`-tier registry) fetch of an ssh remote whose output holds ssh's own `ssh: Could not resolve hostname` line returns `git_clone_failed_strict_ssh_route` with a fixed sentence: the fetch ran in the strict sandbox, which hides `~/.ssh`, so neither `~/.ssh/config` nor the ssh-agent applied, and a host reachable only through an ssh config route is installed from the operator's own clone with `kirocrew app install `. It carries no proxy hint, because ssh never reads `HTTPS_PROXY`; an owner-credentialed clone and an HTTPS remote keep the network hint. | diff --git a/src/kiro_crew/acp/kas_bundle.py b/src/kiro_crew/acp/kas_bundle.py index 7f4d48748650..ec9a77429dcc 100644 --- a/src/kiro_crew/acp/kas_bundle.py +++ b/src/kiro_crew/acp/kas_bundle.py @@ -391,7 +391,10 @@ def _read_json_url(url: str, opener: Any, *, sha256: str | None = None) -> Any: except (OSError, ValueError) as exc: # ValueError is urllib's answer to a url it cannot parse (an unclosed # IPv6 bracket in a hand-typed --url), the same refusal as an unreachable one. - raise KasBundleError(f"could not fetch {asset_downloader.redact_url(url)}: {exc}") from exc + why = asset_downloader.network_failure_cause(exc) or exc + raise KasBundleError( + f"could not download the KAS engine from {asset_downloader.redact_url(url)}: {why}" + ) from exc if len(body) > _MANIFEST_MAX_BYTES: raise KasBundleError(f"{asset_downloader.redact_url(url)} is too large to be a manifest") if sha256 is not None and hashlib.sha256(body).hexdigest() != sha256: diff --git a/src/kiro_crew/asset_downloader.py b/src/kiro_crew/asset_downloader.py index 3bff439eebaf..77d1684264c4 100644 --- a/src/kiro_crew/asset_downloader.py +++ b/src/kiro_crew/asset_downloader.py @@ -80,6 +80,7 @@ import io import logging import os +import socket import ssl import stat import time @@ -348,6 +349,22 @@ def redact_url(url: str) -> str: return "" +def network_failure_cause(exc: BaseException) -> str: + """Why a connection failed, in a user's words, or ``""`` for any other failure. + + Read from the exception types, never their text: urllib carries the socket + error in ``URLError.reason``, aiohttp in ``ClientConnectorError.os_error``. + """ + for err in (exc, getattr(exc, "reason", None), getattr(exc, "os_error", None)): + if isinstance(err, socket.gaierror): + return "the host name could not be resolved" + if isinstance(err, ConnectionRefusedError): + return "connection refused" + if isinstance(err, TimeoutError): + return "timed out" + return "" + + #: ``O_BINARY`` exists only on Windows (where a text-mode descriptor translates #: bytes); ``O_NOFOLLOW`` only on POSIX. Both read as 0 where absent. _O_BINARY = getattr(os, "O_BINARY", 0) @@ -1057,6 +1074,7 @@ def download_to( "file_identity", "install_verified", "make_ssl_context", + "network_failure_cause", "open_staging_nofollow", "redact_url", ] diff --git a/src/kiro_crew/cli_kas_login.py b/src/kiro_crew/cli_kas_login.py index d19b6e1426ac..2ebddc6c1a96 100644 --- a/src/kiro_crew/cli_kas_login.py +++ b/src/kiro_crew/cli_kas_login.py @@ -218,6 +218,28 @@ def _login(args: argparse.Namespace) -> int: return 130 +def _unreachable(lead: str, exc: BaseException) -> str: + """*lead*, the host and why in plain words, then what to do next. + + The library's own text is the reason only when it is none of the causes + :func:`kiro_crew.asset_downloader.network_failure_cause` names, or when the + exception carries no host: aiohttp's connect timeout names it only in its + text (``Connection timeout to host ``). + """ + # Local for the reason _run_device_login gives: `--help` must not pay for it. + from kiro_crew.asset_downloader import network_failure_cause + + host = getattr(exc, "host", "") + if host: + why = f" ({host}): {network_failure_cause(exc) or exc}" + else: + why = f": {str(exc) or network_failure_cause(exc)}" + return ( + f"❌ {lead}{why}.\n" + " Nothing was stored. Check your network connection, then run the command again." + ) + + async def _run_device_login( store: Any, *, provider: str, start_url: str, region: str, replaces: str = "" ) -> int: @@ -257,7 +279,7 @@ async def _run_device_login( print(f"❌ the sign-in service refused to start a sign-in: {exc}", file=sys.stderr) return 1 except (aiohttp.ClientError, asyncio.TimeoutError) as exc: - print(f"❌ could not reach the sign-in service: {exc}", file=sys.stderr) + print(_unreachable("could not reach the sign-in service", exc), file=sys.stderr) return 1 # Line-buffered on purpose: the cloud sign-in reads these two lines out of # a log this process writes under nohup, where stdout is block-buffered. @@ -274,8 +296,9 @@ async def _run_device_login( # The service absorbs a few dropped polls itself; past its budget # the outage is real, and the user gets a line, not a traceback. print( - f"❌ lost contact with the sign-in service while waiting for approval: " - f"{exc}; nothing was stored. Run the command again.", + _unreachable( + "lost contact with the sign-in service while waiting for approval", exc + ), file=sys.stderr, ) return 1 diff --git a/test/test_cli_kas_login.py b/test/test_cli_kas_login.py index 8a6dfd47fd59..3ead7e7b0e94 100644 --- a/test/test_cli_kas_login.py +++ b/test/test_cli_kas_login.py @@ -11,7 +11,9 @@ from __future__ import annotations import argparse +import errno from datetime import datetime, timezone +from types import SimpleNamespace import pytest @@ -328,6 +330,46 @@ async def _drop(self, login_id): assert "lost contact with the sign-in service" in err assert "Traceback" not in err + def test_an_unreachable_sign_in_service_names_the_host_and_the_cause( + self, home_store, fake_service, capsys, monkeypatch + ): + """aiohttp's ``ssl:default [Multiple exceptions: [Errno 111] ...]`` is Python + internals: the user reads the host, the cause in plain words and what to do.""" + import aiohttp + + async def _refused(self, provider, **kwargs): + key = SimpleNamespace(host="oidc.us-east-1.amazonaws.com", port=443, ssl=True) + both = "Multiple exceptions: [Errno 111] Connect call failed ('::1', 443, 0, 0)" + raise aiohttp.ClientConnectorError( + key, ConnectionRefusedError(errno.ECONNREFUSED, both) + ) + + monkeypatch.setattr(fake_service, "begin_device", _refused) + assert cli_kas.kas_cmd(_parse("login")) == 1 + assert capsys.readouterr().err == ( + "❌ could not reach the sign-in service (oidc.us-east-1.amazonaws.com): " + "connection refused.\n" + " Nothing was stored. Check your network connection, then run the command again.\n" + ) + + def test_a_connect_timeout_keeps_the_host_its_text_names( + self, home_store, fake_service, capsys, monkeypatch + ): + """aiohttp's connect timeout carries no ``host``; its text is the one place that + names the host, so it stays the reason instead of a bare ``timed out``.""" + import aiohttp + + url = "https://oidc.us-east-1.amazonaws.com/client/register" + + async def _slow(self, provider, **kwargs): + raise aiohttp.ConnectionTimeoutError(f"Connection timeout to host {url}") + + monkeypatch.setattr(fake_service, "begin_device", _slow) + assert cli_kas.kas_cmd(_parse("login")) == 1 + assert capsys.readouterr().err.startswith( + f"❌ could not reach the sign-in service: Connection timeout to host {url}.\n" + ) + def test_a_sign_out_during_the_login_is_a_line_not_a_traceback( self, home_store, fake_service, capsys, monkeypatch ): diff --git a/test/test_kas_bundle.py b/test/test_kas_bundle.py index 7bb9a4b8cf42..93adc641d228 100644 --- a/test/test_kas_bundle.py +++ b/test/test_kas_bundle.py @@ -10,14 +10,17 @@ from __future__ import annotations +import errno import hashlib import io import json import logging import os +import socket import stat import tarfile import time +import urllib.error from pathlib import Path from unittest.mock import patch @@ -239,9 +242,32 @@ def open(self, url, timeout): def test_fetch_from_a_malformed_url_is_a_refusal_not_a_traceback(self): """urllib raises ValueError for a url it cannot parse; the operator typed it, so the answer is the installer's one error type, which the CLI prints and exits.""" - with pytest.raises(kas_bundle.KasBundleError, match="could not fetch"): + with pytest.raises(kas_bundle.KasBundleError, match="could not download the KAS engine"): kas_bundle.fetch_manifest("https://[mirror", version="0.66.33") + @pytest.mark.parametrize( + "reason, cause", + [ + ( + ConnectionRefusedError(errno.ECONNREFUSED, "Connection refused"), + "connection refused", + ), + (socket.gaierror("Name or service not known"), "the host name could not be resolved"), + (TimeoutError("timed out"), "timed out"), + ], + ) + def test_an_unreachable_host_is_named_with_the_cause_in_plain_words(self, reason, cause): + """urllib's ```` is Python + internals; the installer prints this message as the whole failure.""" + + class _Opener: + def open(self, url, timeout): + raise urllib.error.URLError(reason) + + with pytest.raises(kas_bundle.KasBundleError) as info: + kas_bundle.fetch_manifest("https://h.test", version="0.66.33", opener=_Opener()) + assert str(info.value) == f"could not download the KAS engine from https://h.test: {cause}" + def test_fetch_pinned_version_must_match_the_document(self, source_dir): class _Resp(io.BytesIO): def __enter__(self):