"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
feat: add Web Yu-pri CLI harness
Codex0ac034236902
diff --git a/.gitignore b/.gitignoreindex 618c70154..0d858f379 100644--- a/.gitignore+++ b/.gitignore@@ -70,6 +70,7 @@!/minimax/!/ollama/!/browser/+!/web-yu-pri/!/seaclip/!/pm2/!/chromadb/@@ -143,6 +144,8 @@/ollama/.*/browser/*/browser/.*+/web-yu-pri/*+/web-yu-pri/.*/seaclip/*/seaclip/.*/pm2/*@@ -229,6 +232,7 @@!/minimax/agent-harness/!/ollama/agent-harness/!/browser/agent-harness/+!/web-yu-pri/agent-harness/!/seaclip/agent-harness/!/pm2/agent-harness/!/chromadb/agent-harness/diff --git a/README.md b/README.mdindex 9672f4ab2..d9e89fd81 100644--- a/README.md+++ b/README.md@@ -993,6 +993,13 @@ Each application received complete, production-ready CLI interfaces — not demo<td align="center">✅ <a href="browser/agent-harness/">New</a></td></tr><tr>+<td align="center"><strong><a href="web-yu-pri/agent-harness/">Web Yu-pri</a></strong></td>+<td>Japan Post Shipping Labels</td>+<td><code>cli-anything-web-yu-pri</code></td>+<td>Playwright + Web Yu-pri forms</td>+<td align="center">✅ <a href="web-yu-pri/agent-harness/">New</a></td>+</tr>+<tr><td align="center"><strong>📄 LibreOffice</strong></td><td>Office Suite (Writer, Calc, Impress)</td><td><code>cli-anything-libreoffice</code></td>@@ -1345,6 +1352,7 @@ cli-anything/├── ✏️ inkscape/agent-harness/ # Inkscape CLI (202 tests)├── 🎵 audacity/agent-harness/ # Audacity CLI (161 tests)├── 🌐 browser/agent-harness/ # Browser CLI (DOMShell MCP, new)+├── 🌐 web-yu-pri/agent-harness/ # Japan Post Web Yu-pri CLI (new)├── 📄 libreoffice/agent-harness/ # LibreOffice CLI (158 tests)├── 📧 mailchimp/agent-harness/ # Mailchimp Marketing API CLI (303 commands, 36 unit tests)├── 📚 zotero/agent-harness/ # Zotero CLI (new, write import support)diff --git a/registry.json b/registry.jsonindex 851cbafa1..b6462e4a7 100644--- a/registry.json+++ b/registry.json@@ -138,6 +138,25 @@}]},+ {+ "name": "web-yu-pri",+ "display_name": "Web Yu-pri",+ "version": "0.1.0",+ "description": "Japan Post Web Yu-pri browser workflow automation for login, inspection, screenshots, dry-run planning, and contents-form filling",+ "requires": "Japan Post Web Yu-pri account, Playwright, Microsoft Edge/Chrome or Playwright Chromium",+ "homepage": "https://mgr.post.japanpost.jp/C30P01Action.do",+ "source_url": null,+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=web-yu-pri/agent-harness",+ "entry_point": "cli-anything-web-yu-pri",+ "skill_md": "skills/cli-anything-web-yu-pri/SKILL.md",+ "category": "web",+ "contributors": [+ {+ "name": "CLI-Anything-Team",+ "url": "https://github.com/HKUDS/CLI-Anything"+ }+ ]+ },{"name": "comfyui","display_name": "ComfyUI",diff --git a/skills/cli-anything-web-yu-pri/SKILL.md b/skills/cli-anything-web-yu-pri/SKILL.mdnew file mode 100644index 000000000..af40f54be--- /dev/null+++ b/skills/cli-anything-web-yu-pri/SKILL.md@@ -0,0 +1,85 @@+---+name: "cli-anything-web-yu-pri"+description: Use Japan Post Web Yu-pri from a CLI by driving the real browser UI for login, inspection, screenshots, dry-run planning, and contents-form filling.+---++# Web Yu-pri CLI++Use this skill when a task involves Japan Post Web Yu-pri label entry at+`https://mgr.post.japanpost.jp/C30P01Action.do`, especially repetitive contents+line entry.++## Install++```bash+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=web-yu-pri/agent-harness+```++If no browser is found:++```bash+python -m playwright install chromium+```++## Safety Rules++- Do not put Japan Post credentials in commands, files, logs, or prompts.+- Use `open-login` so the user can log in manually in the persistent profile.+- Run `contents fill ... --dry-run --json` before live form filling.+- This CLI does not click final shipment confirmation or purchase buttons.+- Keep item lines separate when the source data has separate award/category+ lines, while preserving the requested declared total.++## Common Commands++```bash+cli-anything-web-yu-pri --json doctor+cli-anything-web-yu-pri open-login+cli-anything-web-yu-pri --json status --url https://mgr.post.japanpost.jp/M060800.do+cli-anything-web-yu-pri --json plan items.json+cli-anything-web-yu-pri --json contents fill items.json --dry-run+cli-anything-web-yu-pri --json contents fill items.json --total-value 17000+```++## Items File++JSON:++```json+{+ "items": [+ {"description": "Award plaque", "value": 8000, "quantity": 1, "country": "KR"},+ {"description": "Certificate", "value": 9000, "quantity": 1, "country": "KR"}+ ]+}+```++CSV headers can use these aliases:++- description: `description`, `desc`, `content`, `contents`, `item`, `name`, `pkg`+- value: `value`, `declared_value`, `cost`, `price`, `amount`, `yen`, `jpy`+- quantity: `quantity`, `qty`, `num`, `count`+- country: `country`, `country_code`, `country_of_origin`, `origin`, `couCd`, `cou_cd`+- HS code: `hs_code`, `hs`, `hscode`, `hsCode`++By default, `value` is treated as the line declared value. Use `--value-mode unit`+when value should be multiplied by quantity.++## Selector Diagnostics++```bash+cli-anything-web-yu-pri --json selectors+cli-anything-web-yu-pri snapshot --url https://mgr.post.japanpost.jp/M060800.do -o page.png --html-output page.html+```++Known contents-page controls:++- `#M060800_itemBean_pkg`+- `#M060800_itemBean_cost_value`+- `#M060800_itemBean_num_value`+- `#M060800_itemBean_couCd`+- `#M060800_itemBean_hsCode`+- `#M060800_shippingBean_pkgType`+- `#M060800_shippingBean_pkgTotalPrice_value`+- `#M060800_ShippingBean_danger`+- `submitCommand('itemAdd2')`diff --git a/web-yu-pri/agent-harness/README.md b/web-yu-pri/agent-harness/README.mdnew file mode 100644index 000000000..e22891683--- /dev/null+++ b/web-yu-pri/agent-harness/README.md@@ -0,0 +1,71 @@+# cli-anything-web-yu-pri++CLI harness for Japan Post Web Yu-pri label workflows.++This CLI drives the real Web Yu-pri browser UI through Playwright. It uses a+persistent local browser profile so you can log in manually once, then run+structured commands for repetitive form entry. It does not store passwords and+does not click final shipment confirmation buttons.++## Install++```bash+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=web-yu-pri/agent-harness+```++If Playwright cannot find a browser, install Microsoft Edge or Chrome, or run:++```bash+python -m playwright install chromium+```++## Quick Start++```bash+cli-anything-web-yu-pri doctor+cli-anything-web-yu-pri open-login+cli-anything-web-yu-pri plan items.json --json+cli-anything-web-yu-pri contents fill items.json --dry-run --json+cli-anything-web-yu-pri contents fill items.json --json+```++## Items File++JSON:++```json+{+ "items": [+ {"description": "Award plaque", "value": 8000, "quantity": 1, "country": "KR"},+ {"description": "Certificate", "value": 9000, "quantity": 1, "country": "KR"}+ ]+}+```++CSV:++```csv+description,value,quantity,country,hs_code+Award plaque,8000,1,KR,+Certificate,9000,1,KR,+```++`value` is a line value by default. Add `--value-mode unit` when value should be+multiplied by quantity.++## Commands++| Command | Description |+| --- | --- |+| `doctor` | Check local runtime and profile paths |+| `selectors` | Print the known Web Yu-pri selector map |+| `plan <items-file>` | Validate JSON/CSV/TSV items and compute totals |+| `open-login` | Open the login/start URL in the persistent profile |+| `status` | Inspect title, URL, and selector presence |+| `snapshot -o page.png` | Capture screenshot and optional HTML |+| `contents fill <items-file>` | Fill contents rows and declared total |++## Safety++`contents fill` stops after filling contents and totals. It returns a `safety`+object in JSON output with `final_submit_clicked: false`.diff --git a/web-yu-pri/agent-harness/WEB_YU_PRI.md b/web-yu-pri/agent-harness/WEB_YU_PRI.mdnew file mode 100644index 000000000..3a999f840--- /dev/null+++ b/web-yu-pri/agent-harness/WEB_YU_PRI.md@@ -0,0 +1,68 @@+# Web Yu-pri Harness SOP++## Purpose++This harness turns Japan Post's Web Yu-pri browser workflow into an+agent-friendly CLI. Web Yu-pri is a logged-in web application, so the CLI drives+the real browser UI through Playwright instead of reimplementing Japan Post+business logic.++## Backend Surface++- Official start URL: `https://mgr.post.japanpost.jp/C30P01Action.do`+- Known contents form URL: `https://mgr.post.japanpost.jp/M060800.do`+- Browser engine: Playwright Chromium with a persistent user profile+- Credentials: never accepted or stored by the CLI; users log in manually in the+ browser profile++## Safety Model++The first version automates repetitive data entry only. It fills item contents,+declared value totals, optional package type, and dangerous-goods flags, but it+does not click the final shipment confirmation/submit button. Agents should use+`--dry-run` before touching the real page, then inspect `verification` in JSON+output after a live fill.++## Commands++- `doctor` checks Playwright availability and profile paths.+- `selectors` prints the known selector map for page diagnostics.+- `plan <items-file>` validates JSON/CSV/TSV item files and computes totals.+- `open-login` opens the Web Yu-pri start URL in the persistent profile.+- `status` opens a URL and reports current title, URL, and selector presence.+- `snapshot` captures a screenshot and optional HTML dump.+- `contents fill <items-file>` fills item rows on the contents form.++## Input Model++The CLI accepts JSON, CSV, or TSV files. Each row supports the following aliases:++- description: `description`, `desc`, `content`, `contents`, `item`, `name`, `pkg`+- value: `value`, `declared_value`, `cost`, `price`, `amount`, `yen`, `jpy`+- quantity: `quantity`, `qty`, `num`, `count`+- country: `country`, `country_code`, `country_of_origin`, `origin`, `couCd`, `cou_cd`+- HS code: `hs_code`, `hs`, `hscode`, `hsCode`++By default, `value` is treated as the line declared value. Use+`--value-mode unit` when `value` is a unit value that should be multiplied by+quantity.++## Known Web Yu-pri Selectors++- Item description: `#M060800_itemBean_pkg`+- Item value: `#M060800_itemBean_cost_value`+- Item quantity: `#M060800_itemBean_num_value`+- Country of origin: `#M060800_itemBean_couCd`+- HS code: `#M060800_itemBean_hsCode`+- Package type: `#M060800_shippingBean_pkgType`+- Total declared value: `#M060800_shippingBean_pkgTotalPrice_value`+- Dangerous-goods flag: `#M060800_ShippingBean_danger`+- Add item command: `submitCommand('itemAdd2')`++## Test Strategy++Unit tests cover item parsing, total computation, selector publication, and dry+run output without launching a browser. The E2E test file includes a real CLI+dry-run workflow and an optional live test gated by `WEB_YU_PRI_LIVE_E2E=1`,+because live execution requires a Japan Post account and a real logged-in+session.diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/README.md b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/README.mdnew file mode 100644index 000000000..e22891683--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/README.md@@ -0,0 +1,71 @@+# cli-anything-web-yu-pri++CLI harness for Japan Post Web Yu-pri label workflows.++This CLI drives the real Web Yu-pri browser UI through Playwright. It uses a+persistent local browser profile so you can log in manually once, then run+structured commands for repetitive form entry. It does not store passwords and+does not click final shipment confirmation buttons.++## Install++```bash+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=web-yu-pri/agent-harness+```++If Playwright cannot find a browser, install Microsoft Edge or Chrome, or run:++```bash+python -m playwright install chromium+```++## Quick Start++```bash+cli-anything-web-yu-pri doctor+cli-anything-web-yu-pri open-login+cli-anything-web-yu-pri plan items.json --json+cli-anything-web-yu-pri contents fill items.json --dry-run --json+cli-anything-web-yu-pri contents fill items.json --json+```++## Items File++JSON:++```json+{+ "items": [+ {"description": "Award plaque", "value": 8000, "quantity": 1, "country": "KR"},+ {"description": "Certificate", "value": 9000, "quantity": 1, "country": "KR"}+ ]+}+```++CSV:++```csv+description,value,quantity,country,hs_code+Award plaque,8000,1,KR,+Certificate,9000,1,KR,+```++`value` is a line value by default. Add `--value-mode unit` when value should be+multiplied by quantity.++## Commands++| Command | Description |+| --- | --- |+| `doctor` | Check local runtime and profile paths |+| `selectors` | Print the known Web Yu-pri selector map |+| `plan <items-file>` | Validate JSON/CSV/TSV items and compute totals |+| `open-login` | Open the login/start URL in the persistent profile |+| `status` | Inspect title, URL, and selector presence |+| `snapshot -o page.png` | Capture screenshot and optional HTML |+| `contents fill <items-file>` | Fill contents rows and declared total |++## Safety++`contents fill` stops after filling contents and totals. It returns a `safety`+object in JSON output with `final_submit_clicked: false`.diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/__init__.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/__init__.pynew file mode 100644index 000000000..5672e0bec--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/__init__.py@@ -0,0 +1,3 @@+"""CLI-Anything harness for Japan Post Web Yu-pri."""++__version__ = "0.1.0"diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/__main__.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/__main__.pynew file mode 100644index 000000000..7e0c00594--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/__main__.py@@ -0,0 +1,5 @@+from .web_yu_pri_cli import main+++if __name__ == "__main__":+ main()diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/__init__.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/__init__.pynew file mode 100644index 000000000..70783e70c--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/__init__.py@@ -0,0 +1 @@+"""Core helpers for Web Yu-pri automation."""diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/browser.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/browser.pynew file mode 100644index 000000000..148ca168c--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/browser.py@@ -0,0 +1,383 @@+"""Playwright backend for the real Web Yu-pri web application."""++from __future__ import annotations++import json+import time+from contextlib import contextmanager+from pathlib import Path+from typing import Any, Iterator++from .items import ItemLine, build_contents_plan++LOGIN_URL = "https://mgr.post.japanpost.jp/C30P01Action.do"+CONTENTS_URL = "https://mgr.post.japanpost.jp/M060800.do"++SELECTORS = {+ "item_description": "#M060800_itemBean_pkg",+ "item_value": "#M060800_itemBean_cost_value",+ "item_quantity": "#M060800_itemBean_num_value",+ "item_country": "#M060800_itemBean_couCd",+ "item_hs_code": "#M060800_itemBean_hsCode",+ "package_type": "#M060800_shippingBean_pkgType",+ "total_value": "#M060800_shippingBean_pkgTotalPrice_value",+ "danger": "#M060800_ShippingBean_danger",+}++ADD_ITEM_COMMAND = "itemAdd2"+++def default_profile_dir() -> Path:+ return Path.home() / ".cli-anything-web-yu-pri" / "profile"+++def selector_report() -> dict[str, Any]:+ return {+ "login_url": LOGIN_URL,+ "contents_url": CONTENTS_URL,+ "selectors": SELECTORS,+ "add_item_command": ADD_ITEM_COMMAND,+ }+++def doctor(profile_dir: str | Path | None = None) -> dict[str, Any]:+ result: dict[str, Any] = {+ "profile_dir": str(Path(profile_dir).expanduser() if profile_dir else default_profile_dir()),+ "login_url": LOGIN_URL,+ "contents_url": CONTENTS_URL,+ "playwright_available": False,+ "notes": [],+ }+ try:+ import playwright # noqa: F401++ result["playwright_available"] = True+ except Exception as exc: # pragma: no cover - depends on runtime environment+ result["notes"].append(f"playwright import failed: {exc}")+ return result+++@contextmanager+def browser_session(+ profile_dir: str | Path | None = None,+ headless: bool = False,+ browser_channel: str | None = None,+) -> Iterator[tuple[Any, Any]]:+ """Launch a persistent browser context and yield (page, context)."""++ try:+ from playwright.sync_api import Error as PlaywrightError+ from playwright.sync_api import sync_playwright+ except ImportError as exc: # pragma: no cover - dependency exercised via CLI doctor+ raise RuntimeError(+ "playwright is required. Install with: pip install cli-anything-web-yu-pri"+ ) from exc++ user_data_dir = Path(profile_dir).expanduser() if profile_dir else default_profile_dir()+ user_data_dir.mkdir(parents=True, exist_ok=True)++ playwright = sync_playwright().start()+ context = None+ errors: list[str] = []+ channels = [browser_channel] if browser_channel else ["msedge", "chrome", None]+ try:+ for channel in channels:+ try:+ kwargs: dict[str, Any] = {+ "headless": headless,+ "args": ["--disable-blink-features=AutomationControlled"],+ }+ if channel:+ kwargs["channel"] = channel+ context = playwright.chromium.launch_persistent_context(+ str(user_data_dir),+ **kwargs,+ )+ break+ except PlaywrightError as exc:+ label = channel or "bundled-chromium"+ errors.append(f"{label}: {exc}")+ if context is None:+ detail = " | ".join(errors) if errors else "no browser channels attempted"+ raise RuntimeError(f"could not launch Chromium/Edge browser: {detail}")++ page = context.pages[0] if context.pages else context.new_page()+ yield page, context+ finally:+ if context is not None:+ context.close()+ playwright.stop()+++def open_login(+ url: str = LOGIN_URL,+ profile_dir: str | Path | None = None,+ headless: bool = False,+ browser_channel: str | None = None,+) -> dict[str, Any]:+ with browser_session(profile_dir=profile_dir, headless=headless, browser_channel=browser_channel) as (+ page,+ _context,+ ):+ page.goto(url, wait_until="domcontentloaded")+ return inspect_page(page)+++def inspect_url(+ url: str = LOGIN_URL,+ profile_dir: str | Path | None = None,+ headless: bool = False,+ browser_channel: str | None = None,+) -> dict[str, Any]:+ with browser_session(profile_dir=profile_dir, headless=headless, browser_channel=browser_channel) as (+ page,+ _context,+ ):+ page.goto(url, wait_until="domcontentloaded")+ return inspect_page(page)+++def capture_snapshot(+ url: str,+ output: str | Path,+ html_output: str | Path | None = None,+ profile_dir: str | Path | None = None,+ headless: bool = False,+ browser_channel: str | None = None,+) -> dict[str, Any]:+ output_path = Path(output).expanduser().resolve()+ output_path.parent.mkdir(parents=True, exist_ok=True)+ html_path = Path(html_output).expanduser().resolve() if html_output else None+ if html_path:+ html_path.parent.mkdir(parents=True, exist_ok=True)++ with browser_session(profile_dir=profile_dir, headless=headless, browser_channel=browser_channel) as (+ page,+ _context,+ ):+ page.goto(url, wait_until="domcontentloaded")+ page.screenshot(path=str(output_path), full_page=True)+ if html_path:+ html_path.write_text(page.content(), encoding="utf-8")+ info = inspect_page(page)+ info["screenshot"] = str(output_path)+ if html_path:+ info["html"] = str(html_path)+ return info+++def inspect_page(page: Any) -> dict[str, Any]:+ """Return cheap, JSON-safe page facts."""++ selector_presence = {+ name: page.locator(selector).count() > 0 for name, selector in SELECTORS.items()+ }+ return {+ "url": page.url,+ "title": page.title(),+ "has_contents_form": all(+ selector_presence[key]+ for key in ("item_description", "item_value", "item_quantity", "total_value")+ ),+ "selectors": selector_presence,+ }+++def fill_contents(+ items: list[ItemLine],+ total_value: int | None = None,+ value_mode: str = "line",+ url: str = CONTENTS_URL,+ profile_dir: str | Path | None = None,+ package_type: str | None = None,+ danger: bool | None = None,+ headless: bool = False,+ browser_channel: str | None = None,+ delay_ms: int = 500,+) -> dict[str, Any]:+ """Fill the known Web Yu-pri contents form and add each item line."""++ plan = build_contents_plan(items, total_value=total_value, value_mode=value_mode)+ with browser_session(profile_dir=profile_dir, headless=headless, browser_channel=browser_channel) as (+ page,+ _context,+ ):+ page.goto(url, wait_until="domcontentloaded")+ _require_selector(page, SELECTORS["item_description"])++ if package_type:+ _set_value(page, SELECTORS["package_type"], package_type)+ if danger is not None:+ _set_boolean(page, SELECTORS["danger"], danger)++ added: list[dict[str, Any]] = []+ for item in items:+ _fill_item(page, item)+ before = _body_fingerprint(page)+ _run_submit_command(page, ADD_ITEM_COMMAND)+ _wait_after_submit(page, before=before, delay_ms=delay_ms)+ added.append(+ {+ "description": item.description,+ "value": item.value,+ "quantity": item.quantity,+ "country": item.country,+ "hs_code": item.hs_code,+ }+ )++ _set_value(page, SELECTORS["total_value"], str(plan["declared_total"]))+ info = inspect_page(page)+ verification = _verify_descriptions(page, [item.description for item in items])+ return {+ "status": "filled",+ "plan": plan,+ "added": added,+ "page": info,+ "verification": verification,+ "safety": {+ "final_submit_clicked": False,+ "message": "Contents were filled only; final shipment confirmation is not clicked.",+ },+ }+++def build_dry_run(+ items: list[ItemLine],+ total_value: int | None = None,+ value_mode: str = "line",+ package_type: str | None = None,+ danger: bool | None = None,+) -> dict[str, Any]:+ plan = build_contents_plan(items, total_value=total_value, value_mode=value_mode)+ return {+ "dry_run": True,+ "plan": plan,+ "selectors": SELECTORS,+ "add_item_command": ADD_ITEM_COMMAND,+ "package_type": package_type,+ "danger": danger,+ "safety": {+ "browser_launched": False,+ "final_submit_clicked": False,+ },+ }+++def _fill_item(page: Any, item: ItemLine) -> None:+ _set_value(page, SELECTORS["item_description"], item.description)+ _set_value(page, SELECTORS["item_value"], str(item.value))+ _set_value(page, SELECTORS["item_quantity"], str(item.quantity))+ if item.country:+ _set_value(page, SELECTORS["item_country"], item.country)+ if item.hs_code:+ _set_value(page, SELECTORS["item_hs_code"], item.hs_code)+++def _require_selector(page: Any, selector: str, timeout_ms: int = 15_000) -> None:+ try:+ page.wait_for_selector(selector, timeout=timeout_ms)+ except Exception as exc:+ info = {+ "url": page.url,+ "title": page.title(),+ "expected_selector": selector,+ }+ raise RuntimeError(+ "Web Yu-pri contents form was not found. "+ f"Page facts: {json.dumps(info, ensure_ascii=False)}"+ ) from exc+++def _set_value(page: Any, selector: str, value: str) -> None:+ locator = page.locator(selector)+ if locator.count() == 0:+ return+ try:+ tag_name = locator.first.evaluate("el => el.tagName.toLowerCase()")+ if tag_name == "select":+ locator.first.select_option(value)+ else:+ locator.first.fill(str(value))+ except Exception:+ locator.first.evaluate(+ """(el, value) => {+ el.value = value;+ el.dispatchEvent(new Event('input', {bubbles: true}));+ el.dispatchEvent(new Event('change', {bubbles: true}));+ }""",+ str(value),+ )+++def _set_boolean(page: Any, selector: str, value: bool) -> None:+ locator = page.locator(selector)+ if locator.count() == 0:+ return+ try:+ input_type = locator.first.evaluate("el => (el.type || '').toLowerCase()")+ if input_type in {"checkbox", "radio"}:+ locator.first.set_checked(value)+ return+ except Exception:+ pass+ locator.first.evaluate(+ """(el, value) => {+ el.checked = Boolean(value);+ el.value = value ? '1' : '';+ el.dispatchEvent(new Event('change', {bubbles: true}));+ }""",+ value,+ )+++def _run_submit_command(page: Any, command: str) -> None:+ page.evaluate(+ """command => {+ if (typeof window.submitCommand === 'function') {+ window.submitCommand(command);+ return;+ }+ throw new Error('submitCommand is not available on this page');+ }""",+ command,+ )+++def _wait_after_submit(page: Any, before: str, delay_ms: int) -> None:+ try:+ page.wait_for_load_state("domcontentloaded", timeout=10_000)+ except Exception:+ pass+ deadline = time.time() + 10+ while time.time() < deadline:+ time.sleep(max(delay_ms, 100) / 1000)+ if _body_fingerprint(page) != before:+ return+++def _body_fingerprint(page: Any) -> str:+ try:+ return page.evaluate(+ """() => {+ const text = document.body ? document.body.innerText : '';+ const inputs = Array.from(document.querySelectorAll('input,select,textarea'))+ .slice(0, 200)+ .map(el => `${el.id || el.name || ''}:${el.value || ''}`)+ .join('|');+ return `${location.href}|${text.length}|${inputs.length}|${inputs}`;+ }"""+ )+ except Exception:+ return f"{page.url}:{time.time()}"+++def _verify_descriptions(page: Any, descriptions: list[str]) -> dict[str, Any]:+ body_text = page.evaluate("() => document.body ? document.body.innerText : ''")+ found = [description for description in descriptions if description in body_text]+ missing = [description for description in descriptions if description not in body_text]+ return {+ "descriptions_found": found,+ "descriptions_missing": missing,+ "all_found": not missing,+ }diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/items.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/items.pynew file mode 100644index 000000000..53bbd1afb--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/core/items.py@@ -0,0 +1,202 @@+"""Input normalization for Web Yu-pri contents lines."""++from __future__ import annotations++import csv+import json+import re+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any, Iterable+++DESCRIPTION_KEYS = ("description", "desc", "content", "contents", "item", "name", "pkg")+VALUE_KEYS = ("value", "declared_value", "cost", "price", "amount", "yen", "jpy")+QUANTITY_KEYS = ("quantity", "qty", "num", "count")+COUNTRY_KEYS = ("country", "country_code", "country_of_origin", "origin", "couCd", "cou_cd")+HS_KEYS = ("hs_code", "hs", "hscode", "hsCode")+_MISSING = object()+++@dataclass(frozen=True)+class ItemLine:+ """One declared contents line for a Web Yu-pri shipment."""++ description: str+ value: int+ quantity: int = 1+ country: str | None = None+ hs_code: str | None = None++ def to_dict(self, value_mode: str = "line") -> dict[str, Any]:+ line_total = self.line_total(value_mode=value_mode)+ data = asdict(self)+ data["line_total"] = line_total+ data["value_mode"] = value_mode+ return data++ def line_total(self, value_mode: str = "line") -> int:+ if value_mode == "unit":+ return self.value * self.quantity+ if value_mode == "line":+ return self.value+ raise ValueError("value_mode must be 'line' or 'unit'")+++def load_items(path: str | Path, default_country: str | None = None) -> list[ItemLine]:+ """Load contents lines from JSON, CSV, or TSV."""++ input_path = Path(path)+ suffix = input_path.suffix.lower()+ if suffix == ".json":+ return _load_json(input_path, default_country=default_country)+ if suffix in {".csv", ".tsv"}:+ delimiter = "\t" if suffix == ".tsv" else ","+ return _load_delimited(input_path, delimiter=delimiter, default_country=default_country)+ raise ValueError("items file must be .json, .csv, or .tsv")+++def build_contents_plan(+ items: Iterable[ItemLine],+ total_value: int | None = None,+ value_mode: str = "line",+) -> dict[str, Any]:+ """Build a deterministic fill plan for the contents form."""++ if value_mode not in {"line", "unit"}:+ raise ValueError("value_mode must be 'line' or 'unit'")++ item_list = list(items)+ if not item_list:+ raise ValueError("at least one item line is required")++ computed_total = sum(item.line_total(value_mode=value_mode) for item in item_list)+ declared_total = computed_total if total_value is None else _coerce_int(+ total_value, "total_value", minimum=0+ )++ warnings: list[str] = []+ if declared_total != computed_total:+ warnings.append(+ f"declared total {declared_total} does not match computed item total {computed_total}"+ )++ return {+ "item_count": len(item_list),+ "computed_total": computed_total,+ "declared_total": declared_total,+ "total_matches": declared_total == computed_total,+ "value_mode": value_mode,+ "warnings": warnings,+ "items": [item.to_dict(value_mode=value_mode) for item in item_list],+ }+++def parse_item_mapping(row: dict[str, Any], default_country: str | None = None) -> ItemLine:+ """Normalize one user-provided mapping into an ItemLine."""++ description = str(_pick(row, DESCRIPTION_KEYS, "description")).strip()+ if not description:+ raise ValueError("description cannot be blank")++ value = _coerce_int(_pick(row, VALUE_KEYS, "value"), "value", minimum=0)+ quantity = _coerce_int(_pick(row, QUANTITY_KEYS, "quantity", default=1), "quantity", minimum=1)++ raw_country = _pick(row, COUNTRY_KEYS, "country", default=default_country)+ country = _normalize_country(raw_country)+ hs_code = _normalize_hs_code(_pick(row, HS_KEYS, "hs_code", default=None))++ return ItemLine(+ description=description,+ value=value,+ quantity=quantity,+ country=country,+ hs_code=hs_code,+ )+++def _load_json(path: Path, default_country: str | None = None) -> list[ItemLine]:+ with path.open("r", encoding="utf-8-sig") as handle:+ payload = json.load(handle)++ if isinstance(payload, dict):+ rows = payload.get("items")+ if rows is None:+ raise ValueError("JSON object must contain an 'items' array")+ else:+ rows = payload++ if not isinstance(rows, list):+ raise ValueError("items payload must be a list")++ return [parse_item_mapping(_require_mapping(row), default_country=default_country) for row in rows]+++def _load_delimited(+ path: Path,+ delimiter: str,+ default_country: str | None = None,+) -> list[ItemLine]:+ with path.open("r", encoding="utf-8-sig", newline="") as handle:+ reader = csv.DictReader(handle, delimiter=delimiter)+ if not reader.fieldnames:+ raise ValueError("CSV/TSV file must include a header row")+ return [+ parse_item_mapping(dict(row), default_country=default_country)+ for row in reader+ if any(str(value or "").strip() for value in row.values())+ ]+++def _pick(+ row: dict[str, Any],+ keys: tuple[str, ...],+ label: str,+ default: Any = _MISSING,+) -> Any:+ for key in keys:+ if key in row and row[key] not in (None, ""):+ return row[key]+ if default is not _MISSING:+ return default+ raise ValueError(f"missing required field: {label}")+++def _require_mapping(value: Any) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise ValueError("each item must be an object/mapping")+ return value+++def _coerce_int(value: Any, label: str, minimum: int) -> int:+ if isinstance(value, bool):+ raise ValueError(f"{label} must be an integer")+ if isinstance(value, int):+ result = value+ else:+ text = str(value).strip()+ text = re.sub(r"[,\sJPYjpy¥¥円]", "", text)+ if not re.fullmatch(r"-?\d+", text):+ raise ValueError(f"{label} must be an integer")+ result = int(text)+ if result < minimum:+ raise ValueError(f"{label} must be >= {minimum}")+ return result+++def _normalize_country(value: Any) -> str | None:+ if value in (None, ""):+ return None+ text = str(value).strip().upper()+ if not re.fullmatch(r"[A-Z]{2}", text):+ raise ValueError("country must be a two-letter ISO code, for example KR or US")+ return text+++def _normalize_hs_code(value: Any) -> str | None:+ if value in (None, ""):+ return None+ text = re.sub(r"\s+", "", str(value).strip())+ if not re.fullmatch(r"[0-9A-Za-z.\-]{2,20}", text):+ raise ValueError("hs_code may contain only letters, digits, dots, and hyphens")+ return textdiff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/skills/SKILL.md b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/skills/SKILL.mdnew file mode 100644index 000000000..d3912ea4e--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/skills/SKILL.md@@ -0,0 +1,85 @@+---+name: cli-anything-web-yu-pri+description: Use Japan Post Web Yu-pri from a CLI by driving the real browser UI for login, inspection, screenshots, dry-run planning, and contents-form filling.+---++# Web Yu-pri CLI++Use this skill when a task involves Japan Post Web Yu-pri label entry at+`https://mgr.post.japanpost.jp/C30P01Action.do`, especially repetitive contents+line entry.++## Install++```bash+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=web-yu-pri/agent-harness+```++If no browser is found:++```bash+python -m playwright install chromium+```++## Safety Rules++- Do not put Japan Post credentials in commands, files, logs, or prompts.+- Use `open-login` so the user can log in manually in the persistent profile.+- Run `contents fill ... --dry-run --json` before live form filling.+- This CLI does not click final shipment confirmation or purchase buttons.+- Keep item lines separate when the source data has separate award/category+ lines, while preserving the requested declared total.++## Common Commands++```bash+cli-anything-web-yu-pri --json doctor+cli-anything-web-yu-pri open-login+cli-anything-web-yu-pri --json status --url https://mgr.post.japanpost.jp/M060800.do+cli-anything-web-yu-pri --json plan items.json+cli-anything-web-yu-pri --json contents fill items.json --dry-run+cli-anything-web-yu-pri --json contents fill items.json --total-value 17000+```++## Items File++JSON:++```json+{+ "items": [+ {"description": "Award plaque", "value": 8000, "quantity": 1, "country": "KR"},+ {"description": "Certificate", "value": 9000, "quantity": 1, "country": "KR"}+ ]+}+```++CSV headers can use these aliases:++- description: `description`, `desc`, `content`, `contents`, `item`, `name`, `pkg`+- value: `value`, `declared_value`, `cost`, `price`, `amount`, `yen`, `jpy`+- quantity: `quantity`, `qty`, `num`, `count`+- country: `country`, `country_code`, `country_of_origin`, `origin`, `couCd`, `cou_cd`+- HS code: `hs_code`, `hs`, `hscode`, `hsCode`++By default, `value` is treated as the line declared value. Use `--value-mode unit`+when value should be multiplied by quantity.++## Selector Diagnostics++```bash+cli-anything-web-yu-pri --json selectors+cli-anything-web-yu-pri snapshot --url https://mgr.post.japanpost.jp/M060800.do -o page.png --html-output page.html+```++Known contents-page controls:++- `#M060800_itemBean_pkg`+- `#M060800_itemBean_cost_value`+- `#M060800_itemBean_num_value`+- `#M060800_itemBean_couCd`+- `#M060800_itemBean_hsCode`+- `#M060800_shippingBean_pkgType`+- `#M060800_shippingBean_pkgTotalPrice_value`+- `#M060800_ShippingBean_danger`+- `submitCommand('itemAdd2')`diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/TEST.md b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/TEST.mdnew file mode 100644index 000000000..c93e51ed5--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/TEST.md@@ -0,0 +1,98 @@+# Test Plan: cli-anything-web-yu-pri++## Test Inventory Plan++- `test_core.py`: 12 unit/CLI smoke tests planned.+- `test_full_e2e.py`: 2 E2E tests planned.++## Unit Test Plan++### `core.items`++- JSON item loading from array and object payloads.+- CSV loading with aliases.+- Value parsing with commas and yen markers.+- Quantity validation.+- Country validation.+- Total computation in `line` and `unit` value modes.+- Declared total mismatch warning.++### `core.browser`++- Selector report returns the known Web Yu-pri form fields.+- Dry-run output includes safety metadata and does not launch a browser.++### CLI++- `--help` exits successfully.+- `plan --json` emits machine-readable totals.+- `contents fill --dry-run --json` emits browser-free dry-run output.++## E2E Test Plan++### Dry-run CLI workflow++Simulates an agent validating a contents file before touching the real site.+Operations:++1. Write a JSON item file.+2. Run `python -m cli_anything.web_yu_pri.web_yu_pri_cli --json contents fill ... --dry-run`.+3. Verify JSON structure, total, selector map, and safety metadata.++### Optional live Web Yu-pri workflow++Live execution requires a Japan Post account and a logged-in profile, so it is+gated by `WEB_YU_PRI_LIVE_E2E=1`. It runs `status` against the contents URL and+verifies the CLI can inspect the real page. Form mutation is intentionally not+part of default CI.++## Test Results++Command:++```bash+python -m pytest cli_anything/web_yu_pri/tests -v+```++Result:++```text+collected 14 items++cli_anything/web_yu_pri/tests/test_core.py::test_parse_item_mapping_aliases PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_parse_item_rejects_bad_country PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_load_json_object_payload PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_load_csv_aliases PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_plan_line_value_mode PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_plan_unit_value_mode PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_plan_warns_declared_total_mismatch PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_selector_report_contains_contents_controls PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_build_dry_run_has_safety_metadata PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_cli_help PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_cli_plan_json PASSED+cli_anything/web_yu_pri/tests/test_core.py::test_cli_contents_fill_dry_run_json PASSED+cli_anything/web_yu_pri/tests/test_full_e2e.py::test_dry_run_cli_workflow PASSED+cli_anything/web_yu_pri/tests/test_full_e2e.py::test_live_status_against_contents_page SKIPPED++13 passed, 1 skipped+```++Additional checks:++```text+python .github/scripts/validate_root_skills.py+Root skills validation passed.++python -m json.tool registry.json+passed++python -m build+passed++python -m twine check dist/*+PASSED+```++Coverage note: default tests do not log into Japan Post or mutate a real+shipment. The live status test is gated by `WEB_YU_PRI_LIVE_E2E=1` because it+requires a real account and persistent browser profile.diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/__init__.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/__init__.pynew file mode 100644index 000000000..dce3a4085--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/__init__.py@@ -0,0 +1 @@+"""Tests for cli-anything-web-yu-pri."""diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/test_core.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/test_core.pynew file mode 100644index 000000000..c06380d28--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/test_core.py@@ -0,0 +1,125 @@+"""Core tests for cli-anything-web-yu-pri."""++import json++from click.testing import CliRunner+import pytest++from cli_anything.web_yu_pri.core.browser import ADD_ITEM_COMMAND, SELECTORS, build_dry_run, selector_report+from cli_anything.web_yu_pri.core.items import (+ ItemLine,+ build_contents_plan,+ load_items,+ parse_item_mapping,+)+from cli_anything.web_yu_pri.web_yu_pri_cli import cli+++def test_parse_item_mapping_aliases():+ item = parse_item_mapping(+ {+ "pkg": "Award plaque",+ "cost": "8,000",+ "num": "2",+ "couCd": "kr",+ "hsCode": "4901.99",+ }+ )+ assert item.description == "Award plaque"+ assert item.value == 8000+ assert item.quantity == 2+ assert item.country == "KR"+ assert item.hs_code == "4901.99"+++def test_parse_item_rejects_bad_country():+ with pytest.raises(ValueError, match="country"):+ parse_item_mapping({"description": "x", "value": 1, "country": "KOR"})+++def test_load_json_object_payload(tmp_path):+ path = tmp_path / "items.json"+ path.write_text(+ json.dumps({"items": [{"description": "Certificate", "value": 9000}]}),+ encoding="utf-8",+ )+ items = load_items(path, default_country="KR")+ assert items == [ItemLine(description="Certificate", value=9000, quantity=1, country="KR")]+++def test_load_csv_aliases(tmp_path):+ path = tmp_path / "items.csv"+ path.write_text("name,amount,qty,origin\nMedal,1000,3,US\n", encoding="utf-8")+ items = load_items(path)+ assert items[0].description == "Medal"+ assert items[0].value == 1000+ assert items[0].quantity == 3+ assert items[0].country == "US"+++def test_plan_line_value_mode():+ plan = build_contents_plan(+ [+ ItemLine(description="A", value=8000, quantity=2),+ ItemLine(description="B", value=9000, quantity=1),+ ],+ value_mode="line",+ )+ assert plan["computed_total"] == 17000+ assert plan["items"][0]["line_total"] == 8000+++def test_plan_unit_value_mode():+ plan = build_contents_plan(+ [+ ItemLine(description="A", value=4000, quantity=2),+ ItemLine(description="B", value=9000, quantity=1),+ ],+ value_mode="unit",+ )+ assert plan["computed_total"] == 17000+ assert plan["items"][0]["line_total"] == 8000+++def test_plan_warns_declared_total_mismatch():+ plan = build_contents_plan([ItemLine(description="A", value=100)], total_value=200)+ assert plan["total_matches"] is False+ assert plan["warnings"]+++def test_selector_report_contains_contents_controls():+ report = selector_report()+ assert report["selectors"]["item_description"] == SELECTORS["item_description"]+ assert report["add_item_command"] == ADD_ITEM_COMMAND+++def test_build_dry_run_has_safety_metadata():+ dry = build_dry_run([ItemLine(description="A", value=100)])+ assert dry["dry_run"] is True+ assert dry["safety"]["browser_launched"] is False+ assert dry["safety"]["final_submit_clicked"] is False+++def test_cli_help():+ result = CliRunner().invoke(cli, ["--help"])+ assert result.exit_code == 0+ assert "contents" in result.output+++def test_cli_plan_json(tmp_path):+ path = tmp_path / "items.json"+ path.write_text(json.dumps([{"description": "A", "value": 100}]), encoding="utf-8")+ result = CliRunner().invoke(cli, ["--json", "plan", str(path)])+ assert result.exit_code == 0+ data = json.loads(result.output)+ assert data["computed_total"] == 100+++def test_cli_contents_fill_dry_run_json(tmp_path):+ path = tmp_path / "items.json"+ path.write_text(json.dumps([{"description": "A", "value": 100}]), encoding="utf-8")+ result = CliRunner().invoke(cli, ["--json", "contents", "fill", str(path), "--dry-run"])+ assert result.exit_code == 0+ data = json.loads(result.output)+ assert data["dry_run"] is True+ assert data["plan"]["declared_total"] == 100diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/test_full_e2e.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/test_full_e2e.pynew file mode 100644index 000000000..b75cc37ca--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/tests/test_full_e2e.py@@ -0,0 +1,45 @@+"""E2E tests for cli-anything-web-yu-pri."""++import json+import os+import subprocess+import sys++import pytest+++def _run_cli(args, check=True):+ command = [sys.executable, "-m", "cli_anything.web_yu_pri.web_yu_pri_cli"] + args+ return subprocess.run(command, capture_output=True, text=True, check=check)+++def test_dry_run_cli_workflow(tmp_path):+ items_path = tmp_path / "items.json"+ items_path.write_text(+ json.dumps(+ {+ "items": [+ {"description": "Award plaque", "value": 8000, "quantity": 1, "country": "KR"},+ {"description": "Certificate", "value": 9000, "quantity": 1, "country": "KR"},+ ]+ }+ ),+ encoding="utf-8",+ )+ result = _run_cli(["--json", "contents", "fill", str(items_path), "--dry-run"])+ data = json.loads(result.stdout)+ assert data["dry_run"] is True+ assert data["plan"]["computed_total"] == 17000+ assert data["safety"]["final_submit_clicked"] is False+ assert "item_description" in data["selectors"]+++ os.environ.get("WEB_YU_PRI_LIVE_E2E") != "1",+ reason="requires a real Japan Post account and logged-in browser profile",+)+def test_live_status_against_contents_page():+ result = _run_cli(["--json", "status", "--url", "https://mgr.post.japanpost.jp/M060800.do"])+ data = json.loads(result.stdout)+ assert data["url"].startswith("https://mgr.post.japanpost.jp/")+ assert "title" in datadiff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/utils/__init__.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/utils/__init__.pynew file mode 100644index 000000000..d7e127ba1--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/utils/__init__.py@@ -0,0 +1 @@+"""Utility modules for the Web Yu-pri harness."""diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/utils/repl_skin.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/utils/repl_skin.pynew file mode 100644index 000000000..bc1fb6d1d--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/utils/repl_skin.py@@ -0,0 +1,567 @@+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.++Copy this file into your CLI package at:+ cli_anything/<software>/utils/repl_skin.py++Usage:+ from cli_anything.<software>.utils.repl_skin import ReplSkin++ skin = ReplSkin("shotcut", version="1.0.0")+ skin.print_banner() # auto-detects repo-root or packaged SKILL.md+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)+ skin.success("Project saved")+ skin.error("File not found")+ skin.warning("Unsaved changes")+ skin.info("Processing 24 clips...")+ skin.status("Track 1", "3 clips, 00:02:30")+ skin.table(headers, rows)+ skin.print_goodbye()+"""++import os+import sys+from pathlib import Path++# ── ANSI color codes (no external deps for core styling) ──────────────++_RESET = "\033[0m"+_BOLD = "\033[1m"+_DIM = "\033[2m"+_ITALIC = "\033[3m"+_UNDERLINE = "\033[4m"++# Brand colors+_CYAN = "\033[38;5;80m" # cli-anything brand cyan+_CYAN_BG = "\033[48;5;80m"+_WHITE = "\033[97m"+_GRAY = "\033[38;5;245m"+_DARK_GRAY = "\033[38;5;240m"+_LIGHT_GRAY = "\033[38;5;250m"++# Software accent colors — each software gets a unique accent+_ACCENT_COLORS = {+ "gimp": "\033[38;5;214m", # warm orange+ "blender": "\033[38;5;208m", # deep orange+ "inkscape": "\033[38;5;39m", # bright blue+ "audacity": "\033[38;5;33m", # navy blue+ "libreoffice": "\033[38;5;40m", # green+ "obs_studio": "\033[38;5;55m", # purple+ "kdenlive": "\033[38;5;69m", # slate blue+ "shotcut": "\033[38;5;35m", # teal green+}+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue++# Status colors+_GREEN = "\033[38;5;78m"+_YELLOW = "\033[38;5;220m"+_RED = "\033[38;5;196m"+_BLUE = "\033[38;5;75m"+_MAGENTA = "\033[38;5;176m"++_SKILL_SOURCE_REPO = os.environ.get("CLI_ANYTHING_SKILL_REPO", "HKUDS/CLI-Anything")++# ── Brand icon ────────────────────────────────────────────────────────++# The cli-anything icon: a small colored diamond/chevron mark+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"+_ICON_SMALL = f"{_CYAN}▸{_RESET}"++# ── Box drawing characters ────────────────────────────────────────────++_H_LINE = "─"+_V_LINE = "│"+_TL = "╭"+_TR = "╮"+_BL = "╰"+_BR = "╯"+_T_DOWN = "┬"+_T_UP = "┴"+_T_RIGHT = "├"+_T_LEFT = "┤"+_CROSS = "┼"+++def _strip_ansi(text: str) -> str:+ """Remove ANSI escape codes for length calculation."""+ import re+ return re.sub(r"\033\[[^m]*m", "", text)+++def _visible_len(text: str) -> int:+ """Get visible length of text (excluding ANSI codes)."""+ return len(_strip_ansi(text))+++def _display_home_path(path: str) -> str:+ """Display a path relative to the home directory when possible."""+ expanded = Path(path).expanduser().resolve()+ home = Path.home().resolve()+ try:+ relative = expanded.relative_to(home)+ return f"~/{relative.as_posix()}"+ except ValueError:+ return str(expanded)+++class ReplSkin:+ """Unified REPL skin for cli-anything CLIs.++ Provides consistent branding, prompts, and message formatting+ across all CLI harnesses built with the cli-anything methodology.+ """++ def __init__(self, software: str, version: str = "1.0.0",+ history_file: str | None = None, skill_path: str | None = None):+ """Initialize the REPL skin.++ Args:+ software: Software name (e.g., "gimp", "shotcut", "blender").+ version: CLI version string.+ history_file: Path for persistent command history.+ Defaults to ~/.cli-anything-<software>/history+ skill_path: Path to the SKILL.md file for agent discovery.+ Auto-detected from the repo-root skills/ tree when present,+ otherwise from the package's skills/ directory.+ Displayed in banner for AI agents to know where to read skill info.+ """+ self.software = software.lower().replace("-", "_")+ self.display_name = software.replace("_", " ").title()+ self.version = version+ software_aliases = {"iterm2_ctl": "iterm2"}+ self.skill_slug = software_aliases.get(self.software, self.software).replace("_", "-")+ self.skill_id = f"cli-anything-{self.skill_slug}"+ self.skill_install_cmd = (+ f"npx skills add {_SKILL_SOURCE_REPO} --skill {self.skill_id} -g -y"+ )+ global_skill_root = Path(+ os.environ.get("CLI_ANYTHING_GLOBAL_SKILLS_DIR", str(Path.home() / ".agents" / "skills"))+ ).expanduser()+ self.global_skill_path = str(global_skill_root / self.skill_id / "SKILL.md")++ # Prefer repo-root canonical skills/<skill-id>/SKILL.md when running+ # inside the CLI-Anything monorepo. Fall back to the packaged+ # cli_anything/<software>/skills/SKILL.md for installed harnesses.+ if skill_path is None:+ package_skill = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"+ repo_skill = None+ for parent in Path(__file__).resolve().parents:+ candidate = parent / "skills" / self.skill_id / "SKILL.md"+ if candidate.is_file():+ repo_skill = candidate+ break+ if repo_skill and repo_skill.is_file():+ skill_path = str(repo_skill)+ elif package_skill.is_file():+ skill_path = str(package_skill)+ self.skill_path = skill_path+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)++ # History file+ if history_file is None:+ hist_dir = Path.home() / f".cli-anything-{self.software}"+ hist_dir.mkdir(parents=True, exist_ok=True)+ self.history_file = str(hist_dir / "history")+ else:+ self.history_file = history_file++ # Detect terminal capabilities+ self._color = self._detect_color_support()++ def _detect_color_support(self) -> bool:+ """Check if terminal supports color."""+ if os.environ.get("NO_COLOR"):+ return False+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):+ return False+ if not hasattr(sys.stdout, "isatty"):+ return False+ return sys.stdout.isatty()++ def _c(self, code: str, text: str) -> str:+ """Apply color code if colors are supported."""+ if not self._color:+ return text+ return f"{code}{text}{_RESET}"++ # ── Banner ────────────────────────────────────────────────────────++ def print_banner(self):+ """Print the startup banner with branding."""+ import textwrap++ inner = 72++ def _box_line(content: str) -> str:+ """Wrap content in box drawing, padding to inner width."""+ pad = inner - _visible_len(content)+ vl = self._c(_DARK_GRAY, _V_LINE)+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"++ def _meta_lines(label: str, value: str) -> list[str]:+ """Wrap a metadata line for the banner box."""+ icon = self._c(_MAGENTA, "◇")+ label_text = self._c(_DARK_GRAY, label)+ prefix = f" {icon} {label_text} "+ available = max(12, inner - _visible_len(prefix))+ wrapped = textwrap.wrap(+ value,+ width=available,+ break_long_words=True,+ break_on_hyphens=False,+ ) or [""]+ lines = [f"{prefix}{self._c(_LIGHT_GRAY, wrapped[0])}"]+ continuation_prefix = " " * _visible_len(prefix)+ for chunk in wrapped[1:]:+ lines.append(f"{continuation_prefix}{self._c(_LIGHT_GRAY, chunk)}")+ return lines++ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")++ # Title: ◆ cli-anything · Shotcut+ icon = self._c(_CYAN + _BOLD, "◆")+ brand = self._c(_CYAN + _BOLD, "cli-anything")+ dot = self._c(_DARK_GRAY, "·")+ name = self._c(self.accent + _BOLD, self.display_name)+ title = f" {icon} {brand} {dot} {name}"++ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"+ empty = ""++ meta_lines: list[str] = []+ meta_lines.extend(_meta_lines("Install:", self.skill_install_cmd))+ meta_lines.extend(_meta_lines("Global skill:", _display_home_path(self.global_skill_path)))+ print(top)+ print(_box_line(title))+ print(_box_line(ver))+ for line in meta_lines:+ print(_box_line(line))+ print(_box_line(empty))+ print(_box_line(tip))+ print(bot)+ print()++ # ── Prompt ────────────────────────────────────────────────────────++ def prompt(self, project_name: str = "", modified: bool = False,+ context: str = "") -> str:+ """Build a styled prompt string for prompt_toolkit or input().++ Args:+ project_name: Current project name (empty if none open).+ modified: Whether the project has unsaved changes.+ context: Optional extra context to show in prompt.++ Returns:+ Formatted prompt string.+ """+ parts = []++ # Icon+ if self._color:+ parts.append(f"{_CYAN}◆{_RESET} ")+ else:+ parts.append("> ")++ # Software name+ parts.append(self._c(self.accent + _BOLD, self.software))++ # Project context+ if project_name or context:+ ctx = context or project_name+ mod = "*" if modified else ""+ parts.append(f" {self._c(_DARK_GRAY, '[')}")+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))+ parts.append(self._c(_DARK_GRAY, ']'))++ parts.append(self._c(_GRAY, " ❯ "))++ return "".join(parts)++ def prompt_tokens(self, project_name: str = "", modified: bool = False,+ context: str = ""):+ """Build prompt_toolkit formatted text tokens for the prompt.++ Use with prompt_toolkit's FormattedText for proper ANSI handling.++ Returns:+ list of (style, text) tuples for prompt_toolkit.+ """+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")+ tokens = []++ tokens.append(("class:icon", "◆ "))+ tokens.append(("class:software", self.software))++ if project_name or context:+ ctx = context or project_name+ mod = "*" if modified else ""+ tokens.append(("class:bracket", " ["))+ tokens.append(("class:context", f"{ctx}{mod}"))+ tokens.append(("class:bracket", "]"))++ tokens.append(("class:arrow", " ❯ "))++ return tokens++ def get_prompt_style(self):+ """Get a prompt_toolkit Style object matching the skin.++ Returns:+ prompt_toolkit.styles.Style+ """+ try:+ from prompt_toolkit.styles import Style+ except ImportError:+ return None++ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")++ return Style.from_dict({+ "icon": "#5fdfdf bold", # cyan brand color+ "software": f"{accent_hex} bold",+ "bracket": "#585858",+ "context": "#bcbcbc",+ "arrow": "#808080",+ # Completion menu+ "completion-menu.completion": "bg:#303030 #bcbcbc",+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",+ "completion-menu.meta.completion": "bg:#303030 #808080",+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",+ # Auto-suggest+ "auto-suggest": "#585858",+ # Bottom toolbar+ "bottom-toolbar": "bg:#1c1c1c #808080",+ "bottom-toolbar.text": "#808080",+ })++ # ── Messages ──────────────────────────────────────────────────────++ def success(self, message: str):+ """Print a success message with green checkmark."""+ icon = self._c(_GREEN + _BOLD, "✓")+ print(f" {icon} {self._c(_GREEN, message)}")++ def error(self, message: str):+ """Print an error message with red cross."""+ icon = self._c(_RED + _BOLD, "✗")+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)++ def warning(self, message: str):+ """Print a warning message with yellow triangle."""+ icon = self._c(_YELLOW + _BOLD, "⚠")+ print(f" {icon} {self._c(_YELLOW, message)}")++ def info(self, message: str):+ """Print an info message with blue dot."""+ icon = self._c(_BLUE, "●")+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")++ def hint(self, message: str):+ """Print a subtle hint message."""+ print(f" {self._c(_DARK_GRAY, message)}")++ def section(self, title: str):+ """Print a section header."""+ print()+ print(f" {self._c(self.accent + _BOLD, title)}")+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")++ # ── Status display ────────────────────────────────────────────────++ def status(self, label: str, value: str):+ """Print a key-value status line."""+ lbl = self._c(_GRAY, f" {label}:")+ val = self._c(_WHITE, f" {value}")+ print(f"{lbl}{val}")++ def status_block(self, items: dict[str, str], title: str = ""):+ """Print a block of status key-value pairs.++ Args:+ items: Dict of label -> value pairs.+ title: Optional title for the block.+ """+ if title:+ self.section(title)++ max_key = max(len(k) for k in items) if items else 0+ for label, value in items.items():+ lbl = self._c(_GRAY, f" {label:<{max_key}}")+ val = self._c(_WHITE, f" {value}")+ print(f"{lbl}{val}")++ def progress(self, current: int, total: int, label: str = ""):+ """Print a simple progress indicator.++ Args:+ current: Current step number.+ total: Total number of steps.+ label: Optional label for the progress.+ """+ pct = int(current / total * 100) if total > 0 else 0+ bar_width = 20+ filled = int(bar_width * current / total) if total > 0 else 0+ bar = "█" * filled + "░" * (bar_width - filled)+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"+ if label:+ text += f" {self._c(_LIGHT_GRAY, label)}"+ print(text)++ # ── Table display ─────────────────────────────────────────────────++ def table(self, headers: list[str], rows: list[list[str]],+ max_col_width: int = 40):+ """Print a formatted table with box-drawing characters.++ Args:+ headers: Column header strings.+ rows: List of rows, each a list of cell strings.+ max_col_width: Maximum column width before truncation.+ """+ if not headers:+ return++ # Calculate column widths+ col_widths = [min(len(h), max_col_width) for h in headers]+ for row in rows:+ for i, cell in enumerate(row):+ if i < len(col_widths):+ col_widths[i] = min(+ max(col_widths[i], len(str(cell))), max_col_width+ )++ def pad(text: str, width: int) -> str:+ t = str(text)[:width]+ return t + " " * (width - len(t))++ # Header+ header_cells = [+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))+ for i, h in enumerate(headers)+ ]+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")+ header_line = f" {sep.join(header_cells)}"+ print(header_line)++ # Separator+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]+ sep_line = self._c(_DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}")+ print(sep_line)++ # Rows+ for row in rows:+ cells = []+ for i, cell in enumerate(row):+ if i < len(col_widths):+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")+ print(f" {row_sep.join(cells)}")++ # ── Help display ──────────────────────────────────────────────────++ def help(self, commands: dict[str, str]):+ """Print a formatted help listing.++ Args:+ commands: Dict of command -> description pairs.+ """+ self.section("Commands")+ max_cmd = max(len(c) for c in commands) if commands else 0+ for cmd, desc in commands.items():+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")+ desc_styled = self._c(_GRAY, f" {desc}")+ print(f"{cmd_styled}{desc_styled}")+ print()++ # ── Goodbye ───────────────────────────────────────────────────────++ def print_goodbye(self):+ """Print a styled goodbye message."""+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")++ # ── Prompt toolkit session factory ────────────────────────────────++ def create_prompt_session(self):+ """Create a prompt_toolkit PromptSession with skin styling.++ Returns:+ A configured PromptSession, or None if prompt_toolkit unavailable.+ """+ try:+ from prompt_toolkit import PromptSession+ from prompt_toolkit.history import FileHistory+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory+ from prompt_toolkit.formatted_text import FormattedText++ style = self.get_prompt_style()++ session = PromptSession(+ history=FileHistory(self.history_file),+ auto_suggest=AutoSuggestFromHistory(),+ style=style,+ enable_history_search=True,+ )+ return session+ except ImportError:+ return None++ def get_input(self, pt_session, project_name: str = "",+ modified: bool = False, context: str = "") -> str:+ """Get input from user using prompt_toolkit or fallback.++ Args:+ pt_session: A prompt_toolkit PromptSession (or None).+ project_name: Current project name.+ modified: Whether project has unsaved changes.+ context: Optional context string.++ Returns:+ User input string (stripped).+ """+ if pt_session is not None:+ from prompt_toolkit.formatted_text import FormattedText+ tokens = self.prompt_tokens(project_name, modified, context)+ return pt_session.prompt(FormattedText(tokens)).strip()+ else:+ raw_prompt = self.prompt(project_name, modified, context)+ return input(raw_prompt).strip()++ # ── Toolbar builder ───────────────────────────────────────────────++ def bottom_toolbar(self, items: dict[str, str]):+ """Create a bottom toolbar callback for prompt_toolkit.++ Args:+ items: Dict of label -> value pairs to show in toolbar.++ Returns:+ A callable that returns FormattedText for the toolbar.+ """+ def toolbar():+ from prompt_toolkit.formatted_text import FormattedText+ parts = []+ for i, (k, v) in enumerate(items.items()):+ if i > 0:+ parts.append(("class:bottom-toolbar.text", " │ "))+ parts.append(("class:bottom-toolbar.text", f" {k}: "))+ parts.append(("class:bottom-toolbar", v))+ return FormattedText(parts)+ return toolbar+++# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────++_ANSI_256_TO_HEX = {+ "\033[38;5;33m": "#0087ff", # audacity navy blue+ "\033[38;5;35m": "#00af5f", # shotcut teal+ "\033[38;5;39m": "#00afff", # inkscape bright blue+ "\033[38;5;40m": "#00d700", # libreoffice green+ "\033[38;5;55m": "#5f00af", # obs purple+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue+ "\033[38;5;75m": "#5fafff", # default sky blue+ "\033[38;5;80m": "#5fd7d7", # brand cyan+ "\033[38;5;208m": "#ff8700", # blender deep orange+ "\033[38;5;214m": "#ffaf00", # gimp warm orange+}diff --git a/web-yu-pri/agent-harness/cli_anything/web_yu_pri/web_yu_pri_cli.py b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/web_yu_pri_cli.pynew file mode 100644index 000000000..64f6cd361--- /dev/null+++ b/web-yu-pri/agent-harness/cli_anything/web_yu_pri/web_yu_pri_cli.py@@ -0,0 +1,346 @@+#!/usr/bin/env python3+"""CLI harness for Japan Post Web Yu-pri."""++from __future__ import annotations++import json+import shlex+from contextlib import contextmanager+from typing import Any++import click++from cli_anything.web_yu_pri import __version__+from cli_anything.web_yu_pri.core.browser import (+ CONTENTS_URL,+ LOGIN_URL,+ build_dry_run,+ capture_snapshot,+ doctor as browser_doctor,+ fill_contents,+ inspect_url,+ open_login,+ selector_report,+)+from cli_anything.web_yu_pri.core.items import build_contents_plan, load_items++_json_output = False+_profile_dir: str | None = None+++def emit(data: Any, message: str | None = None) -> None:+ if _json_output:+ click.echo(json.dumps(data, ensure_ascii=False, indent=2, default=str))+ else:+ if message:+ click.echo(message)+ if isinstance(data, dict):+ _print_dict(data)+ elif isinstance(data, list):+ _print_list(data)+ elif data is not None:+ click.echo(str(data))+++def fail(message: str, error_type: str = "runtime_error") -> None:+ if _json_output:+ click.echo(json.dumps({"error": message, "type": error_type}, ensure_ascii=False))+ else:+ click.echo(f"Error: {message}", err=True)+ raise SystemExit(1)+++def _print_dict(data: dict[str, Any], indent: int = 0) -> None:+ prefix = " " * indent+ for key, value in data.items():+ if isinstance(value, dict):+ click.echo(f"{prefix}{key}:")+ _print_dict(value, indent + 1)+ elif isinstance(value, list):+ click.echo(f"{prefix}{key}:")+ _print_list(value, indent + 1)+ else:+ click.echo(f"{prefix}{key}: {value}")+++def _print_list(values: list[Any], indent: int = 0) -> None:+ prefix = " " * indent+ for index, value in enumerate(values):+ if isinstance(value, dict):+ click.echo(f"{prefix}[{index}]")+ _print_dict(value, indent + 1)+ else:+ click.echo(f"{prefix}- {value}")+++def _load_plan(+ items_file: str,+ default_country: str | None,+ total_value: int | None,+ value_mode: str,+) -> tuple[list[Any], dict[str, Any]]:+ items = load_items(items_file, default_country=default_country)+ plan = build_contents_plan(items, total_value=total_value, value_mode=value_mode)+ return items, plan++[email protected](invoke_without_command=True)[email protected]("--json", "json_output", is_flag=True, help="Output machine-readable JSON.")+ "--profile-dir",+ type=click.Path(file_okay=False, dir_okay=True, path_type=str),+ default=None,+ help="Persistent browser profile directory. Defaults to ~/.cli-anything-web-yu-pri/profile.",+)[email protected]_option(version=__version__)[email protected]_context+def cli(ctx: click.Context, json_output: bool, profile_dir: str | None) -> None:+ """Japan Post Web Yu-pri browser automation harness.++ Run with --json for agent-safe output. Commands that touch the real site use a+ persistent local browser profile and never store account passwords.+ """++ global _json_output, _profile_dir+ _json_output = json_output+ _profile_dir = profile_dir+ if ctx.invoked_subcommand is None:+ click.echo(ctx.get_help())++[email protected]("doctor")+def doctor_cmd() -> None:+ """Check local runtime and profile paths."""++ try:+ emit(browser_doctor(profile_dir=_profile_dir))+ except Exception as exc:+ fail(str(exc))++[email protected]("selectors")+def selectors_cmd() -> None:+ """Print the currently known Web Yu-pri selector map."""++ emit(selector_report())++[email protected]("plan")[email protected]("items_file", type=click.Path(exists=True, dir_okay=False, path_type=str))[email protected]("--country-default", default=None, help="Default ISO country code for rows without one.")[email protected]("--total-value", type=int, default=None, help="Override the declared total value in yen.")+ "--value-mode",+ type=click.Choice(["line", "unit"]),+ default="line",+ show_default=True,+ help="Treat item value as a line total or a unit value.",+)+def plan_cmd(items_file: str, country_default: str | None, total_value: int | None, value_mode: str) -> None:+ """Validate an items JSON/CSV/TSV file and print the fill plan."""++ try:+ _items, plan = _load_plan(items_file, country_default, total_value, value_mode)+ emit(plan)+ except Exception as exc:+ fail(str(exc), error_type=type(exc).__name__)++[email protected]("open-login")[email protected]("--url", default=LOGIN_URL, show_default=True, help="Login/start URL to open.")[email protected]("--headless", is_flag=True, help="Run browser headless.")[email protected]("--browser-channel", default=None, help="Playwright channel, for example msedge or chrome.")+ "--wait/--no-wait",+ default=True,+ show_default=True,+ help="Keep the browser open until Enter is pressed.",+)+def open_login_cmd(url: str, headless: bool, browser_channel: str | None, wait: bool) -> None:+ """Open the Web Yu-pri login/start page in the persistent profile."""++ try:+ if wait:+ with _interactive_session(url, headless=headless, browser_channel=browser_channel) as info:+ emit(info, "Opened Web Yu-pri login page.")+ if not _json_output:+ click.echo("Log in or inspect the page, then press Enter here to close the browser.")+ input()+ else:+ info = open_login(url=url, profile_dir=_profile_dir, headless=headless, browser_channel=browser_channel)+ emit(info, "Opened Web Yu-pri login page.")+ except KeyboardInterrupt:+ return+ except Exception as exc:+ fail(str(exc), error_type=type(exc).__name__)++[email protected]("status")[email protected]("--url", default=LOGIN_URL, show_default=True, help="URL to inspect.")[email protected]("--headless", is_flag=True, help="Run browser headless.")[email protected]("--browser-channel", default=None, help="Playwright channel, for example msedge or chrome.")+def status_cmd(url: str, headless: bool, browser_channel: str | None) -> None:+ """Open a URL and report title, current URL, and selector presence."""++ try:+ emit(inspect_url(url=url, profile_dir=_profile_dir, headless=headless, browser_channel=browser_channel))+ except Exception as exc:+ fail(str(exc), error_type=type(exc).__name__)++[email protected]("snapshot")[email protected]("--url", default=LOGIN_URL, show_default=True, help="URL to capture.")+ "-o",+ "--output",+ required=True,+ type=click.Path(dir_okay=False, path_type=str),+ help="PNG screenshot output path.",+)+ "--html-output",+ type=click.Path(dir_okay=False, path_type=str),+ default=None,+ help="Optional HTML dump output path.",+)[email protected]("--headless", is_flag=True, help="Run browser headless.")[email protected]("--browser-channel", default=None, help="Playwright channel, for example msedge or chrome.")+def snapshot_cmd(+ url: str,+ output: str,+ html_output: str | None,+ headless: bool,+ browser_channel: str | None,+) -> None:+ """Capture a screenshot, and optionally HTML, for the current form state."""++ try:+ result = capture_snapshot(+ url=url,+ output=output,+ html_output=html_output,+ profile_dir=_profile_dir,+ headless=headless,+ browser_channel=browser_channel,+ )+ emit(result, "Snapshot captured.")+ except Exception as exc:+ fail(str(exc), error_type=type(exc).__name__)+++def contents() -> None:+ """Commands for the shipment contents form."""++[email protected]("fill")[email protected]("items_file", type=click.Path(exists=True, dir_okay=False, path_type=str))[email protected]("--url", default=CONTENTS_URL, show_default=True, help="Contents form URL.")[email protected]("--country-default", default=None, help="Default ISO country code for rows without one.")[email protected]("--total-value", type=int, default=None, help="Override the declared total value in yen.")+ "--value-mode",+ type=click.Choice(["line", "unit"]),+ default="line",+ show_default=True,+ help="Treat item value as a line total or a unit value.",+)[email protected]("--package-type", default=None, help="Optional package type/select value.")[email protected]("--danger/--no-danger", default=None, help="Set the dangerous-goods flag when present.")[email protected]("--dry-run", is_flag=True, help="Validate and print the plan without opening a browser.")[email protected]("--headless", is_flag=True, help="Run browser headless.")[email protected]("--browser-channel", default=None, help="Playwright channel, for example msedge or chrome.")[email protected]("--delay-ms", type=int, default=500, show_default=True, help="Delay after adding each item.")+def contents_fill_cmd(+ items_file: str,+ url: str,+ country_default: str | None,+ total_value: int | None,+ value_mode: str,+ package_type: str | None,+ danger: bool | None,+ dry_run: bool,+ headless: bool,+ browser_channel: str | None,+ delay_ms: int,+) -> None:+ """Fill item lines on the Web Yu-pri contents page.++ This command stops after filling contents and the declared total. It does not+ click the final shipment confirmation/submit button.+ """++ try:+ items, _plan = _load_plan(items_file, country_default, total_value, value_mode)+ if dry_run:+ emit(+ build_dry_run(+ items,+ total_value=total_value,+ value_mode=value_mode,+ package_type=package_type,+ danger=danger,+ )+ )+ return+ result = fill_contents(+ items,+ total_value=total_value,+ value_mode=value_mode,+ url=url,+ profile_dir=_profile_dir,+ package_type=package_type,+ danger=danger,+ headless=headless,+ browser_channel=browser_channel,+ delay_ms=delay_ms,+ )+ emit(result, "Contents filled.")+ except Exception as exc:+ fail(str(exc), error_type=type(exc).__name__)++[email protected]("repl")+def repl_cmd() -> None:+ """Start a small command REPL."""++ click.echo("cli-anything-web-yu-pri REPL. Type help or exit.")+ while True:+ try:+ line = input("web-yu-pri> ").strip()+ except (EOFError, KeyboardInterrupt):+ click.echo()+ return+ if not line:+ continue+ if line in {"exit", "quit"}:+ return+ if line == "help":+ click.echo("Try: doctor, selectors, plan <items.json>, contents fill <items.json> --dry-run")+ continue+ try:+ cli.main(args=shlex.split(line), prog_name="cli-anything-web-yu-pri", standalone_mode=False)+ except SystemExit:+ pass+ except Exception as exc:+ click.echo(f"Error: {exc}", err=True)+++@contextmanager+def _interactive_session(url: str, headless: bool, browser_channel: str | None):+ from cli_anything.web_yu_pri.core.browser import browser_session, inspect_page++ with browser_session(profile_dir=_profile_dir, headless=headless, browser_channel=browser_channel) as (+ page,+ _context,+ ):+ page.goto(url, wait_until="domcontentloaded")+ yield inspect_page(page)+++def main() -> None:+ cli()+++if __name__ == "__main__":+ main()diff --git a/web-yu-pri/agent-harness/setup.py b/web-yu-pri/agent-harness/setup.pynew file mode 100644index 000000000..bcd25404e--- /dev/null+++ b/web-yu-pri/agent-harness/setup.py@@ -0,0 +1,65 @@+#!/usr/bin/env python3+from pathlib import Path+from setuptools import find_namespace_packages, setup++ROOT = Path(__file__).parent+README = ROOT / "README.md"+++def read_readme():+ try:+ return README.read_text(encoding="utf-8")+ except FileNotFoundError:+ return ""+++setup(+ name="cli-anything-web-yu-pri",+ version="0.1.0",+ author="CLI Anything Contributors",+ description="CLI harness for Japan Post Web Yu-pri label workflows",+ long_description=read_readme(),+ long_description_content_type="text/markdown",+ url="https://github.com/HKUDS/CLI-Anything",+ project_urls={+ "Homepage": "https://github.com/HKUDS/CLI-Anything",+ "Issues": "https://github.com/HKUDS/CLI-Anything/issues",+ },+ license="MIT",+ packages=find_namespace_packages(include=["cli_anything.*"]),+ python_requires=">=3.10",+ install_requires=[+ "click>=8.1,<9.0",+ "playwright>=1.45,<2.0",+ ],+ extras_require={+ "dev": [+ "pytest>=7",+ "build",+ "twine",+ ],+ },+ entry_points={+ "console_scripts": [+ "cli-anything-web-yu-pri=cli_anything.web_yu_pri.web_yu_pri_cli:main",+ ],+ },+ package_data={+ "cli_anything.web_yu_pri": ["skills/*.md"],+ },+ include_package_data=True,+ zip_safe=False,+ keywords="cli japan-post web-yu-pri shipping labels browser-automation ai-agent",+ classifiers=[+ "Development Status :: 3 - Alpha",+ "Intended Audience :: Developers",+ "Topic :: Internet :: WWW/HTTP :: Browsers",+ "Topic :: Office/Business",+ "Topic :: Software Development :: Testing",+ "License :: OSI Approved :: MIT License",+ "Programming Language :: Python :: 3 :: Only",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ ],+)