diff --git a/README.en.md b/README.en.md index 202d9e2..a824208 100644 --- a/README.en.md +++ b/README.en.md @@ -12,9 +12,29 @@ adh connect 127.0.0.1:8088 adh devices ``` -Source: [decrypthub/adh-cli](https://github.com/decrypthub/adh-cli). PyPI project: [android-decrypt-hub](https://pypi.org/project/android-decrypt-hub/). Product repository: [AndroidDecryptHub](https://github.com/decrypthub/AndroidDecryptHub). Current version: **0.1.2**. +Source: [decrypthub/adh-cli](https://github.com/decrypthub/adh-cli). PyPI project: [android-decrypt-hub](https://pypi.org/project/android-decrypt-hub/). Product repository: [AndroidDecryptHub](https://github.com/decrypthub/AndroidDecryptHub). Current version: **0.2.0**. -The Host ADH Daemon has no authentication. Use it only on a trusted LAN, and do not point an MCP client at the HTTP `/mcp` endpoint directly. +Full connection authentication and TLS are not implemented. P1 operator credentials coordinate human control only. Use the Host on a trusted LAN, and do not point an MCP client at the HTTP `/mcp` endpoint directly. + +## P1 durable operations and control (unreleased source) + +This branch pairs with the P1 AndroidDecryptHub Host. It has not been published to PyPI and does not upgrade or restart an existing Host. P1 writes require expectedRevision/controlEpoch/hostEpoch in `_operation`; unversioned writes return CONTROL_REQUIRED. Ordinary reads and stdio passthrough remain compatible. See the product repository's `docs/P1_OPERATIONS.md` for the shared execution contract. + +```bash +adh tasks create --title "Request analysis" --endpoint 127.0.0.1:18088 --json +adh run TOOL --arguments JSON --task-id TASK_ID --idempotency-key INTENT_ID --endpoint 127.0.0.1:18088 --json +adh tasks get OPERATION_ID --include-result --endpoint 127.0.0.1:18088 --json +adh tasks cancel OPERATION_ID --endpoint 127.0.0.1:18088 +adh tasks cancel --task-id TASK_ID --endpoint 127.0.0.1:18088 +adh tasks list --limit 50 --offset 0 --endpoint 127.0.0.1:18088 +adh control snapshot --session SESSION --endpoint 127.0.0.1:18088 +``` + +`run` observes once and submits asynchronously. Queued/running means accepted; query `tasks get` for the outcome. Use `adh call TOOL --arguments JSON --operation METADATA_JSON` to preserve previously observed versions. On a conflict, observe and re-plan; the CLI never silently replaces stale versions or retries. Keep the same idempotency key for the same intent. + +An operator explicitly sets ADH_OPERATOR_TOKEN in their terminal and uses `adh control takeover|release --session SESSION --operator`. Supply all of `--revision N --epoch N --host-epoch N` to use an existing observation. Actions are snapshot/takeover/release/resolve/hold. Use `resolve --acknowledge --operator` only after checking unknown effects; it does not stop or roll back the target. + +CLI and stdio AI defaults ignore an inherited operator key; only explicit `--operator` sends it. Tasks support pause/resume/complete; cancelling one operation leaves its named task active. In-flight cancellation can still finish successfully: cancel_requested or succeeded with cancelRequested preserves that fact. Post-dispatch timeout/disconnect is unknown, with late evidence and no automatic replay. An HTTP timeout does not prove Host/target execution stopped; query the durable id/key before taking further action. ## Install @@ -24,7 +44,7 @@ python -m pip install -U android-decrypt-hub ## Connect -Start the Host ADH Daemon first. Its current default HTTP port is `8088`. This CLI still uses `8760` when the port is omitted, so pass the real port: +Start the Host ADH Daemon first. Its current default HTTP port is `8088`. This CLI still uses `8088` when the port is omitted, so pass the real port: ```bash adh connect 127.0.0.1:8088 @@ -93,3 +113,19 @@ Keep the upload token in `~/.config/pypi/token` on the release machine. Do not c Install the official gateway from DecryptHub → Plugins, then configure your device service address. The component contains the PC CLI and a standard-library launcher and requires Python 3.10+. Device plugins and Host services are deployed separately. Maintainers: run `python scripts/build_component.py` to build `dist/adh--any.zip`, including an API 1 manifest, source revision and per-file SHA-256 checksums. GitHub Releases tags `decrypthub-v` distribute desktop components independently of PyPI releases. + +## Desktop Agent status and discovery + +```bash +adh status --json --endpoint http://127.0.0.1:8088 +adh tools --json --endpoint http://127.0.0.1:8088 +``` + +`status --json` returns a read-only snapshot with `schemaVersion: 1`, `checkedAt`, service observations in `connections`, and current app/PID identifiers in `targets`. An offline address is never reported as an online target. Status does not save connections, inject, restart apps, or upgrade the CLI. `tools --json` reads the real MCP tool descriptions and argument schemas. Refresh status, select a unique returned target, then use `call` or the persistent MCP connection; ask the user when multiple targets match. + +ADH defaults to port 8088. `devices --endpoint` inspects a temporary address. `call` exits nonzero for an MCP error or `isError` result. + +## Development checks + +Run `python -m pytest` from the source checkout. The test configuration imports this repository's `src` first, avoiding an older globally installed `adh`. +Before publishing, also run `python -m build` and `python -m twine check dist/*`, then verify the built wheel in an isolated environment. diff --git a/README.md b/README.md index 5ce9c73..18b6c88 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,29 @@ adh connect 127.0.0.1:8088 adh devices ``` -源码在 [decrypthub/adh-cli](https://github.com/decrypthub/adh-cli),PyPI 包名是 [android-decrypt-hub](https://pypi.org/project/android-decrypt-hub/)。产品仓库是 [AndroidDecryptHub](https://github.com/decrypthub/AndroidDecryptHub)。当前版本 **0.1.2**。 +源码在 [decrypthub/adh-cli](https://github.com/decrypthub/adh-cli),PyPI 包名是 [android-decrypt-hub](https://pypi.org/project/android-decrypt-hub/)。产品仓库是 [AndroidDecryptHub](https://github.com/decrypthub/AndroidDecryptHub)。当前版本 **0.2.0**。 -Host ADH Daemon 没有身份认证,只在可信局域网里使用,不要暴露到公网。不要把 HTTP `/mcp` 直接配进 MCP 客户端。 +Host ADH Daemon 的完整连接认证与 TLS 尚未实现,P1 的 operator 凭据只协调人类控制权。只在可信局域网里使用,不要暴露到公网。不要把 HTTP `/mcp` 直接配进 MCP 客户端。 + +## P1 持久任务与接管(源码待发布) + +本分支与 AndroidDecryptHub 的 P1 Host 配套,尚未发布到 PyPI;不会升级或重启已有 Host。新 Host 的写入要求 `_operation` 中的 expectedRevision/controlEpoch/hostEpoch,旧无版本写调用会返回 CONTROL_REQUIRED。普通读取与 stdio 透传仍兼容;AI 需要明确观察版本后提交。统一执行层与状态定义见产品仓库 `docs/P1_OPERATIONS.md`。 + +```bash +adh tasks create --title "请求分析" --endpoint 127.0.0.1:18088 --json +adh run TOOL --arguments JSON --task-id TASK_ID --idempotency-key INTENT_ID --endpoint 127.0.0.1:18088 --json +adh tasks get OPERATION_ID --include-result --endpoint 127.0.0.1:18088 --json +adh tasks cancel OPERATION_ID --endpoint 127.0.0.1:18088 +adh tasks cancel --task-id TASK_ID --endpoint 127.0.0.1:18088 +adh tasks list --limit 50 --offset 0 --endpoint 127.0.0.1:18088 +adh control snapshot --session SESSION --endpoint 127.0.0.1:18088 +``` + +`run` 观察一次状态并异步提交,返回 queued/running 只代表已接受;通过 `tasks get` 检查真实结果。AI 已有旧版本时用 `adh call TOOL --arguments JSON --operation METADATA_JSON` 保留原版本;发生冲突必须重新观察并规划,CLI 不替换版本重试。同一意图保持同一个 idempotency key。 + +人类在当前终端显式配置 ADH_OPERATOR_TOKEN 后,用 `adh control takeover|release --session SESSION --operator` 接管/释放;也可加 `--revision N --epoch N --host-epoch N` 使用已观察版本。完整 action 包括 snapshot/takeover/release/resolve/hold。`resolve --acknowledge --operator` 仅在检查未知副作用后使用,不代表停止或回滚目标。 + +默认 CLI 和 stdio AI 代理忽略继承的 operator 密钥;只有显式 `--operator` 才发送。任务可 pause/resume/complete;cancel 单个 operation 不取消整项 task。派发后取消仍可能执行成功,反馈 cancel_requested 或 succeeded + cancelRequested;派发后超时/断连为 unknown,保留晚到证据,不自动重放。HTTP 传输超时本身不能证明 Host 或目标已停止,使用持久 id/key 查询;不要直接重发旧写入。 ## 安装 @@ -31,7 +51,7 @@ pipx upgrade android-decrypt-hub ## 连接 -先在电脑上启动 Host ADH Daemon,再保存它的地址。当前 Daemon 默认 HTTP 端口是 `8088`。这个 CLI 在省略端口时仍使用 `8760`,所以请带上实际端口: +先在电脑上启动 Host ADH Daemon,再保存它的地址。Daemon 和 CLI 的默认 HTTP 端口均为 `8088`。已保存或显式指定的其他端口继续有效: ```bash adh connect 127.0.0.1:8088 @@ -96,7 +116,7 @@ adh call --endpoint http://127.0.0.1:8088 | 命令 | 作用 | | --- | --- | -| `adh connect [地址]` | 探测并保存 Host ADH Daemon。默认 `127.0.0.1:8760` | +| `adh connect [地址]` | 探测并保存 Host ADH Daemon。默认 `127.0.0.1:8088` | | `adh disconnect [地址]` | 移除一个已保存地址;`--all` 清空 | | `adh devices` | 列出已保存地址,并显示在线状态 | | `adh mcp` | 把已保存 Daemon 的 `POST /mcp` 转成 stdio MCP | @@ -139,3 +159,19 @@ python -m twine upload --repository pypi dist/android_decrypt_hub-* 在 DecryptHub 的「插件」入口安装官方网关,配置设备服务地址后即可启用 MCP。安装包只包含电脑端 CLI 和标准库启动器,要求 Python 3.10+;设备插件及 Host 服务仍按各自项目说明准备。 维护者构建组件:`python scripts/build_component.py`。输出 `dist/adh--any.zip`,包含 API 1 清单、源代码版本及逐文件 SHA-256,可独立通过 GitHub Releases 更新。`decrypthub-v` 标签用于桌面组件分发,与 PyPI 发版独立。 + +## 桌面 Agent 与状态查询 + +```bash +adh status --json --endpoint http://127.0.0.1:8088 +adh tools --json --endpoint http://127.0.0.1:8088 +``` + +`status --json` 返回带 `schemaVersion: 1` 和 `checkedAt` 的只读快照,分别列出 `connections` 的服务在线事实及 `targets` 的应用/PID/目标标识;离线地址不会冒充在线目标。状态查询不保存地址、不注入、不启停应用,也不自动升级 CLI。`tools --json` 返回当前目标的真实 MCP 工具说明和参数 schema。先查询状态,再选择本次返回的唯一目标,最后通过现有 `call` 或持久 MCP 连接执行分析;多个候选必须让用户选择。 + +ADH 省略端口时默认连接 8088;`devices --endpoint` 支持临时探测,`call` 收到 MCP 错误或 `isError` 时返回非零退出码。 + +## 开发验证 + +在源码目录运行 `python -m pytest`。测试配置优先导入本仓 `src`,避免误测电脑上已安装的旧版 `adh`。 +发布前另运行 `python -m build` 与 `python -m twine check dist/*`,并在隔离环境验证构建后的 wheel。 diff --git a/pyproject.toml b/pyproject.toml index 97222d1..bfc52d6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "android-decrypt-hub" -version = "0.1.2" +version = "0.2.0" description = "Connect to Host ADH Daemon and bridge HTTP MCP to stdio" readme = "README.md" requires-python = ">=3.10" @@ -47,3 +47,4 @@ where = ["src"] [tool.pytest.ini_options] testpaths = ["tests"] +pythonpath = ["src"] diff --git a/src/adh/__init__.py b/src/adh/__init__.py index 2c20232..41394a8 100644 --- a/src/adh/__init__.py +++ b/src/adh/__init__.py @@ -1,3 +1,3 @@ """Android DecryptHub MCP gateway.""" -__version__ = "0.1.2" +__version__ = "0.2.0" diff --git a/src/adh/cli.py b/src/adh/cli.py index 7c0982a..2c4e92e 100644 --- a/src/adh/cli.py +++ b/src/adh/cli.py @@ -3,6 +3,7 @@ import argparse import json import sys +import uuid from collections.abc import Sequence from . import __version__ @@ -10,6 +11,7 @@ from .endpoint import DEFAULT_PORT, HostEndpoint from .http_mcp import MCPHTTPClient, MCPTransportError, probe_endpoint from .stdio import TransparentProxy, configure_stdio_utf8, serve_stdio +from .status import inventory PROBE_TIMEOUT = 3.0 DEFAULT_CONNECT = f"127.0.0.1:{DEFAULT_PORT}" @@ -35,6 +37,16 @@ def build_parser() -> argparse.ArgumentParser: devices = sub.add_parser("devices", help="list saved Host daemons") devices.add_argument("--json", action="store_true") + devices.add_argument("--endpoint", action="append", default=[]) + + status = sub.add_parser("status", help="read-only service and target inventory for desktop Agents") + status.add_argument("--endpoint", action="append", default=[]) + status.add_argument("--timeout", type=float, default=PROBE_TIMEOUT) + status.add_argument("--json", action="store_true") + + tools = sub.add_parser("tools", help="list the Host's real MCP tools and argument schemas") + tools.add_argument("--endpoint") + tools.add_argument("--json", action="store_true") mcp = sub.add_parser("mcp", help="stdio MCP proxy to Host POST /mcp") mcp.add_argument("--endpoint", help="override saved address for this run") @@ -44,6 +56,42 @@ def build_parser() -> argparse.ArgumentParser: call.add_argument("--arguments", default="{}", metavar="JSON") call.add_argument("--endpoint") call.add_argument("--json", action="store_true") + call.add_argument("--operation", help="explicit operation control metadata as JSON") + call.add_argument("--operator", action="store_true", help="use ADH_OPERATOR_TOKEN explicitly") + + run = sub.add_parser("run", help="observe current control once and submit a durable tool operation") + run.add_argument("tool_name") + run.add_argument("--arguments", default="{}") + run.add_argument("--task-id") + run.add_argument("--idempotency-key") + run.add_argument("--timeout-ms", type=int, default=120000) + run.add_argument("--endpoint") + run.add_argument("--operator", action="store_true") + run.add_argument("--json", action="store_true") + + tasks = sub.add_parser("tasks", help="query/control persistent Host tasks and operations") + tasks.add_argument("action", choices=["create", "list", "get", "pause", "resume", "cancel", "complete"]) + tasks.add_argument("id", nargs="?") + tasks.add_argument("--task-id") + tasks.add_argument("--title", default="analysis") + tasks.add_argument("--include-result", action="store_true") + tasks.add_argument("--limit", type=int, default=50) + tasks.add_argument("--offset", type=int, default=0) + tasks.add_argument("--endpoint") + tasks.add_argument("--operator", action="store_true") + tasks.add_argument("--json", action="store_true") + + control = sub.add_parser("control", help="read state versions or explicitly transfer operator control") + control.add_argument("action", choices=["snapshot", "takeover", "release", "resolve", "hold"]) + control.add_argument("--session") + control.add_argument("--resource") + control.add_argument("--revision", type=int) + control.add_argument("--epoch", type=int) + control.add_argument("--host-epoch", type=int) + control.add_argument("--acknowledge", action="store_true") + control.add_argument("--endpoint") + control.add_argument("--operator", action="store_true") + control.add_argument("--json", action="store_true") return parser @@ -54,7 +102,7 @@ def _resolve_saved(override: str | None) -> HostEndpoint: if len(saved) == 1: return saved[0] if not saved: - raise SystemExit("adh: no saved host; run `adh connect 127.0.0.1:8760`") + raise SystemExit("adh: no saved host; run `adh connect 127.0.0.1:8088`") raise SystemExit( "adh: multiple saved hosts; pass --endpoint \n" + "\n".join(f" {item.mcp_url}" for item in saved) @@ -106,7 +154,7 @@ def _cmd_disconnect(args: argparse.Namespace) -> int: def _cmd_devices(args: argparse.Namespace) -> int: - saved = load_saved_endpoints() + saved = [HostEndpoint.from_url(value) for value in args.endpoint] if args.endpoint else load_saved_endpoints() rows = [probe_endpoint(item) for item in saved] if args.json: print( @@ -127,7 +175,7 @@ def _cmd_devices(args: argparse.Namespace) -> int: ) return 0 if not rows: - print("adh: no saved hosts. `adh connect 127.0.0.1:8760`") + print("adh: no saved hosts. `adh connect 127.0.0.1:8088`") return 0 for item in rows: status = item.properties.get("status") or "unknown" @@ -136,6 +184,28 @@ def _cmd_devices(args: argparse.Namespace) -> int: return 0 +def _cmd_status(args: argparse.Namespace) -> int: + endpoints = [HostEndpoint.from_url(value) for value in args.endpoint] if args.endpoint else load_saved_endpoints() + data = inventory(endpoints, timeout=args.timeout) + print(json.dumps(data, ensure_ascii=False, indent=2)) + return 0 + + +def _cmd_tools(args: argparse.Namespace) -> int: + endpoint = _resolve_saved(args.endpoint) + try: + response = MCPHTTPClient(endpoint, timeout=10.0).send({"jsonrpc": "2.0", "id": "adh-tools", "method": "tools/list", "params": {}}) + result = response.get("result") if isinstance(response, dict) and "error" not in response else None + if not isinstance(result, dict) or not isinstance(result.get("tools"), list): + print("adh: invalid tools/list response", file=sys.stderr) + return 1 + print(json.dumps(result, ensure_ascii=False, indent=2)) + return 0 + except MCPTransportError as exc: + print(f"adh: {exc}", file=sys.stderr) + return 1 + + def _cmd_mcp(args: argparse.Namespace) -> int: endpoint = _resolve_saved(args.endpoint) probed = probe_endpoint(endpoint) @@ -156,8 +226,17 @@ def _cmd_call(args: argparse.Namespace) -> int: if not isinstance(arguments, dict): print("adh: --arguments must be a JSON object", file=sys.stderr) return 2 - client = MCPHTTPClient(endpoint) + if args.operation: + try: + metadata = json.loads(args.operation) + if not isinstance(metadata, dict) or "_operation" in arguments: + raise ValueError("use one operation metadata object") + arguments["_operation"] = metadata + except (ValueError, json.JSONDecodeError) as exc: + print(f"adh: invalid --operation: {exc}", file=sys.stderr) + return 2 try: + client = MCPHTTPClient(endpoint, operator=True) if args.operator else MCPHTTPClient(endpoint) response = client.send( { "jsonrpc": "2.0", @@ -174,7 +253,78 @@ def _cmd_call(args: argparse.Namespace) -> int: else: result = response.get("result") if isinstance(response, dict) else response print(json.dumps(result, ensure_ascii=False, indent=2)) - return 0 + result = response.get("result") if isinstance(response, dict) else None + return 1 if not isinstance(result, dict) or result.get("isError") else 0 + + +def _operation_rpc(client: MCPHTTPClient, arguments: dict) -> dict: + response = client.send({"jsonrpc": "2.0", "id": uuid.uuid4().hex, "method": "tools/call", + "params": {"name": "operations", "arguments": arguments}}) + if not isinstance(response, dict) or "error" in response: + raise MCPTransportError("Host rejected operation management request") + result = response.get("result", {}) + try: + value = json.loads(result["content"][0]["text"]) + except (KeyError, IndexError, TypeError, json.JSONDecodeError) as exc: + raise MCPTransportError("Host does not support P1 operation management") from exc + if not isinstance(value, dict): + raise MCPTransportError("invalid operation response") + return value + + +def _cmd_operations(args: argparse.Namespace) -> int: + try: + endpoint = _resolve_saved(args.endpoint) + client = MCPHTTPClient(endpoint, operator=True) if args.operator else MCPHTTPClient(endpoint) + if args.command == "run": + values = json.loads(args.arguments) + if not isinstance(values, dict) or "_operation" in values: + raise ValueError("--arguments must be an object without _operation; use call for explicit versions") + snapshot = _operation_rpc(client, {"action": "snapshot", "tool": args.tool_name, "arguments": values}) + if snapshot.get("ok") is False: + value = snapshot + else: + metadata = {"expectedRevision": snapshot["revision"], "controlEpoch": snapshot["epoch"], + "hostEpoch": snapshot["hostEpoch"], "idempotencyKey": args.idempotency_key or uuid.uuid4().hex, + "timeoutMs": args.timeout_ms} + if args.task_id: + metadata["taskId"] = args.task_id + value = _operation_rpc(client, {"action": "submit", "tool": args.tool_name, "arguments": values, "_operation": metadata}) + elif args.command == "control": + target = {key: val for key, val in {"session": args.session, "resource": args.resource}.items() if val} + values = {"action": args.action, **target} + if args.action != "snapshot": + numbers = [args.revision, args.epoch, args.host_epoch] + if any(n is not None for n in numbers) and not all(n is not None for n in numbers): + raise ValueError("supply --revision, --epoch and --host-epoch together") + if args.acknowledge and args.action != "resolve": + raise ValueError("--acknowledge only applies to resolve") + snapshot = _operation_rpc(client, {"action": "snapshot", **target}) if numbers[0] is None else None + if snapshot and snapshot.get("ok") is False: + print(json.dumps(snapshot, ensure_ascii=False, indent=2)) + return 1 + values["_operation"] = {"expectedRevision": snapshot["revision"] if snapshot else args.revision, + "controlEpoch": snapshot["epoch"] if snapshot else args.epoch, + "hostEpoch": snapshot["hostEpoch"] if snapshot else args.host_epoch} + values["acknowledge"] = args.acknowledge + value = _operation_rpc(client, values) + else: + values = {"action": args.action, "limit": args.limit, "offset":args.offset, "includeResult": args.include_result} + if args.action == "create": + values["title"] = args.title + if args.task_id: + values["taskId"] = args.task_id + elif args.id: + values["taskId" if args.action in ["pause", "resume", "complete"] else "id"] = args.id + if args.action not in ["create", "list"] and not (args.id or args.task_id): + raise ValueError("a task/operation id is required") + value = _operation_rpc(client, values) + print(json.dumps(value, ensure_ascii=False, indent=2 if args.json else None)) + # Queued/running acknowledges acceptance, never claims analysis succeeded. + return 0 if value.get("ok") is not False else 1 + except (MCPTransportError, ValueError, KeyError) as exc: + print(f"adh: {exc}", file=sys.stderr) + return 1 def main(argv: Sequence[str] | None = None) -> int: @@ -188,7 +338,12 @@ def main(argv: Sequence[str] | None = None) -> int: "connect": _cmd_connect, "disconnect": _cmd_disconnect, "devices": _cmd_devices, + "status": _cmd_status, + "tools": _cmd_tools, "mcp": _cmd_mcp, "call": _cmd_call, + "run": _cmd_operations, + "tasks": _cmd_operations, + "control": _cmd_operations, } return commands[args.command](args) diff --git a/src/adh/endpoint.py b/src/adh/endpoint.py index e18d571..178421e 100644 --- a/src/adh/endpoint.py +++ b/src/adh/endpoint.py @@ -6,7 +6,7 @@ from typing import Any, Mapping from urllib.parse import urlsplit -DEFAULT_PORT = 8760 +DEFAULT_PORT = 8088 DEFAULT_MCP_PATH = "/mcp" diff --git a/src/adh/http_mcp.py b/src/adh/http_mcp.py index b5d18ca..73e24a6 100644 --- a/src/adh/http_mcp.py +++ b/src/adh/http_mcp.py @@ -3,6 +3,8 @@ from __future__ import annotations import json +import os +import uuid from typing import Any from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen @@ -16,10 +18,14 @@ class MCPTransportError(RuntimeError): class MCPHTTPClient: - def __init__(self, endpoint: HostEndpoint, *, timeout: float = 120.0) -> None: + def __init__(self, endpoint: HostEndpoint, *, timeout: float = 120.0, operator: bool = False) -> None: self.endpoint = endpoint self.timeout = timeout self.session_id: str | None = None + self.client_id = uuid.uuid4().hex + self.operator_token = os.environ.get("ADH_OPERATOR_TOKEN") if operator else None + if operator and not self.operator_token: + raise MCPTransportError("--operator requires ADH_OPERATOR_TOKEN in this process environment") def update_endpoint(self, endpoint: HostEndpoint) -> None: if endpoint.mcp_url != self.endpoint.mcp_url: @@ -32,10 +38,13 @@ def send(self, message: Any) -> Any | None: "Content-Type": "application/json", "Accept": "application/json", "User-Agent": f"adh/{__version__}", + "X-Adh-Client-Id": self.client_id, } if self.session_id: headers["Mcp-Session-Id"] = self.session_id request = Request(self.endpoint.mcp_url, data=body, headers=headers, method="POST") + if self.operator_token: + request.add_unredirected_header("X-Adh-Operator-Key", self.operator_token) try: with urlopen(request, timeout=self.timeout) as response: session_id = response.headers.get("Mcp-Session-Id") @@ -51,7 +60,10 @@ def send(self, message: Any) -> Any | None: f"MCP HTTP {exc.code} ({self.endpoint.mcp_url}): {detail or exc.reason}" ) from exc except (URLError, TimeoutError, OSError) as exc: - raise MCPTransportError(f"cannot connect to {self.endpoint.mcp_url}: {exc}") from exc + raise MCPTransportError( + f"MCP HTTP exchange failed ({self.endpoint.mcp_url}): {exc}; " + "Host/target execution may continue; inspect durable operations before retrying writes" + ) from exc except json.JSONDecodeError as exc: raise MCPTransportError(f"host returned invalid JSON: {exc}") from exc @@ -76,5 +88,6 @@ def probe_endpoint(endpoint: HostEndpoint, *, timeout: float = 3.0) -> HostEndpo "version": health.get("version"), "agents": health.get("agents"), "mcp_tools": health.get("mcpTools"), + "apps": health.get("apps", []), } ) diff --git a/src/adh/status.py b/src/adh/status.py new file mode 100644 index 0000000..c889678 --- /dev/null +++ b/src/adh/status.py @@ -0,0 +1,32 @@ +"""Read-only, versioned inventory consumed by desktop applications and Agents.""" +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +from typing import Any + +from . import __version__ +from .endpoint import HostEndpoint +from .http_mcp import probe_endpoint + + +def inventory(endpoints: list[HostEndpoint], *, timeout: float = 3.0) -> dict[str, Any]: + unique = list({endpoint.key: endpoint for endpoint in endpoints}.values()) + with ThreadPoolExecutor(max_workers=max(1, min(8, len(unique)))) as pool: + checked = list(pool.map(lambda endpoint: probe_endpoint(endpoint, timeout=timeout), unique)) + connections = [] + targets = [] + for endpoint in checked: + online = endpoint.properties.get("status") == "online" + connections.append({"endpoint": endpoint.mcp_url, "online": online, + "version": endpoint.properties.get("version"), + "error": None if online else "unreachable"}) + apps = endpoint.properties.get("apps") + for app in apps if isinstance(apps, list) else []: + if not isinstance(app, dict) or not isinstance(app.get("sessionId"), str): + continue + targets.append({"id": app["sessionId"], "name": str(app.get("package") or app["sessionId"]), + "package": app.get("package"), "pid": app.get("pid"), + "endpoint": endpoint.mcp_url, "online": online and app.get("online") is True}) + return {"schemaVersion": 1, "component": "adh", "version": __version__, + "checkedAt": datetime.now(timezone.utc).isoformat(), "connections": connections, "targets": targets} diff --git a/tests/test_agent_cli.py b/tests/test_agent_cli.py new file mode 100644 index 0000000..e8e90db --- /dev/null +++ b/tests/test_agent_cli.py @@ -0,0 +1,71 @@ +import json +import os +from pathlib import Path +import subprocess +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Thread + +import pytest + + +@pytest.fixture +def host(): + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps({"ok": True, "service": "adhd", "version": "test", "apps": [ + {"package": "com.example.live", "sessionId": "live-session", "pid": 42, "online": True}, + {"package": "com.example.old", "sessionId": "old-session", "pid": 43, "online": False}, + ]}).encode()) + + def do_POST(self): + data = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + result = {"tools": [{"name": "sessions", "description": "Live sessions", "inputSchema": {"type": "object"}}]} if data["method"] == "tools/list" else {"isError": True, "content": []} + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps({"jsonrpc": "2.0", "id": data["id"], "result": result}).encode()) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_port}" + server.shutdown() + server.server_close() + thread.join() + + +def run(tmp_path, *args): + env = {**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[1] / "src"), + "ADH_CONFIG_PATH": str(tmp_path / "connections.json"), "PYTHONIOENCODING": "utf-8"} + return subprocess.run([sys.executable, "-m", "adh", *args], env=env, capture_output=True, text=True, encoding="utf-8", timeout=15) + + +def test_status_reads_actual_health_without_saving_or_claiming_an_old_session_online(tmp_path, host): + result = run(tmp_path, "status", "--endpoint", host, "--json") + assert result.returncode == 0, result.stderr + status = json.loads(result.stdout) + assert status["component"] == "adh" and status["schemaVersion"] == 1 + assert status["connections"][0]["online"] is True + assert [(row["id"], row["online"]) for row in status["targets"]] == [("live-session", True), ("old-session", False)] + assert not (tmp_path / "connections.json").exists() + + +def test_unreachable_host_is_an_observation_not_a_fake_target(tmp_path): + result = run(tmp_path, "status", "--endpoint", "127.0.0.1:1", "--timeout", "0.1", "--json") + assert result.returncode == 0, result.stderr + status = json.loads(result.stdout) + assert status["connections"][0]["online"] is False + assert status["targets"] == [] + + +def test_tools_returns_real_schema_and_call_failure_has_nonzero_exit(tmp_path, host): + result = run(tmp_path, "tools", "--endpoint", host, "--json") + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout)["tools"][0]["inputSchema"] == {"type": "object"} + result = run(tmp_path, "call", "failure", "--endpoint", host, "--json") + assert result.returncode == 1 diff --git a/tests/test_endpoint.py b/tests/test_endpoint.py index bcdc989..277c21e 100644 --- a/tests/test_endpoint.py +++ b/tests/test_endpoint.py @@ -8,9 +8,9 @@ class EndpointTests(unittest.TestCase): def test_default_port_and_mcp_path(self) -> None: endpoint = HostEndpoint.from_url("192.168.1.8") - self.assertEqual(endpoint.port, 8760) - self.assertEqual(endpoint.mcp_url, "http://192.168.1.8:8760/mcp") - self.assertEqual(endpoint.panel_url, "http://192.168.1.8:8760/") + self.assertEqual(endpoint.port, 8088) + self.assertEqual(endpoint.mcp_url, "http://192.168.1.8:8088/mcp") + self.assertEqual(endpoint.panel_url, "http://192.168.1.8:8088/") def test_strips_mcp_suffix(self) -> None: endpoint = HostEndpoint.from_url("http://127.0.0.1:8760/mcp") diff --git a/tests/test_operations.py b/tests/test_operations.py new file mode 100644 index 0000000..912f046 --- /dev/null +++ b/tests/test_operations.py @@ -0,0 +1,112 @@ +import json +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Thread + +import pytest + +from adh import cli +from adh.endpoint import HostEndpoint +from adh.http_mcp import MCPHTTPClient, MCPTransportError + + +@pytest.fixture +def host(): + calls = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + data = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + args = data["params"]["arguments"] + calls.append((data, dict(self.headers))) + if args.get("action") == "snapshot": + value = {"ok": True, "revision": 7, "epoch": 2, "hostEpoch": 1} + elif args.get("action") == "submit": + value = {"ok": False, "code": "STALE_CONTROL", "error": "human changed state"} + else: + value = {"ok": True, "operation": {"id": "fixture-operation", "state": "cancel_requested"}} + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps({"jsonrpc": "2.0", "id": data["id"], "result": { + "content": [{"type": "text", "text": json.dumps(value)}], "isError": value.get("ok") is False, + }}).encode()) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_port}", calls + server.shutdown() + server.server_close() + thread.join() + + +def test_run_observes_once_preserves_versions_and_never_rebases_after_conflict(host, capsys): + endpoint, calls = host + result = cli.main(["run", "memory_write", "--arguments", '{"session":"fixture","hex":"41"}', + "--task-id", "fixture-task", "--idempotency-key", "one-intent", "--timeout-ms", "4567", + "--endpoint", endpoint, "--json"]) + assert result == 1 + assert json.loads(capsys.readouterr().out)["code"] == "STALE_CONTROL" + assert [call[0]["params"]["arguments"]["action"] for call in calls] == ["snapshot", "submit"] + metadata = calls[-1][0]["params"]["arguments"]["_operation"] + assert metadata == {"expectedRevision": 7, "controlEpoch": 2, "hostEpoch": 1, + "taskId": "fixture-task", "idempotencyKey": "one-intent", "timeoutMs": 4567} + + +def test_explicit_call_keeps_old_versions_for_host_to_reject(host): + endpoint, calls = host + assert cli.main(["call", "memory_write", "--arguments", '{"session":"fixture"}', + "--operation", '{"expectedRevision":0,"controlEpoch":0,"hostEpoch":0}', + "--endpoint", endpoint]) == 0 + assert len(calls) == 1 + assert calls[0][0]["params"]["arguments"]["_operation"]["expectedRevision"] == 0 + + +def test_operator_access_is_explicit_and_stable_client_id_binds_notifications(host, monkeypatch): + endpoint, calls = host + monkeypatch.setenv("ADH_OPERATOR_TOKEN", "synthetic-operator-token") + client = MCPHTTPClient(HostEndpoint.from_url(endpoint)) + message = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "operations", "arguments": {"action": "get"}}} + client.send(message) + client.send(message) + assert "X-Adh-Operator-Key" not in calls[0][1] + assert calls[0][1]["X-Adh-Client-Id"] == calls[1][1]["X-Adh-Client-Id"] + MCPHTTPClient(HostEndpoint.from_url(endpoint), operator=True).send(message) + assert calls[-1][1]["X-Adh-Operator-Key"] == "synthetic-operator-token" + monkeypatch.delenv("ADH_OPERATOR_TOKEN") + with pytest.raises(MCPTransportError, match="ADH_OPERATOR_TOKEN"): + MCPHTTPClient(HostEndpoint.from_url(endpoint), operator=True) + + +def test_task_get_cancel_and_pagination_preserve_requested_meaning(host): + endpoint, calls = host + assert cli.main(["tasks", "get", "fixture-operation", "--include-result", "--endpoint", endpoint]) == 0 + assert calls[-1][0]["params"]["arguments"]["includeResult"] is True + assert calls[-1][0]["params"]["arguments"]["id"] == "fixture-operation" + assert cli.main(["tasks", "cancel", "--task-id", "fixture-task", "--endpoint", endpoint]) == 0 + assert calls[-1][0]["params"]["arguments"]["taskId"] == "fixture-task" + assert cli.main(["tasks", "list", "--offset", "50", "--limit", "25", "--endpoint", endpoint]) == 0 + assert calls[-1][0]["params"]["arguments"]["offset"] == 50 + assert calls[-1][0]["params"]["arguments"]["limit"] == 25 + + +def test_control_explicit_versions_are_not_refreshed_and_partial_versions_are_rejected(host): + endpoint, calls = host + assert cli.main(["control", "release", "--revision", "4", "--epoch", "3", "--host-epoch", "2", + "--endpoint", endpoint]) == 0 + assert len(calls) == 1 + assert calls[-1][0]["params"]["arguments"]["_operation"] == {"expectedRevision": 4, "controlEpoch": 3, "hostEpoch": 2} + assert cli.main(["control", "release", "--revision", "4", "--endpoint", endpoint]) == 1 + assert len(calls) == 1 + + +def test_http_timeout_does_not_report_confirmed_cancellation(monkeypatch): + def timeout(*args, **kwargs): + raise TimeoutError('synthetic network timeout') + + monkeypatch.setattr('adh.http_mcp.urlopen', timeout) + client = MCPHTTPClient(HostEndpoint.from_url('127.0.0.1:1')) + with pytest.raises(MCPTransportError, match='execution may continue'): + client.send({'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call', 'params': {}})