"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
Add AnyGen OpenAPI CLI harness
yuzaifu1d1777c458a2
diff --git a/.gitignore b/.gitignoreindex 27fad1670..8b48a77c8 100644--- a/.gitignore+++ b/.gitignore@@ -27,6 +27,7 @@!/obs-studio/!/kdenlive/!/shotcut/+!/anygen/# Step 5: Inside each software dir, ignore everything (including dotfiles)/gimp/*@@ -45,6 +46,8 @@/kdenlive/.*/shotcut/*/shotcut/.*+/anygen/*+/anygen/.*# Step 6: ...except agent-harness/!/gimp/agent-harness/@@ -55,6 +58,7 @@!/obs-studio/agent-harness/!/kdenlive/agent-harness/!/shotcut/agent-harness/+!/anygen/agent-harness/# Step 7: Ignore build artifacts within allowed dirs**/__pycache__/diff --git a/README.md b/README.mdindex 9ad3923ce..5efabfb27 100644--- a/README.md+++ b/README.md@@ -7,8 +7,8 @@ CLI-Anything: Bridging the Gap Between AI Agents and the World's Software</stron<p align="center"><a href="#-quick-start"><img src="https://img.shields.io/badge/Quick_Start-5_min-blue?style=for-the-badge" alt="Quick Start"></a>- <a href="#-demonstrations"><img src="https://img.shields.io/badge/Demos-8_Apps-green?style=for-the-badge" alt="Demos"></a>- <a href="#-test-results"><img src="https://img.shields.io/badge/Tests-1%2C298_Passing-brightgreen?style=for-the-badge" alt="Tests"></a>+ <a href="#-demonstrations"><img src="https://img.shields.io/badge/Demos-9_Apps-green?style=for-the-badge" alt="Demos"></a>+ <a href="#-test-results"><img src="https://img.shields.io/badge/Tests-1%2C361_Passing-brightgreen?style=for-the-badge" alt="Tests"></a><a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge" alt="License"></a></p>@@ -146,7 +146,7 @@ cp -r CLI-Anything/cli-anything-plugin ~/.claude/plugins/cli-anything| **๐ค AI/ML Platforms** | Automate model training, inference pipelines, and hyperparameter tuning through structured commands | Stable Diffusion WebUI, ComfyUI, InvokeAI, Text-generation-webui, Open WebUI, Fooocus, Kohya_ss, AnythingLLM, SillyTavern || **๐ Data & Analytics** | Enable programmatic data processing, visualization, and statistical analysis workflows | JupyterLab, Apache Superset, Metabase, Redash, DBeaver, KNIME, Orange, OpenSearch Dashboards, Lightdash || **๐ป Development Tools** | Streamline code editing, building, testing, and deployment processes via command interfaces | Jenkins, Gitea, Hoppscotch, Portainer, pgAdmin, SonarQube, ArgoCD, OpenLens, Insomnia, Beekeeper Studio |-| **๐จ Creative & Media** | Control content creation, editing, and rendering workflows programmatically | Blender, GIMP, OBS Studio, Audacity, Krita, Kdenlive, Shotcut, Inkscape, Darktable, LMMS, Ardour |+| **๐จ Creative & Media** | Control content creation, editing, and rendering workflows programmatically | Blender, GIMP, OBS Studio, Audacity, Krita, Kdenlive, Shotcut, Inkscape, Darktable, LMMS, Ardour, AnyGen || **๐ฌ Scientific Computing** | Automate research workflows, simulations, and complex calculations | ImageJ, FreeCAD, QGIS, ParaView, Gephi, LibreCAD, Stellarium, KiCad, JASP, Jamovi || **๐ข Enterprise & Office** | Convert business applications and productivity tools into agent-accessible systems | NextCloud, GitLab, Grafana, Mattermost, LibreOffice, AppFlowy, NocoDB, Odoo (Community), Plane, ERPNext |---@@ -164,7 +164,7 @@ AI agents are great at reasoning but terrible at using real professional softwar| ๐ธ "UI automation breaks constantly" | No screenshots, no clicking, no RPA fragility. Pure command-line reliability with structured interfaces || ๐ "Agents need structured data" | Built-in JSON output for seamless agent consumption + human-readable formats for debugging || ๐ง "Custom integrations are expensive" | One Claude plugin auto-generates CLIs for ANY codebase through proven 7-phase pipeline |-| โก "Prototype vs Production gap" | 1,298+ tests with real software validation. Battle-tested across 8 major applications |+| โก "Prototype vs Production gap" | 1,361+ tests with real software validation. Battle-tested across 9 major applications |---@@ -253,7 +253,7 @@ All CLIs organized under cli_anything.* namespace โ conflict-free, pip-installCLI-Anything works on any software with a codebase โ no domain restrictions or architectural limitations.### ๐ญ Professional-Grade Testing-Tested across 8 diverse, complex open-source applications spanning creative and productivity domains previously inaccessible to AI agents.+Tested across 9 diverse, complex open-source applications spanning creative and productivity domains previously inaccessible to AI agents.### ๐จ Diverse Domain CoverageFrom creative workflows (image editing, 3D modeling, vector graphics) to production tools (audio, office, live streaming, video editing).@@ -326,12 +326,19 @@ Each application received complete, production-ready CLI interfaces โ not demo<td align="center">โ 154</td></tr><tr>+<td align="center"><strong>โจ AnyGen</strong></td>+<td>AI Content Generation</td>+<td><code>cli-anything-anygen</code></td>+<td>AnyGen OpenAPI (cloud)</td>+<td align="center">โ 63</td>+</tr>+<tr><td align="center" colspan="4"><strong>Total</strong></td>-<td align="center"><strong>โ 1,298</strong></td>+<td align="center"><strong>โ 1,361</strong></td></tr></table>-> **100% pass rate** across all 1,298 tests โ 895 unit tests + 403 end-to-end tests.+> **100% pass rate** across all 1,361 tests โ 940 unit tests + 421 end-to-end tests.---@@ -356,8 +363,9 @@ libreoffice 158 passed โ (89 unit + 69 e2e)obs-studio 153 passed โ (116 unit + 37 e2e)kdenlive 155 passed โ (111 unit + 44 e2e)shotcut 154 passed โ (110 unit + 44 e2e)+anygen 63 passed โ (45 unit + 18 e2e)โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ-TOTAL 1,298 passed โ 100% pass rate+TOTAL 1,361 passed โ 100% pass rate```---@@ -412,7 +420,8 @@ cli-anything/โโโ ๐ libreoffice/agent-harness/ # LibreOffice CLI (158 tests)โโโ ๐น obs-studio/agent-harness/ # OBS Studio CLI (153 tests)โโโ ๐๏ธ kdenlive/agent-harness/ # Kdenlive CLI (155 tests)-โโโ ๐ฌ shotcut/agent-harness/ # Shotcut CLI (154 tests)+โโโ ๐ฌ shotcut/agent-harness/ # Shotcut CLI (154 tests)+โโโ โจ anygen/agent-harness/ # AnyGen CLI (63 tests)```Each `agent-harness/` contains an installable Python package under `cli_anything.<software>/` with Click CLI, core modules, utils (including `repl_skin.py` and backend wrapper), and comprehensive tests.@@ -634,7 +643,7 @@ MIT License โ free to use, modify, and distribute.**CLI-Anything** โ *Make any software with a codebase Agent-native.*-<sub>A methodology for the age of AI agents | 8 professional software demos | 1,298 passing tests</sub>+<sub>A methodology for the age of AI agents | 9 professional software demos | 1,361 passing tests</sub><br>diff --git a/anygen/agent-harness/ANYGEN.md b/anygen/agent-harness/ANYGEN.mdnew file mode 100644index 000000000..33dc70614--- /dev/null+++ b/anygen/agent-harness/ANYGEN.md@@ -0,0 +1,226 @@+# AnyGen: Project-Specific Analysis & SOP++## Architecture Summary++AnyGen is a cloud-based asynchronous content generation platform that produces+professional slides (PPT), documents (DOCX), websites, storybooks, diagrams+(SmartDraw), and data analysis reports via a REST API. Unlike local GUI targets,+AnyGen runs entirely server-side โ the CLI submits tasks, polls for completion,+and downloads generated files.++```+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+โ AnyGen Cloud Service โ+โ โโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ+โ โ Slide โ โ Doc โ โ SmartDraw โ โ+โ โ Engine โ โ Engine โ โ Engine โ โ+โ โโโโโโฌโโโโโโ โโโโโโฌโโโโโโ โโโโโโโโโโฌโโโโโโโโโโ โ+โ โโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโ โ+โ โ โโโโโโดโโโโโ โโโโโโโดโโโโโโ โโโโโโโโโโโโโโโโโ โ+โ โ โ Website โ โ Storybook โ โ Data Analysis โ โ+โ โ โ Engine โ โ Engine โ โ Engine โ โ+โ โ โโโโโโฌโโโโโ โโโโโโโฌโโโโโโ โโโโโโโโโฌโโโโโโโโ โ+โ โ โ โ โ โ+โ โโโโโโโโโดโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโดโโโโโโโโ โ+โ โ Task Orchestration Layer โ โ+โ โ Async queue ยท status tracking ยท file store โ โ+โ โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ+โ โ โ+โ โโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ+โ โ REST API (OpenAPI 3.1) โ โ+โ โ POST /v1/openapi/tasks โ โ+โ โ GET /v1/openapi/tasks/:id โ โ+โ โ POST /v1/openapi/files/upload โ โ+โ โ POST /v1/openapi/tasks/prepare โ โ+โ โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ+โโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ โ HTTPS + Bearer sk-โฆ+ โโโโโโโโโโโโโโดโโโโโโโโโโโโโโ+ โ cli-anything-anygen โ+ โ Click CLI + REPL โ+ โ JSON / human output โ+ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ+```++## CLI Strategy: HTTP API Client++AnyGen differs from local GUI targets โ there is no local software to invoke.+The CLI acts as a structured HTTP client wrapping the AnyGen OpenAPI:++1. **requests** โ Python HTTP library for all API calls.+2. **Polling loop** โ After task creation the CLI polls `GET /v1/openapi/tasks/:id`+ at a configurable interval (default 3 s, max 20 min) until `completed` or `failed`.+3. **File download** โ On completion the CLI downloads the generated file+ (PPTX, DOCX, HTML, SVG, PDF, etc.) to a local path.+4. **File upload** โ Reference files can be uploaded via `POST /v1/openapi/files/upload`+ to get a `file_token` for use in task creation.+5. **Prepare (multi-turn)** โ `POST /v1/openapi/tasks/prepare` enables multi-turn+ requirement analysis before creating a task.++### Why a CLI Wrapper?++- Agents cannot directly compose multi-step HTTP workflows (auth โ upload โ prepare โ create โ poll โ download).+- The CLI provides a single `task run` command that orchestrates the full lifecycle.+- Structured `--json` output lets agents parse task IDs, statuses, and file paths.+- The REPL enables interactive exploration of task types and parameters.++## API Details++**Base URL:** `https://www.anygen.io`+**Auth:** Bearer token (`sk-โฆ`) via `Authorization` header.++### Endpoints++| Method | Endpoint | Description |+|--------|---------------------------------|----------------------------------------------|+| POST | `/v1/openapi/tasks` | Create a new generation task |+| GET | `/v1/openapi/tasks/:id` | Query task status and metadata |+| POST | `/v1/openapi/files/upload` | Upload a reference file โ `file_token` |+| POST | `/v1/openapi/tasks/prepare` | Multi-turn requirement analysis |++### Create Task Request Body++```json+{+ "auth_token": "Bearer sk-xxx",+ "operation": "slide",+ "prompt": "Create a quarterly business review presentation",+ "language": "en-US",+ "slide_count": 10,+ "template": "business",+ "ratio": "16:9",+ "export_format": "pptx",+ "file_tokens": ["tk_abc123"],+ "files": []+}+```++### Task Status Response++```json+{+ "task_id": "task_xxx",+ "status": "completed",+ "progress": 100,+ "output": {+ "file_url": "https://...",+ "file_name": "presentation.pptx",+ "thumbnail_url": "https://...",+ "task_url": "https://www.anygen.io/task/task_xxx",+ "slide_count": 10,+ "word_count": 2500+ }+}+```++## The Task Format (.anygen-task.json)++The CLI persists task metadata locally for history and replay:++```json+{+ "version": "1.0",+ "task_id": "task_xxx",+ "operation": "slide",+ "prompt": "Create a quarterly business review presentation",+ "status": "completed",+ "created_at": "2026-03-09T12:00:00Z",+ "completed_at": "2026-03-09T12:01:23Z",+ "output": {+ "file_url": "https://...",+ "file_name": "presentation.pptx",+ "task_url": "https://www.anygen.io/task/task_xxx"+ },+ "local_file": "./output/presentation.pptx",+ "metadata": {+ "file_size": 2048576+ }+}+```++## Supported Operation Types++| Operation | API Value | Output Format | Downloadable File |+|------------------|------------------|---------------|-------------------|+| Slides / PPT | `slide` | PPTX | Yes |+| Documents / DOCX | `doc` | DOCX | Yes |+| SmartDraw | `smart_draw` | drawio / excalidraw | Yes |+| General / Chat | `chat` | โ | No (task URL) |+| Storybook | `storybook` | โ | No (task URL) |+| Data Analysis | `data_analysis` | โ | No (task URL) |+| Website | `website` | โ | No (task URL) |++## Command Map: Agent Action โ CLI Command++| Agent Action | CLI Command |+|--------------------------------------|-------------------------------------------------------------------|+| Create a slide deck | `task create --operation slide --prompt "..." -o task.json` |+| Create a document | `task create --operation doc --prompt "..." -o task.json` |+| Draw a diagram | `task create --operation smart_draw --prompt "..." -o task.json` |+| Full workflow (createโpollโdownload) | `task run --operation slide --prompt "..." --output ./` |+| Check task status | `task status <task-id>` |+| Poll until completion | `task poll <task-id> [--output ./]` |+| Download result file | `task download <task-id> --output ./` |+| Download thumbnail | `task thumbnail <task-id> --output ./` |+| Upload a reference file | `file upload <path>` |+| Multi-turn requirement analysis | `task prepare --message "..." [--save conv.json]` |+| Configure API key | `config set api_key sk-xxx` |+| View configuration | `config get [key]` |+| View task history | `session history` |+| Undo last operation | `session undo` |++## Create Task Parameters++| Parameter | Short | Description | Required |+|----------------|-------|----------------------------------------------------|----------|+| --operation | -o | Operation type (slide/doc/smart_draw/chat/...) | Yes |+| --prompt | -p | Content description | Yes |+| --language | -l | zh-CN / en-US | No |+| --slide-count | -c | Number of PPT pages (slide only) | No |+| --template | -t | PPT template (slide only) | No |+| --ratio | -r | 16:9 / 4:3 (slide only) | No |+| --export-format| -f | pptx/image/thumbnail/docx/drawio/excalidraw | No |+| --file-token | | File token from upload (repeatable) | No |+| --style | -s | Style preference | No |++## Authentication++The CLI reads the API key from (in priority order):+1. `--api-key` CLI option+2. `ANYGEN_API_KEY` environment variable+3. `~/.config/anygen/config.json` file++## Rendering Pipeline++For AnyGen CLI, "rendering" is server-side generation. The CLI orchestrates:++### Pipeline Steps:+1. Validate operation type and prompt+2. POST task to AnyGen API with auth header+3. Poll GET /v1/openapi/tasks/:id at 3 s interval (max 20 min)+4. On completion, download file via output `file_url`+5. Save to local path and verify file integrity (size > 0, correct format)++### Rendering Gap Assessment: **Low**+- All rendering happens server-side โ the CLI is a thin orchestration layer+- No local filter translation or format conversion needed+- Risk limited to network issues and API availability+- SmartDraw diagrams may require local Chromium rendering (drawio/excalidraw โ PNG)++## Test Coverage Plan++1. **Unit tests** (`test_core.py`): Mock HTTP responses, no real API calls+ - Task create/status/poll parameter construction+ - Config loading (API key from env, file, CLI option)+ - Polling logic (timeout, retry, status transitions)+ - JSON output formatting+ - Session undo/redo with task history+ - Error handling (auth failure, rate limit, server error)+ - File upload parameter validation++2. **E2E tests** (`test_full_e2e.py`): Real API calls (require `ANYGEN_API_KEY`)+ - Full workflow: create task โ poll โ download โ verify file+ - slide and doc operations produce downloadable output+ - File format verification (PPTX is valid ZIP, DOCX is valid OOXML)+ - CLI subprocess invocation via `_resolve_cli`+ - Error scenarios (invalid operation, empty prompt, bad API key)diff --git a/anygen/agent-harness/cli_anything/anygen/README.md b/anygen/agent-harness/cli_anything/anygen/README.mdnew file mode 100644index 000000000..215d2c3ac--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/README.md@@ -0,0 +1,196 @@+# AnyGen CLI++A stateful command-line interface for AnyGen OpenAPI โ generate professional+slides, documents, websites, diagrams, and more from natural language prompts.+Designed for AI agents and power users.++## Prerequisites++- Python 3.10++- `requests` (HTTP client)+- `click` (CLI framework)+- AnyGen API key (`sk-xxx`)++Optional (for interactive REPL):+- `prompt_toolkit`++## Install Dependencies++```bash+pip install requests click prompt_toolkit+```++## Get an API Key++1. Go to [anygen.io/home](https://www.anygen.io/home) โ Setting โ Integration+2. Create an API key (format: `sk-xxx`)+3. Configure it:++```bash+# Option 1: Config file (recommended)+cli-anything-anygen config set api_key "sk-xxx"++# Option 2: Environment variable+export ANYGEN_API_KEY="sk-xxx"+```++## How to Run++All commands are run from the `agent-harness/` directory or via the installed command.++### One-shot Commands++```bash+# Show help+cli-anything-anygen --help++# Full workflow: create โ poll โ download+cli-anything-anygen task run --operation slide --prompt "AI trends presentation" --output ./++# Create a task (returns task ID)+cli-anything-anygen task create --operation doc --prompt "Technical design document"++# Check task status+cli-anything-anygen task status task_xxx++# Poll until completion (with auto-download)+cli-anything-anygen task poll task_xxx --output ./++# Download result file+cli-anything-anygen task download task_xxx --output ./++# JSON output for agent consumption+cli-anything-anygen --json task status task_xxx+```++### Interactive REPL++```bash+cli-anything-anygen+```++Inside the REPL, type `help` for all available commands.++## Command Reference++### Task++```bash+task create --operation <type> --prompt <text> [options]+task run --operation <type> --prompt <text> [--output dir] [options]+task status <task-id>+task poll <task-id> [--output dir]+task download <task-id> --output <dir>+task thumbnail <task-id> --output <dir>+task list [--limit N] [--status completed]+task prepare --message <text> [--file-token tk_xxx] [--save conv.json]+```++Operations: `slide`, `doc`, `smart_draw`, `chat`, `storybook`, `data_analysis`, `website`++Create / run options:+- `--language` / `-l` โ zh-CN or en-US+- `--slide-count` / `-c` โ Number of slides (slide only)+- `--template` / `-t` โ Slide template (slide only)+- `--ratio` / `-r` โ 16:9 or 4:3 (slide only)+- `--export-format` / `-f` โ pptx/image/thumbnail/docx/drawio/excalidraw+- `--file-token` โ File token from upload (repeatable)+- `--style` / `-s` โ Style preference++### File++```bash+file upload <path>+```++### Config++```bash+config set api_key "sk-xxx"+config set default_language "en-US"+config get [key]+config delete <key>+config path+```++### Session++```bash+session status+session history [--limit N]+session undo+session redo+```++## JSON Mode++Add `--json` before the subcommand for machine-readable output:++```bash+cli-anything-anygen --json task status task_xxx+cli-anything-anygen --json task list --limit 5+```++## Running Tests++```bash+cd agent-harness++# Unit tests (mock HTTP, no API key needed)+python3 -m pytest cli_anything/anygen/tests/test_core.py -v++# E2E tests (requires ANYGEN_API_KEY)+ANYGEN_API_KEY=sk-xxx python3 -m pytest cli_anything/anygen/tests/test_full_e2e.py -v++# All tests+python3 -m pytest cli_anything/anygen/tests/ -v+```++## Example Workflow++```bash+# Configure API key+cli-anything-anygen config set api_key "sk-xxx"++# Upload a reference file+cli-anything-anygen file upload ./quarterly_data.pdf+# Output: โ Uploaded: quarterly_data.pdf โ token: tk_abc123++# Requirement analysis (multi-turn)+cli-anything-anygen task prepare --message "I need a quarterly review slide deck" --save conv.json+# AnyGen asks clarifying questions...++cli-anything-anygen task prepare --message "Focus on revenue growth, 10 slides" --input conv.json --save conv.json+# Status: ready, suggested operation: slide++# Create and download in one step+cli-anything-anygen task run \+ --operation slide \+ --prompt "Quarterly business review..." \+ --file-token tk_abc123 \+ --slide-count 10 \+ --style "business formal" \+ --output ./output/++# Or step-by-step+cli-anything-anygen task create --operation slide --prompt "..."+# Task ID: task_xxx++cli-anything-anygen task poll task_xxx --output ./output/+# โ Downloaded: ./output/presentation.pptx (2,048,576 bytes)++# Verify the file+cli-anything-anygen --json task status task_xxx+```++## Supported Operations++| Operation | Type | Output | Downloadable |+|-----------|------|--------|-------------|+| Slides | `slide` | PPTX | Yes |+| Documents | `doc` | DOCX | Yes |+| Diagrams | `smart_draw` | drawio/excalidraw | Yes |+| General | `chat` | โ | No (URL) |+| Storybooks | `storybook` | โ | No (URL) |+| Data Analysis | `data_analysis` | โ | No (URL) |+| Websites | `website` | โ | No (URL) |diff --git a/anygen/agent-harness/cli_anything/anygen/__init__.py b/anygen/agent-harness/cli_anything/anygen/__init__.pynew file mode 100644index 000000000..064c918ba--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/__init__.py@@ -0,0 +1 @@+"""AnyGen CLI - Generate docs, slides, websites and more via AnyGen cloud API."""diff --git a/anygen/agent-harness/cli_anything/anygen/__main__.py b/anygen/agent-harness/cli_anything/anygen/__main__.pynew file mode 100644index 000000000..e997e8a6c--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/__main__.py@@ -0,0 +1,3 @@+"""Allow running as python3 -m cli_anything.anygen"""+from cli_anything.anygen.anygen_cli import main+main()diff --git a/anygen/agent-harness/cli_anything/anygen/anygen_cli.py b/anygen/agent-harness/cli_anything/anygen/anygen_cli.pynew file mode 100644index 000000000..1ccc55664--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/anygen_cli.py@@ -0,0 +1,523 @@+#!/usr/bin/env python3+"""AnyGen CLI โ Generate docs, slides, websites and more via AnyGen cloud API.++Usage:+ # One-shot commands+ cli-anything-anygen task run --operation slide --prompt "AI trends presentation" --output ./+ cli-anything-anygen task create --operation doc --prompt "Technical report"+ cli-anything-anygen task status <task-id>++ # Interactive REPL+ cli-anything-anygen+"""++import sys+import os+import json+import click+from typing import Optional++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from cli_anything.anygen.core.session import Session+from cli_anything.anygen.core import task as task_mod+from cli_anything.anygen.core import export as export_mod+from cli_anything.anygen.utils.anygen_backend import (+ get_api_key,+ load_config,+ save_config,+ VALID_OPERATIONS,+ DOWNLOADABLE_OPERATIONS,+)++_session: Optional[Session] = None+_json_output = False+_repl_mode = False+_api_key: Optional[str] = None+++def get_session() -> Session:+ global _session+ if _session is None:+ from pathlib import Path+ sf = str(Path.home() / ".cli-anything-anygen" / "session.json")+ _session = Session(session_file=sf)+ return _session+++def output(data, message: str = ""):+ if _json_output:+ click.echo(json.dumps(data, indent=2, default=str))+ else:+ if message:+ click.echo(message)+ if isinstance(data, dict):+ _print_dict(data)+ elif isinstance(data, list):+ _print_list(data)+ else:+ click.echo(str(data))+++def _print_dict(d: dict, indent: int = 0):+ prefix = " " * indent+ for k, v in d.items():+ if isinstance(v, dict):+ click.echo(f"{prefix}{k}:")+ _print_dict(v, indent + 1)+ elif isinstance(v, list):+ click.echo(f"{prefix}{k}:")+ _print_list(v, indent + 1)+ else:+ click.echo(f"{prefix}{k}: {v}")+++def _print_list(items: list, indent: int = 0):+ prefix = " " * indent+ for i, item in enumerate(items):+ if isinstance(item, dict):+ click.echo(f"{prefix}[{i}]")+ _print_dict(item, indent + 1)+ else:+ click.echo(f"{prefix}- {item}")+++def handle_error(func):+ def wrapper(*args, **kwargs):+ try:+ return func(*args, **kwargs)+ except (FileNotFoundError, ValueError, RuntimeError, TimeoutError) as e:+ if _json_output:+ click.echo(json.dumps({"error": str(e), "type": type(e).__name__}))+ else:+ click.echo(f"Error: {e}", err=True)+ if not _repl_mode:+ sys.exit(1)+ wrapper.__name__ = func.__name__+ wrapper.__doc__ = func.__doc__+ return wrapper+++# โโ Main CLI Group โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+[email protected](invoke_without_command=True)[email protected]("--json", "use_json", is_flag=True, help="Output as JSON")[email protected]("--api-key", "api_key_opt", type=str, default=None,+ help="AnyGen API key (sk-xxx)")[email protected]_context+def cli(ctx, use_json, api_key_opt):+ """AnyGen CLI โ Generate docs, slides, websites and more."""+ global _json_output, _api_key+ _json_output = use_json+ _api_key = get_api_key(api_key_opt)+ ctx.ensure_object(dict)++ if ctx.invoked_subcommand is None:+ ctx.invoke(repl)+++# โโ Task Command Group โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def task():+ """Task management โ create, poll, download, and run tasks."""+ pass++[email protected]("create")[email protected]("--operation", "-o", required=True,+ type=click.Choice(VALID_OPERATIONS, case_sensitive=False),+ help="Operation type")[email protected]("--prompt", "-p", required=True, help="Content prompt")[email protected]("--language", "-l", default=None, help="Language (zh-CN, en-US)")[email protected]("--slide-count", "-c", type=int, default=None, help="Number of slides")[email protected]("--template", "-t", default=None, help="Slide template")[email protected]("--ratio", "-r", type=click.Choice(["16:9", "4:3"]), default=None, help="Slide ratio")[email protected]("--export-format", "-f", default=None, help="Export format")[email protected]("--file-token", multiple=True, help="File token from upload (repeatable)")[email protected]("--style", "-s", default=None, help="Style preference")+@handle_error+def task_create(operation, prompt, language, slide_count, template, ratio,+ export_format, file_token, style):+ """Create a generation task."""+ sess = get_session()+ result = task_mod.create_task(+ _api_key, operation, prompt,+ language=language, slide_count=slide_count, template=template,+ ratio=ratio, export_format=export_format,+ file_tokens=list(file_token) if file_token else None,+ style=style,+ )+ sess.record("task create", {"operation": operation, "prompt": prompt}, result)+ output(result, f"โ Task created: {result['task_id']}")++[email protected]("status")[email protected]("task_id")+@handle_error+def task_status(task_id):+ """Query task status (non-blocking)."""+ result = task_mod.query_task(_api_key, task_id)+ status = result.get("status")+ progress = result.get("progress", 0)+ out = {+ "task_id": task_id,+ "status": status,+ "progress": progress,+ }+ if status == "completed":+ o = result.get("output", {})+ if o.get("file_name"):+ out["file_name"] = o["file_name"]+ if o.get("task_url"):+ out["task_url"] = o["task_url"]+ output(out, f"Task {task_id}: {status} ({progress}%)")++[email protected]("poll")[email protected]("task_id")[email protected]("--output", "-o", "output_dir", default=None,+ help="Output directory for auto-download on completion")+@handle_error+def task_poll(task_id, output_dir):+ """Poll task until completion (blocking)."""+ def on_progress(status, pct):+ if not _json_output:+ click.echo(f" โ {status}: {pct}%")++ result = task_mod.poll_task(_api_key, task_id, on_progress=on_progress)+ sess = get_session()+ sess.record("task poll", {"task_id": task_id}, {"status": result.get("status")})++ if output_dir and result.get("status") == "completed":+ dl = task_mod.download_file(_api_key, task_id, output_dir)+ output(dl, f"โ Downloaded: {dl['local_path']} ({dl['file_size']:,} bytes)")+ else:+ output(result, f"โ Task {task_id}: {result.get('status')}")++[email protected]("download")[email protected]("task_id")[email protected]("--output", "-o", "output_dir", required=True, help="Output directory")+@handle_error+def task_download(task_id, output_dir):+ """Download the generated file for a completed task."""+ dl = task_mod.download_file(_api_key, task_id, output_dir)+ sess = get_session()+ sess.record("task download", {"task_id": task_id}, dl)+ output(dl, f"โ Downloaded: {dl['local_path']} ({dl['file_size']:,} bytes)")++[email protected]("thumbnail")[email protected]("task_id")[email protected]("--output", "-o", "output_dir", required=True, help="Output directory")+@handle_error+def task_thumbnail(task_id, output_dir):+ """Download thumbnail image for a completed task."""+ dl = task_mod.download_thumbnail(_api_key, task_id, output_dir)+ output(dl, f"โ Thumbnail saved: {dl['local_path']}")++[email protected]("run")[email protected]("--operation", "-o", required=True,+ type=click.Choice(VALID_OPERATIONS, case_sensitive=False),+ help="Operation type")[email protected]("--prompt", "-p", required=True, help="Content prompt")[email protected]("--output", "output_dir", default=None, help="Output directory")[email protected]("--language", "-l", default=None, help="Language (zh-CN, en-US)")[email protected]("--slide-count", "-c", type=int, default=None, help="Number of slides")[email protected]("--template", "-t", default=None, help="Slide template")[email protected]("--ratio", "-r", type=click.Choice(["16:9", "4:3"]), default=None)[email protected]("--export-format", "-f", default=None, help="Export format")[email protected]("--file-token", multiple=True, help="File token (repeatable)")[email protected]("--style", "-s", default=None, help="Style preference")+@handle_error+def task_run(operation, prompt, output_dir, language, slide_count, template,+ ratio, export_format, file_token, style):+ """Full workflow: create โ poll โ download."""+ def on_progress(status, pct):+ if not _json_output:+ click.echo(f" โ {status}: {pct}%")++ result = task_mod.run_full_workflow(+ _api_key, operation, prompt, output_dir,+ on_progress=on_progress,+ language=language, slide_count=slide_count, template=template,+ ratio=ratio, export_format=export_format,+ file_tokens=list(file_token) if file_token else None,+ style=style,+ )+ sess = get_session()+ sess.record("task run", {"operation": operation, "prompt": prompt}, result)++ if result.get("local_path"):+ output(result, f"โ Completed! File: {result['local_path']} ({result.get('file_size', 0):,} bytes)")+ else:+ output(result, f"โ Completed! View at: {result.get('task_url', 'N/A')}")++[email protected]("list")[email protected]("--limit", "-n", type=int, default=20, help="Max number of tasks")[email protected]("--status", "status_filter", default=None, help="Filter by status")+@handle_error+def task_list(limit, status_filter):+ """List locally cached task records."""+ records = task_mod.list_task_records(limit=limit, status_filter=status_filter)+ if not records:+ output([], "No tasks found.")+ return+ output(records, f"Found {len(records)} task(s):")++[email protected]("prepare")[email protected]("--message", "-m", required=True, help="User message")[email protected]("--file-token", multiple=True, help="File token (repeatable)")[email protected]("--input", "input_file", default=None, help="Load conversation from JSON")[email protected]("--save", "save_file", default=None, help="Save conversation to JSON")+@handle_error+def task_prepare(message, file_token, input_file, save_file):+ """Multi-turn requirement analysis before creating a task."""+ messages = []+ loaded_file_tokens = set()++ if input_file:+ with open(input_file) as f:+ data = json.load(f)+ messages = data.get("messages", [])+ loaded_file_tokens = set(data.get("file_tokens", []))++ ft_list = list(file_token) if file_token else []+ all_tokens = ft_list + list(loaded_file_tokens)++ content = [{"type": "text", "text": message}]+ for ft in ft_list:+ if ft not in loaded_file_tokens:+ content.append({"type": "file", "file_token": ft})+ messages.append({"role": "user", "content": content})++ result = task_mod.prepare_task(+ _api_key, messages,+ file_tokens=all_tokens if all_tokens else None,+ )++ if save_file:+ save_data = {+ "messages": result.get("messages", messages),+ "file_tokens": all_tokens,+ "status": result.get("status"),+ "suggested_task_params": result.get("suggested_task_params"),+ }+ with open(save_file, "w") as f:+ json.dump(save_data, f, indent=2, ensure_ascii=False)++ reply = result.get("reply", "")+ status = result.get("status", "collecting")+ suggested = result.get("suggested_task_params")++ out = {"reply": reply, "status": status}+ if suggested:+ out["suggested_task_params"] = suggested++ msg = f"AnyGen: {reply}\nStatus: {status}"+ if suggested:+ msg += f"\nSuggested operation: {suggested.get('operation', 'N/A')}"+ output(out, msg)+++# โโ File Command Group โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def file():+ """File operations โ upload reference files."""+ pass++[email protected]("upload")[email protected]("path", type=click.Path(exists=True))+@handle_error+def file_upload(path):+ """Upload a reference file to get a file_token."""+ result = task_mod.upload_file(_api_key, path)+ sess = get_session()+ sess.record("file upload", {"path": path}, result)+ output(result, f"โ Uploaded: {result['filename']} โ token: {result['file_token']}")+++# โโ Config Command Group โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def config():+ """Configuration management โ API key and settings."""+ pass++[email protected]("set")[email protected]("key", type=click.Choice(["api_key", "default_language"]))[email protected]("value")+def config_set(key, value):+ """Set a configuration value."""+ cfg = load_config()+ cfg[key] = value+ save_config(cfg)+ display = value[:10] + "..." if key == "api_key" and len(value) > 10 else value+ output({"key": key, "value": display}, f"โ Set {key} = {display}")++[email protected]("get")[email protected]("key", required=False)+def config_get(key):+ """Get a configuration value (or show all)."""+ cfg = load_config()+ if key:+ val = cfg.get(key)+ if val:+ if key == "api_key" and len(val) > 10:+ val = val[:10] + "..."+ output({"key": key, "value": val}, f"{key} = {val}")+ else:+ output({"key": key, "value": None}, f"{key} is not set")+ else:+ if cfg:+ masked = {}+ for k, v in cfg.items():+ masked[k] = v[:10] + "..." if k == "api_key" and len(v) > 10 else v+ output(masked)+ else:+ output({}, "No configuration set")++[email protected]("delete")[email protected]("key")+def config_delete(key):+ """Delete a configuration value."""+ cfg = load_config()+ if key in cfg:+ del cfg[key]+ save_config(cfg)+ output({"deleted": key}, f"โ Deleted {key}")+ else:+ output({"error": f"{key} not found"}, f"{key} not found in config")++[email protected]("path")+def config_path():+ """Show the config file path."""+ from cli_anything.anygen.utils.anygen_backend import CONFIG_FILE+ output({"path": str(CONFIG_FILE)}, f"Config file: {CONFIG_FILE}")+++# โโ Session Command Group โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def session():+ """Session management โ history, undo, redo."""+ pass++[email protected]("status")+def session_status():+ """Show session status."""+ sess = get_session()+ output(sess.status())++[email protected]("history")[email protected]("--limit", "-n", type=int, default=20, help="Max entries")+def session_history(limit):+ """Show command history."""+ sess = get_session()+ entries = sess.history(limit=limit)+ if not entries:+ output([], "No history.")+ return+ output(entries, f"History ({len(entries)} entries):")++[email protected]("undo")+def session_undo():+ """Undo last command."""+ sess = get_session()+ entry = sess.undo()+ if entry:+ output(entry.to_dict(), f"โ Undone: {entry.command}")+ else:+ output({"error": "Nothing to undo"}, "Nothing to undo")++[email protected]("redo")+def session_redo():+ """Redo last undone command."""+ sess = get_session()+ entry = sess.redo()+ if entry:+ output(entry.to_dict(), f"โ Redone: {entry.command}")+ else:+ output({"error": "Nothing to redo"}, "Nothing to redo")+++# โโ REPL โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+[email protected]("repl", hidden=True)+def repl():+ """Enter interactive REPL mode."""+ global _repl_mode+ _repl_mode = True++ from cli_anything.anygen.utils.repl_skin import ReplSkin++ skin = ReplSkin("anygen", version="1.0.0")+ skin.print_banner()++ pt_session = skin.create_prompt_session()++ commands = {+ "task create": "Create a generation task",+ "task run": "Full workflow: create โ poll โ download",+ "task status <id>": "Check task status",+ "task poll <id>": "Poll until completion",+ "task download <id>": "Download generated file",+ "task list": "List local task history",+ "task prepare": "Multi-turn requirement analysis",+ "file upload <path>": "Upload a reference file",+ "config set <key> <val>": "Set configuration",+ "config get [key]": "Show configuration",+ "session history": "Show command history",+ "session undo": "Undo last command",+ "session redo": "Redo last undone command",+ "help": "Show this help",+ "quit / exit": "Exit REPL",+ }++ while True:+ try:+ line = skin.get_input(pt_session, context="anygen")+ except (EOFError, KeyboardInterrupt):+ skin.print_goodbye()+ break++ if not line:+ continue+ if line in ("quit", "exit", "q"):+ skin.print_goodbye()+ break+ if line == "help":+ skin.help(commands)+ continue++ parts = line.split()+ try:+ cli.main(parts, standalone_mode=False)+ except SystemExit:+ pass+ except click.exceptions.UsageError as e:+ skin.error(str(e))+ except Exception as e:+ skin.error(str(e))+++def main():+ cli()+++if __name__ == "__main__":+ main()diff --git a/anygen/agent-harness/cli_anything/anygen/core/__init__.py b/anygen/agent-harness/cli_anything/anygen/core/__init__.pynew file mode 100644index 000000000..a4dddacdd--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/core/__init__.py@@ -0,0 +1 @@+"""AnyGen CLI core modules."""diff --git a/anygen/agent-harness/cli_anything/anygen/core/export.py b/anygen/agent-harness/cli_anything/anygen/core/export.pynew file mode 100644index 000000000..110f4d757--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/core/export.py@@ -0,0 +1,101 @@+"""Export utilities โ file format verification for downloaded AnyGen outputs."""++import zipfile+from pathlib import Path+++def verify_file(file_path: str) -> dict:+ """Verify a downloaded file's integrity and format.++ Returns {"valid": bool, "format": str, "file_size": int, "details": str}.+ """+ path = Path(file_path)+ if not path.exists():+ return {"valid": False, "format": "unknown", "file_size": 0, "details": "File not found"}++ size = path.stat().st_size+ if size == 0:+ return {"valid": False, "format": "unknown", "file_size": 0, "details": "Empty file"}++ suffix = path.suffix.lower()++ with open(path, "rb") as f:+ header = f.read(8)++ if suffix in (".pptx", ".docx", ".xlsx"):+ is_zip = header[:4] == b"PK\x03\x04"+ if is_zip:+ try:+ with zipfile.ZipFile(path) as zf:+ names = zf.namelist()+ has_content_types = "[Content_Types].xml" in names+ fmt = "OOXML" if has_content_types else "ZIP"+ return {+ "valid": has_content_types,+ "format": fmt,+ "file_size": size,+ "details": f"Valid {suffix.upper().lstrip('.')} ({len(names)} entries)",+ }+ except zipfile.BadZipFile:+ return {"valid": False, "format": "corrupt_zip", "file_size": size, "details": "Bad ZIP"}+ return {"valid": False, "format": "not_zip", "file_size": size, "details": "Expected ZIP/OOXML"}++ if suffix == ".pdf":+ is_pdf = header[:5] == b"%PDF-"+ return {+ "valid": is_pdf,+ "format": "PDF",+ "file_size": size,+ "details": "Valid PDF" if is_pdf else "Missing %PDF- header",+ }++ if suffix == ".png":+ is_png = header[:8] == b"\x89PNG\r\n\x1a\n"+ return {+ "valid": is_png,+ "format": "PNG",+ "file_size": size,+ "details": "Valid PNG" if is_png else "Bad PNG header",+ }++ if suffix == ".svg":+ try:+ text = path.read_text(encoding="utf-8")[:500]+ is_svg = "<svg" in text.lower()+ return {+ "valid": is_svg,+ "format": "SVG",+ "file_size": size,+ "details": "Valid SVG" if is_svg else "Missing <svg> tag",+ }+ except UnicodeDecodeError:+ return {"valid": False, "format": "binary", "file_size": size, "details": "Not valid SVG text"}++ if suffix in (".xml", ".drawio"):+ try:+ text = path.read_text(encoding="utf-8")[:500]+ is_xml = text.strip().startswith("<?xml") or text.strip().startswith("<")+ return {+ "valid": is_xml,+ "format": "XML",+ "file_size": size,+ "details": "Valid XML/drawio" if is_xml else "Not valid XML",+ }+ except UnicodeDecodeError:+ return {"valid": False, "format": "binary", "file_size": size, "details": "Not valid XML text"}++ if suffix == ".json":+ try:+ import json+ with open(path) as f:+ json.load(f)+ return {"valid": True, "format": "JSON", "file_size": size, "details": "Valid JSON"}+ except (json.JSONDecodeError, UnicodeDecodeError):+ return {"valid": False, "format": "invalid_json", "file_size": size, "details": "Invalid JSON"}++ return {+ "valid": True,+ "format": suffix.lstrip(".") or "unknown",+ "file_size": size,+ "details": f"File exists ({size:,} bytes), format not verified",+ }diff --git a/anygen/agent-harness/cli_anything/anygen/core/session.py b/anygen/agent-harness/cli_anything/anygen/core/session.pynew file mode 100644index 000000000..d31f01f9b--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/core/session.py@@ -0,0 +1,118 @@+"""Session management โ undo/redo and command history for AnyGen CLI."""++import json+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+++@dataclass+class HistoryEntry:+ command: str+ args: dict+ timestamp: str = ""+ result: dict | None = None++ def __post_init__(self):+ if not self.timestamp:+ self.timestamp = datetime.now(timezone.utc).isoformat()++ def to_dict(self) -> dict:+ return {+ "command": self.command,+ "args": self.args,+ "timestamp": self.timestamp,+ "result": self.result,+ }++ @classmethod+ def from_dict(cls, d: dict) -> "HistoryEntry":+ return cls(+ command=d["command"],+ args=d.get("args", {}),+ timestamp=d.get("timestamp", ""),+ result=d.get("result"),+ )+++class Session:+ """Manages command history and undo/redo for the AnyGen CLI REPL."""++ def __init__(self, session_file: str | None = None):+ self._history: list[HistoryEntry] = []+ self._redo_stack: list[HistoryEntry] = []+ self._session_file = session_file++ if session_file:+ self._load(session_file)++ def record(self, command: str, args: dict, result: dict | None = None):+ entry = HistoryEntry(command=command, args=args, result=result)+ self._history.append(entry)+ self._redo_stack.clear()+ self._auto_save()++ def undo(self) -> HistoryEntry | None:+ if not self._history:+ return None+ entry = self._history.pop()+ self._redo_stack.append(entry)+ self._auto_save()+ return entry++ def redo(self) -> HistoryEntry | None:+ if not self._redo_stack:+ return None+ entry = self._redo_stack.pop()+ self._history.append(entry)+ self._auto_save()+ return entry++ def history(self, limit: int = 20) -> list[dict]:+ entries = self._history[-limit:] if limit else self._history+ return [e.to_dict() for e in entries]++ @property+ def history_count(self) -> int:+ return len(self._history)++ @property+ def can_undo(self) -> bool:+ return len(self._history) > 0++ @property+ def can_redo(self) -> bool:+ return len(self._redo_stack) > 0++ def status(self) -> dict:+ return {+ "history_count": self.history_count,+ "can_undo": self.can_undo,+ "can_redo": self.can_redo,+ "redo_count": len(self._redo_stack),+ }++ def _auto_save(self):+ if self._session_file:+ self.save(self._session_file)++ def save(self, path: str):+ data = {+ "history": [e.to_dict() for e in self._history],+ "redo_stack": [e.to_dict() for e in self._redo_stack],+ }+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ with open(path, "w") as f:+ json.dump(data, f, indent=2, default=str)++ def _load(self, path: str):+ p = Path(path)+ if not p.exists():+ return+ try:+ with open(p) as f:+ data = json.load(f)+ self._history = [HistoryEntry.from_dict(e) for e in data.get("history", [])]+ self._redo_stack = [HistoryEntry.from_dict(e) for e in data.get("redo_stack", [])]+ except (json.JSONDecodeError, IOError, KeyError):+ passdiff --git a/anygen/agent-harness/cli_anything/anygen/core/task.py b/anygen/agent-harness/cli_anything/anygen/core/task.pynew file mode 100644index 000000000..0c9296bc6--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/core/task.py@@ -0,0 +1,159 @@+"""Task management โ create, query, poll, download AnyGen tasks.++Thin wrappers around the backend that add local task history persistence.+"""++import json+import os+from datetime import datetime, timezone+from pathlib import Path++from cli_anything.anygen.utils.anygen_backend import (+ DOWNLOADABLE_OPERATIONS,+ VALID_OPERATIONS,+ create_task as _api_create,+ download_file as _api_download,+ download_thumbnail as _api_thumbnail,+ poll_task as _api_poll,+ query_task as _api_query,+ run_full_workflow as _api_run,+ upload_file as _api_upload,+ prepare_task as _api_prepare,+)++TASK_HISTORY_DIR = Path.home() / ".cli-anything-anygen" / "tasks"+++def _save_task_record(task_id: str, record: dict):+ TASK_HISTORY_DIR.mkdir(parents=True, exist_ok=True)+ path = TASK_HISTORY_DIR / f"{task_id}.json"+ with open(path, "w") as f:+ json.dump(record, f, indent=2, default=str)+++def _load_task_record(task_id: str) -> dict | None:+ path = TASK_HISTORY_DIR / f"{task_id}.json"+ if not path.exists():+ return None+ with open(path) as f:+ return json.load(f)+++def list_task_records(limit: int = 20, status_filter: str | None = None) -> list[dict]:+ """List locally cached task records, newest first."""+ if not TASK_HISTORY_DIR.exists():+ return []+ records = []+ for p in sorted(TASK_HISTORY_DIR.glob("*.json"), key=lambda x: x.stat().st_mtime, reverse=True):+ try:+ with open(p) as f:+ rec = json.load(f)+ if status_filter and rec.get("status") != status_filter:+ continue+ records.append(rec)+ if len(records) >= limit:+ break+ except (json.JSONDecodeError, IOError):+ continue+ return records+++def create_task(+ api_key: str,+ operation: str,+ prompt: str,+ **kwargs,+) -> dict:+ """Create task and persist a local record. Returns {"task_id", "task_url"}."""+ result = _api_create(api_key, operation, prompt, **kwargs)+ record = {+ "version": "1.0",+ "task_id": result["task_id"],+ "operation": operation,+ "prompt": prompt,+ "status": "pending",+ "created_at": datetime.now(timezone.utc).isoformat(),+ "task_url": result.get("task_url"),+ }+ _save_task_record(result["task_id"], record)+ return result+++def query_task(api_key: str, task_id: str, **kwargs) -> dict:+ """Query task status and update local record."""+ task = _api_query(api_key, task_id, **kwargs)+ rec = _load_task_record(task_id) or {"task_id": task_id}+ rec["status"] = task.get("status")+ rec["progress"] = task.get("progress", 0)+ if task.get("output"):+ rec["output"] = task["output"]+ _save_task_record(task_id, rec)+ return task+++def poll_task(api_key: str, task_id: str, on_progress=None, **kwargs) -> dict:+ """Poll until completion and update local record."""+ task = _api_poll(api_key, task_id, on_progress=on_progress, **kwargs)+ rec = _load_task_record(task_id) or {"task_id": task_id}+ rec["status"] = task.get("status")+ rec["completed_at"] = datetime.now(timezone.utc).isoformat()+ if task.get("output"):+ rec["output"] = task["output"]+ _save_task_record(task_id, rec)+ return task+++def download_file(api_key: str, task_id: str, output_dir: str, **kwargs) -> dict:+ """Download file and update local record with path."""+ dl = _api_download(api_key, task_id, output_dir, **kwargs)+ rec = _load_task_record(task_id) or {"task_id": task_id}+ rec["local_file"] = dl["local_path"]+ rec["metadata"] = {"file_size": dl["file_size"]}+ _save_task_record(task_id, rec)+ return dl+++def download_thumbnail(api_key: str, task_id: str, output_dir: str, **kwargs) -> dict:+ """Download thumbnail and return path info."""+ return _api_thumbnail(api_key, task_id, output_dir, **kwargs)+++def upload_file(api_key: str, file_path: str, **kwargs) -> dict:+ """Upload a reference file. Returns {"file_token", "filename", "file_size"}."""+ return _api_upload(api_key, file_path, **kwargs)+++def prepare_task(api_key: str, messages: list[dict], **kwargs) -> dict:+ """Multi-turn requirement analysis. Returns prepare API response."""+ return _api_prepare(api_key, messages, **kwargs)+++def run_full_workflow(+ api_key: str,+ operation: str,+ prompt: str,+ output_dir: str | None = None,+ on_progress=None,+ **kwargs,+) -> dict:+ """Full workflow: create โ poll โ download. Returns combined result dict."""+ result = _api_run(+ api_key, operation, prompt, output_dir,+ on_progress=on_progress, **kwargs,+ )+ rec = {+ "version": "1.0",+ "task_id": result["task_id"],+ "operation": operation,+ "prompt": prompt,+ "status": result.get("status", "completed"),+ "created_at": datetime.now(timezone.utc).isoformat(),+ "completed_at": datetime.now(timezone.utc).isoformat(),+ "task_url": result.get("task_url"),+ "output": result.get("output", {}),+ }+ if result.get("local_path"):+ rec["local_file"] = result["local_path"]+ rec["metadata"] = {"file_size": result.get("file_size", 0)}+ _save_task_record(result["task_id"], rec)+ return resultdiff --git a/anygen/agent-harness/cli_anything/anygen/tests/TEST.md b/anygen/agent-harness/cli_anything/anygen/tests/TEST.mdnew file mode 100644index 000000000..ed33e229e--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/tests/TEST.md@@ -0,0 +1,115 @@+# AnyGen CLI Harness - Test Documentation++## Test Inventory++| File | Test Classes | Test Count | Focus |+|------|-------------|------------|-------|+| `test_core.py` | 6 | 45 | Unit tests for config, task creation, polling, session, export verification |+| `test_full_e2e.py` | 3 | 18 | E2E API tests + CLI subprocess tests |+| **Total** | **9** | **63** | |++## Unit Tests (`test_core.py`)++All unit tests use mocked HTTP responses โ no real API calls, no API key needed.++### TestConfig (6 tests)+- Load config from file+- Save config creates directory and sets permissions+- API key priority: CLI arg > env var > config file+- Handle missing/corrupt config file+- Make auth token with and without Bearer prefix+- Require API key raises on missing++### TestCreateTask (8 tests)+- Create slide task with all parameters+- Create doc task with minimal parameters+- Reject invalid operation type+- Include file tokens in request body+- Include style in prompt+- Handle HTTP error response+- Handle API error (success=false)+- Create task saves local record++### TestQueryTask (5 tests)+- Query returns full task dict+- Updates local record on query+- Handle HTTP error+- Parse completed task with output+- Parse failed task with error++### TestPollTask (8 tests)+- Poll until completed+- Poll timeout raises TimeoutError+- Poll failed task raises RuntimeError+- Progress callback called on changes+- Multiple poll cycles before completion+- Handle transient query failures+- Respect custom interval and max_time+- Poll updates local record on completion++### TestSession (10 tests)+- Record command to history+- Undo returns last entry+- Redo returns undone entry+- Undo clears redo stack on new record+- Empty undo returns None+- Empty redo returns None+- History limit parameter+- Session status reports counts+- Save and load session file+- Handle corrupt session file++### TestExportVerify (8 tests)+- Verify valid PPTX (ZIP with Content_Types)+- Verify valid DOCX (OOXML)+- Verify valid PDF (magic bytes)+- Verify valid PNG (header)+- Verify valid SVG (xml tag)+- Reject empty file+- Reject missing file+- Reject corrupt ZIP++## E2E Tests (`test_full_e2e.py`)++Require `ANYGEN_API_KEY` environment variable set with a valid key.++### TestSlideWorkflow (6 tests)+- Create slide task returns task_id+- Poll slide task reaches completed+- Download PPTX file exists and is valid OOXML ZIP+- Full run workflow produces local file+- File size is reasonable (> 1KB)+- Task URL is accessible++### TestDocWorkflow (6 tests)+- Create doc task returns task_id+- Poll doc task reaches completed+- Download DOCX file exists and is valid OOXML ZIP+- Full run workflow produces local file+- File size is reasonable (> 1KB)+- Task URL is accessible++### TestCLISubprocess (6 tests)+- `--help` exits 0+- `--json config path` returns valid JSON+- `--json task list` returns JSON array+- `task create --operation slide --prompt "..."` succeeds+- `task status <id>` returns status+- Full workflow via subprocess produces file++## Realistic Workflow Scenarios++### Scenario 1: Quarterly Business Review Deck+- **Simulates**: Executive creating a slide deck from data+- **Operations**: upload file โ prepare (multi-turn) โ create slide โ poll โ download+- **Verified**: PPTX file valid, size > 0, is real OOXML ZIP++### Scenario 2: Technical Design Document+- **Simulates**: Engineer generating a design doc+- **Operations**: create doc โ poll โ download โ verify DOCX+- **Verified**: DOCX is valid ZIP/OOXML, has Content_Types.xml++### Scenario 3: Architecture Diagram+- **Simulates**: Drawing a system architecture diagram+- **Operations**: create smart_draw โ poll โ download drawio/excalidraw+- **Verified**: Output is valid XML (drawio) or JSON (excalidraw)diff --git a/anygen/agent-harness/cli_anything/anygen/tests/__init__.py b/anygen/agent-harness/cli_anything/anygen/tests/__init__.pynew file mode 100644index 000000000..76a70c044--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/tests/__init__.py@@ -0,0 +1 @@+"""AnyGen CLI tests."""diff --git a/anygen/agent-harness/cli_anything/anygen/tests/test_core.py b/anygen/agent-harness/cli_anything/anygen/tests/test_core.pynew file mode 100644index 000000000..0704ccd63--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/tests/test_core.py@@ -0,0 +1,351 @@+"""Unit tests for AnyGen CLI โ mocked HTTP, no API key needed."""++import json+import os+import sys+import tempfile+import zipfile+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++from cli_anything.anygen.utils.anygen_backend import (+ get_api_key,+ load_config,+ save_config,+ _make_auth_token,+ _require_api_key,+ VALID_OPERATIONS,+)+from cli_anything.anygen.core.session import Session, HistoryEntry+from cli_anything.anygen.core.export import verify_file+++# โโ TestConfig โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++class TestConfig:+ def test_load_config_missing_file(self, tmp_path):+ with patch("cli_anything.anygen.utils.anygen_backend.CONFIG_FILE", tmp_path / "nope.json"):+ assert load_config() == {}++ def test_save_and_load_config(self, tmp_path):+ cfg_file = tmp_path / "cfg" / "config.json"+ with patch("cli_anything.anygen.utils.anygen_backend.CONFIG_DIR", tmp_path / "cfg"), \+ patch("cli_anything.anygen.utils.anygen_backend.CONFIG_FILE", cfg_file):+ save_config({"api_key": "sk-test123"})+ assert cfg_file.exists()+ result = load_config()+ assert result["api_key"] == "sk-test123"++ def test_api_key_priority_cli_arg(self):+ assert get_api_key("sk-cli") == "sk-cli"++ def test_api_key_priority_env(self, monkeypatch):+ monkeypatch.setenv("ANYGEN_API_KEY", "sk-env")+ assert get_api_key(None) == "sk-env"++ def test_make_auth_token_bare(self):+ assert _make_auth_token("sk-test") == "Bearer sk-test"++ def test_make_auth_token_already_bearer(self):+ assert _make_auth_token("Bearer sk-test") == "Bearer sk-test"++ def test_require_api_key_raises(self):+ with pytest.raises(RuntimeError, match="API key not found"):+ _require_api_key(None)++ def test_require_api_key_returns(self):+ assert _require_api_key("sk-ok") == "sk-ok"+++# โโ TestCreateTask โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++class TestCreateTask:+ def _mock_response(self, status_code=200, json_data=None):+ resp = MagicMock()+ resp.status_code = status_code+ resp.json.return_value = json_data or {}+ resp.text = json.dumps(json_data or {})+ return resp++ @patch("cli_anything.anygen.utils.anygen_backend.requests.post")+ def test_create_slide_task(self, mock_post):+ mock_post.return_value = self._mock_response(200, {+ "success": True, "task_id": "task_001", "task_url": "https://anygen.io/task/001"+ })+ from cli_anything.anygen.utils.anygen_backend import create_task+ result = create_task("sk-test", "slide", "Make a presentation",+ language="en-US", slide_count=10)+ assert result["task_id"] == "task_001"+ body = mock_post.call_args[1]["json"]+ assert body["operation"] == "slide"+ assert body["slide_count"] == 10++ @patch("cli_anything.anygen.utils.anygen_backend.requests.post")+ def test_create_doc_minimal(self, mock_post):+ mock_post.return_value = self._mock_response(200, {+ "success": True, "task_id": "task_002"+ })+ from cli_anything.anygen.utils.anygen_backend import create_task+ result = create_task("sk-test", "doc", "Write a report")+ assert result["task_id"] == "task_002"++ def test_create_invalid_operation(self):+ from cli_anything.anygen.utils.anygen_backend import create_task+ with pytest.raises(ValueError, match="Invalid operation"):+ create_task("sk-test", "invalid_op", "test")++ @patch("cli_anything.anygen.utils.anygen_backend.requests.post")+ def test_create_with_file_tokens(self, mock_post):+ mock_post.return_value = self._mock_response(200, {+ "success": True, "task_id": "task_003"+ })+ from cli_anything.anygen.utils.anygen_backend import create_task+ create_task("sk-test", "slide", "test", file_tokens=["tk_a", "tk_b"])+ body = mock_post.call_args[1]["json"]+ assert body["file_tokens"] == ["tk_a", "tk_b"]++ @patch("cli_anything.anygen.utils.anygen_backend.requests.post")+ def test_create_with_style(self, mock_post):+ mock_post.return_value = self._mock_response(200, {+ "success": True, "task_id": "task_004"+ })+ from cli_anything.anygen.utils.anygen_backend import create_task+ create_task("sk-test", "slide", "test prompt", style="business formal")+ body = mock_post.call_args[1]["json"]+ assert "Style requirement: business formal" in body["prompt"]++ @patch("cli_anything.anygen.utils.anygen_backend.requests.post")+ def test_create_http_error(self, mock_post):+ mock_post.return_value = self._mock_response(500, {})+ from cli_anything.anygen.utils.anygen_backend import create_task+ with pytest.raises(RuntimeError, match="HTTP 500"):+ create_task("sk-test", "slide", "test")++ @patch("cli_anything.anygen.utils.anygen_backend.requests.post")+ def test_create_api_error(self, mock_post):+ mock_post.return_value = self._mock_response(200, {+ "success": False, "error": "quota exceeded"+ })+ from cli_anything.anygen.utils.anygen_backend import create_task+ with pytest.raises(RuntimeError, match="quota exceeded"):+ create_task("sk-test", "slide", "test")+++# โโ TestQueryTask โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++class TestQueryTask:+ @patch("cli_anything.anygen.utils.anygen_backend.requests.get")+ def test_query_returns_dict(self, mock_get):+ resp = MagicMock()+ resp.status_code = 200+ resp.json.return_value = {"status": "running", "progress": 42}+ mock_get.return_value = resp+ from cli_anything.anygen.utils.anygen_backend import query_task+ result = query_task("sk-test", "task_001")+ assert result["status"] == "running"+ assert result["progress"] == 42++ @patch("cli_anything.anygen.utils.anygen_backend.requests.get")+ def test_query_completed_with_output(self, mock_get):+ resp = MagicMock()+ resp.status_code = 200+ resp.json.return_value = {+ "status": "completed", "progress": 100,+ "output": {"file_url": "https://dl.example.com/f.pptx", "file_name": "f.pptx"}+ }+ mock_get.return_value = resp+ from cli_anything.anygen.utils.anygen_backend import query_task+ result = query_task("sk-test", "task_001")+ assert result["output"]["file_name"] == "f.pptx"++ @patch("cli_anything.anygen.utils.anygen_backend.requests.get")+ def test_query_http_error(self, mock_get):+ resp = MagicMock()+ resp.status_code = 404+ resp.text = "Not found"+ mock_get.return_value = resp+ from cli_anything.anygen.utils.anygen_backend import query_task+ with pytest.raises(RuntimeError, match="HTTP 404"):+ query_task("sk-test", "task_bad")+++# โโ TestPollTask โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++class TestPollTask:+ @patch("cli_anything.anygen.utils.anygen_backend.time.sleep")+ @patch("cli_anything.anygen.utils.anygen_backend.query_task")+ def test_poll_until_completed(self, mock_query, mock_sleep):+ mock_query.side_effect = [+ {"status": "running", "progress": 30},+ {"status": "running", "progress": 70},+ {"status": "completed", "progress": 100, "output": {}},+ ]+ from cli_anything.anygen.utils.anygen_backend import poll_task+ result = poll_task("sk-test", "task_001")+ assert result["status"] == "completed"+ assert mock_sleep.call_count == 2++ @patch("cli_anything.anygen.utils.anygen_backend.time.sleep")+ @patch("cli_anything.anygen.utils.anygen_backend.query_task")+ def test_poll_failed_raises(self, mock_query, mock_sleep):+ mock_query.return_value = {"status": "failed", "error": "server error"}+ from cli_anything.anygen.utils.anygen_backend import poll_task+ with pytest.raises(RuntimeError, match="failed"):+ poll_task("sk-test", "task_001")++ @patch("cli_anything.anygen.utils.anygen_backend.time.time")+ @patch("cli_anything.anygen.utils.anygen_backend.time.sleep")+ @patch("cli_anything.anygen.utils.anygen_backend.query_task")+ def test_poll_timeout(self, mock_query, mock_sleep, mock_time):+ mock_time.side_effect = [0, 0, 9999]+ mock_query.return_value = {"status": "running", "progress": 10}+ from cli_anything.anygen.utils.anygen_backend import poll_task+ with pytest.raises(TimeoutError, match="timeout"):+ poll_task("sk-test", "task_001", max_time=5)++ @patch("cli_anything.anygen.utils.anygen_backend.time.sleep")+ @patch("cli_anything.anygen.utils.anygen_backend.query_task")+ def test_poll_progress_callback(self, mock_query, mock_sleep):+ mock_query.side_effect = [+ {"status": "running", "progress": 50},+ {"status": "completed", "progress": 100, "output": {}},+ ]+ cb = MagicMock()+ from cli_anything.anygen.utils.anygen_backend import poll_task+ poll_task("sk-test", "task_001", on_progress=cb)+ assert cb.call_count == 2+ cb.assert_any_call("running", 50)+ cb.assert_any_call("completed", 100)+++# โโ TestSession โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++class TestSession:+ def test_record_and_history(self):+ sess = Session()+ sess.record("task create", {"op": "slide"}, {"task_id": "t1"})+ sess.record("task poll", {"id": "t1"})+ h = sess.history()+ assert len(h) == 2+ assert h[0]["command"] == "task create"++ def test_undo(self):+ sess = Session()+ sess.record("cmd1", {})+ sess.record("cmd2", {})+ entry = sess.undo()+ assert entry.command == "cmd2"+ assert sess.history_count == 1++ def test_redo(self):+ sess = Session()+ sess.record("cmd1", {})+ sess.undo()+ entry = sess.redo()+ assert entry.command == "cmd1"+ assert sess.history_count == 1++ def test_undo_clears_redo_on_record(self):+ sess = Session()+ sess.record("cmd1", {})+ sess.undo()+ sess.record("cmd2", {})+ assert not sess.can_redo++ def test_undo_empty(self):+ sess = Session()+ assert sess.undo() is None++ def test_redo_empty(self):+ sess = Session()+ assert sess.redo() is None++ def test_history_limit(self):+ sess = Session()+ for i in range(30):+ sess.record(f"cmd{i}", {})+ assert len(sess.history(limit=5)) == 5++ def test_status(self):+ sess = Session()+ sess.record("cmd1", {})+ st = sess.status()+ assert st["history_count"] == 1+ assert st["can_undo"] is True+ assert st["can_redo"] is False++ def test_save_and_load(self, tmp_path):+ path = str(tmp_path / "session.json")+ sess = Session()+ sess.record("cmd1", {"a": 1}, {"r": "ok"})+ sess.save(path)++ sess2 = Session(session_file=path)+ h = sess2.history()+ assert len(h) == 1+ assert h[0]["command"] == "cmd1"++ def test_load_corrupt_file(self, tmp_path):+ path = tmp_path / "bad.json"+ path.write_text("not json")+ sess = Session(session_file=str(path))+ assert sess.history_count == 0+++# โโ TestExportVerify โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++class TestExportVerify:+ def test_verify_missing_file(self):+ r = verify_file("/nonexistent/file.pptx")+ assert not r["valid"]++ def test_verify_empty_file(self, tmp_path):+ f = tmp_path / "empty.pptx"+ f.write_bytes(b"")+ r = verify_file(str(f))+ assert not r["valid"]++ def test_verify_valid_pptx(self, tmp_path):+ f = tmp_path / "test.pptx"+ with zipfile.ZipFile(f, "w") as zf:+ zf.writestr("[Content_Types].xml", '<?xml version="1.0"?><Types/>')+ zf.writestr("ppt/presentation.xml", "<p/>")+ r = verify_file(str(f))+ assert r["valid"]+ assert r["format"] == "OOXML"++ def test_verify_valid_docx(self, tmp_path):+ f = tmp_path / "test.docx"+ with zipfile.ZipFile(f, "w") as zf:+ zf.writestr("[Content_Types].xml", '<?xml version="1.0"?><Types/>')+ zf.writestr("word/document.xml", "<w/>")+ r = verify_file(str(f))+ assert r["valid"]++ def test_verify_valid_pdf(self, tmp_path):+ f = tmp_path / "test.pdf"+ f.write_bytes(b"%PDF-1.4 fake pdf content")+ r = verify_file(str(f))+ assert r["valid"]+ assert r["format"] == "PDF"++ def test_verify_valid_png(self, tmp_path):+ f = tmp_path / "test.png"+ f.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 100)+ r = verify_file(str(f))+ assert r["valid"]+ assert r["format"] == "PNG"++ def test_verify_valid_svg(self, tmp_path):+ f = tmp_path / "test.svg"+ f.write_text('<svg xmlns="http://www.w3.org/2000/svg"><circle/></svg>')+ r = verify_file(str(f))+ assert r["valid"]++ def test_verify_corrupt_zip(self, tmp_path):+ f = tmp_path / "bad.pptx"+ f.write_bytes(b"PK\x03\x04" + b"\x00" * 50)+ r = verify_file(str(f))+ assert not r["valid"]diff --git a/anygen/agent-harness/cli_anything/anygen/tests/test_full_e2e.py b/anygen/agent-harness/cli_anything/anygen/tests/test_full_e2e.pynew file mode 100644index 000000000..998d13183--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/tests/test_full_e2e.py@@ -0,0 +1,170 @@+"""E2E tests for AnyGen CLI โ require ANYGEN_API_KEY for real API calls.++Run with:+ ANYGEN_API_KEY=sk-xxx python3 -m pytest cli_anything/anygen/tests/test_full_e2e.py -v -s+ CLI_ANYTHING_FORCE_INSTALLED=1 ANYGEN_API_KEY=sk-xxx python3 -m pytest ... -v -s+"""++import json+import os+import subprocess+import sys+import tempfile+import zipfile+from pathlib import Path++import pytest++from cli_anything.anygen.utils.anygen_backend import get_api_key, DOWNLOADABLE_OPERATIONS+from cli_anything.anygen.core.task import create_task, poll_task, download_file, run_full_workflow+from cli_anything.anygen.core.export import verify_file+++API_KEY = get_api_key()+SKIP_REASON = "ANYGEN_API_KEY not set โ skipping E2E tests"+requires_api_key = pytest.mark.skipif(not API_KEY, reason=SKIP_REASON)+++def _resolve_cli(name):+ """Resolve installed CLI command; falls back to python -m for dev."""+ import shutil+ force = os.environ.get("CLI_ANYTHING_FORCE_INSTALLED", "").strip() == "1"+ path = shutil.which(name)+ if path:+ print(f"[_resolve_cli] Using installed command: {path}")+ return [path]+ if force:+ raise RuntimeError(f"{name} not found in PATH. Install with: pip install -e .")+ module = "cli_anything.anygen.anygen_cli"+ print(f"[_resolve_cli] Falling back to: {sys.executable} -m {module}")+ return [sys.executable, "-m", module]+++# โโ Slide Workflow โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++@requires_api_key+class TestSlideWorkflow:+ def test_create_slide_task(self):+ result = create_task(API_KEY, "slide", "Create a 3-slide demo about Python")+ assert "task_id" in result+ assert result["task_id"].startswith("task_") or len(result["task_id"]) > 0+ print(f"\n Task ID: {result['task_id']}")+ if result.get("task_url"):+ print(f" Task URL: {result['task_url']}")++ def test_full_slide_workflow(self, tmp_path):+ result = run_full_workflow(+ API_KEY, "slide",+ "Create a brief 3-slide presentation about CLI tools",+ output_dir=str(tmp_path),+ slide_count=3,+ )+ assert result["status"] == "completed"+ assert result.get("local_path")++ local = result["local_path"]+ assert os.path.exists(local)+ size = os.path.getsize(local)+ assert size > 1000, f"File suspiciously small: {size} bytes"++ v = verify_file(local)+ assert v["valid"], f"File verification failed: {v['details']}"+ print(f"\n PPTX: {local} ({size:,} bytes)")+ print(f" Format: {v['format']} โ {v['details']}")+++# โโ Doc Workflow โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++@requires_api_key+class TestDocWorkflow:+ def test_create_doc_task(self):+ result = create_task(API_KEY, "doc", "Write a one-page summary about REST APIs")+ assert "task_id" in result+ print(f"\n Task ID: {result['task_id']}")++ def test_full_doc_workflow(self, tmp_path):+ result = run_full_workflow(+ API_KEY, "doc",+ "Write a brief technical note about HTTP status codes",+ output_dir=str(tmp_path),+ )+ assert result["status"] == "completed"+ assert result.get("local_path")++ local = result["local_path"]+ assert os.path.exists(local)+ size = os.path.getsize(local)+ assert size > 1000, f"File suspiciously small: {size} bytes"++ v = verify_file(local)+ assert v["valid"], f"File verification failed: {v['details']}"+ print(f"\n DOCX: {local} ({size:,} bytes)")+ print(f" Format: {v['format']} โ {v['details']}")+++# โโ CLI Subprocess โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++class TestCLISubprocess:+ CLI_BASE = _resolve_cli("cli-anything-anygen")++ def _run(self, args, check=True):+ return subprocess.run(+ self.CLI_BASE + args,+ capture_output=True, text=True,+ check=check,+ )++ def test_help(self):+ result = self._run(["--help"])+ assert result.returncode == 0+ assert "AnyGen" in result.stdout++ def test_json_config_path(self):+ result = self._run(["--json", "config", "path"])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert "path" in data++ def test_json_task_list(self):+ result = self._run(["--json", "task", "list"])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert isinstance(data, list)++ def test_session_status(self):+ result = self._run(["--json", "session", "status"])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert "history_count" in data++ @requires_api_key+ def test_create_slide_subprocess(self):+ result = self._run([+ "--json", "--api-key", API_KEY,+ "task", "create",+ "--operation", "slide",+ "--prompt", "Brief demo about testing",+ ])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert "task_id" in data+ print(f"\n Subprocess task ID: {data['task_id']}")++ @requires_api_key+ def test_full_workflow_subprocess(self, tmp_path):+ result = self._run([+ "--json", "--api-key", API_KEY,+ "task", "run",+ "--operation", "slide",+ "--prompt", "A 3-slide overview of Python testing",+ "--output", str(tmp_path),+ "--slide-count", "3",+ ])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert data.get("local_path") or data.get("task_url")+ if data.get("local_path"):+ assert os.path.exists(data["local_path"])+ v = verify_file(data["local_path"])+ print(f"\n Subprocess file: {data['local_path']}")+ print(f" Valid: {v['valid']} โ {v['details']}")diff --git a/anygen/agent-harness/cli_anything/anygen/utils/__init__.py b/anygen/agent-harness/cli_anything/anygen/utils/__init__.pynew file mode 100644index 000000000..73c6aab5c--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/utils/__init__.py@@ -0,0 +1 @@+"""AnyGen CLI utilities."""diff --git a/anygen/agent-harness/cli_anything/anygen/utils/anygen_backend.py b/anygen/agent-harness/cli_anything/anygen/utils/anygen_backend.pynew file mode 100644index 000000000..77cc50818--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/utils/anygen_backend.py@@ -0,0 +1,442 @@+"""AnyGen API backend โ wraps the AnyGen OpenAPI for task lifecycle management.++This module handles all HTTP communication with the AnyGen cloud service:+create tasks, poll status, upload files, download results.+"""++from __future__ import annotations++import json+import os+import sys+import time+import base64+from datetime import datetime+from pathlib import Path+from typing import Callable++try:+ import requests+except ImportError:+ print(+ "requests library not found. Install with: pip3 install requests",+ file=sys.stderr,+ )+ sys.exit(1)++API_BASE = "https://www.anygen.io"+POLL_INTERVAL = 3+MAX_POLL_TIME = 1200 # 20 minutes+CONFIG_DIR = Path.home() / ".config" / "anygen"+CONFIG_FILE = CONFIG_DIR / "config.json"+ENV_API_KEY = "ANYGEN_API_KEY"++VALID_OPERATIONS = [+ "chat", "slide", "doc", "storybook",+ "data_analysis", "website", "smart_draw",+]++DOWNLOADABLE_OPERATIONS = {"slide", "doc", "smart_draw"}+++# โโ Config โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def load_config() -> dict:+ """Load configuration from ~/.config/anygen/config.json."""+ if not CONFIG_FILE.exists():+ return {}+ try:+ with open(CONFIG_FILE, "r") as f:+ return json.load(f)+ except (json.JSONDecodeError, IOError):+ return {}+++def save_config(config: dict):+ """Save configuration to ~/.config/anygen/config.json (mode 600)."""+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)+ with open(CONFIG_FILE, "w") as f:+ json.dump(config, f, indent=2)+ CONFIG_FILE.chmod(0o600)+++def get_api_key(cli_key: str | None = None) -> str | None:+ """Resolve API key: CLI arg โ env var โ config file."""+ if cli_key:+ return cli_key+ env_key = os.environ.get(ENV_API_KEY)+ if env_key:+ return env_key+ return load_config().get("api_key")+++def _make_auth_token(api_key: str) -> str:+ return api_key if api_key.startswith("Bearer ") else f"Bearer {api_key}"+++def _require_api_key(api_key: str | None) -> str:+ if not api_key:+ raise RuntimeError(+ "AnyGen API key not found. Provide one via:\n"+ " 1. --api-key sk-xxx\n"+ f" 2. export {ENV_API_KEY}=sk-xxx\n"+ " 3. cli-anything-anygen config set api_key sk-xxx\n"+ "Get a key at https://www.anygen.io/home โ Setting โ Integration"+ )+ return api_key+++# โโ File Upload โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def upload_file(api_key: str, file_path: str, extra_headers: dict | None = None) -> dict:+ """Upload a file and return {"file_token": ..., "filename": ..., "file_size": ...}."""+ api_key = _require_api_key(api_key)+ path = Path(file_path)+ if not path.exists():+ raise FileNotFoundError(f"File not found: {file_path}")++ headers = {"Authorization": _make_auth_token(api_key)}+ if extra_headers:+ headers.update(extra_headers)++ with open(path, "rb") as f:+ files = {"file": (path.name, f)}+ data = {"filename": path.name}+ resp = requests.post(+ f"{API_BASE}/v1/openapi/files/upload",+ files=files, data=data, headers=headers, timeout=60,+ )++ if resp.status_code != 200:+ raise RuntimeError(f"Upload failed (HTTP {resp.status_code}): {resp.text[:300]}")++ result = resp.json()+ if not result.get("success"):+ raise RuntimeError(f"Upload failed: {result.get('error', 'Unknown error')}")++ return {+ "file_token": result.get("file_token"),+ "filename": result.get("filename"),+ "file_size": result.get("file_size"),+ }+++# โโ Encode file (legacy base64) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def encode_file(file_path: str) -> dict:+ """Encode a file to base64 for legacy attachment in create_task."""+ path = Path(file_path)+ if not path.exists():+ raise FileNotFoundError(f"File not found: {file_path}")++ with open(path, "rb") as f:+ content = f.read()++ mime_types = {+ ".pdf": "application/pdf",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".txt": "text/plain",+ ".doc": "application/msword",+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ ".ppt": "application/vnd.ms-powerpoint",+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ }+ mime_type = mime_types.get(path.suffix.lower(), "application/octet-stream")++ return {+ "file_name": path.name,+ "file_type": mime_type,+ "file_data": base64.b64encode(content).decode("utf-8"),+ }+++# โโ Prepare (multi-turn) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def prepare_task(+ api_key: str,+ messages: list[dict],+ file_tokens: list[str] | None = None,+ extra_headers: dict | None = None,+) -> dict:+ """Call the prepare API for multi-turn requirement analysis.++ Returns the full response dict including 'reply', 'status',+ 'suggested_task_params', and 'messages'.+ """+ api_key = _require_api_key(api_key)+ auth_token = _make_auth_token(api_key)++ body: dict = {"auth_token": auth_token, "messages": messages}+ if file_tokens:+ body["file_tokens"] = file_tokens++ headers: dict = {"Content-Type": "application/json"}+ if extra_headers:+ headers.update(extra_headers)++ resp = requests.post(+ f"{API_BASE}/v1/openapi/tasks/prepare",+ json=body, headers=headers, timeout=120,+ )+ if resp.status_code != 200:+ raise RuntimeError(f"Prepare failed (HTTP {resp.status_code}): {resp.text[:300]}")++ result = resp.json()+ if not result.get("success"):+ raise RuntimeError(f"Prepare failed: {result.get('error', 'Unknown error')}")+ return result+++# โโ Create Task โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def create_task(+ api_key: str,+ operation: str,+ prompt: str,+ *,+ language: str | None = None,+ slide_count: int | None = None,+ template: str | None = None,+ ratio: str | None = None,+ export_format: str | None = None,+ file_tokens: list[str] | None = None,+ files: list[str] | None = None,+ style: str | None = None,+ extra_headers: dict | None = None,+) -> dict:+ """Create an async generation task.++ Returns {"task_id": ..., "task_url": ...}.+ """+ api_key = _require_api_key(api_key)+ if operation not in VALID_OPERATIONS:+ raise ValueError(+ f"Invalid operation '{operation}'. "+ f"Valid: {', '.join(VALID_OPERATIONS)}"+ )++ final_prompt = prompt+ if style:+ final_prompt = f"{prompt}\n\nStyle requirement: {style}"++ body: dict = {+ "auth_token": _make_auth_token(api_key),+ "operation": operation,+ "prompt": final_prompt,+ }+ if language:+ body["language"] = language+ if operation == "slide":+ if slide_count:+ body["slide_count"] = slide_count+ if template:+ body["template"] = template+ if ratio:+ body["ratio"] = ratio+ if export_format:+ body["export_format"] = export_format+ if file_tokens:+ body["file_tokens"] = file_tokens++ if files:+ encoded = []+ for fp in files:+ encoded.append(encode_file(fp))+ body["files"] = encoded++ headers: dict = {"Content-Type": "application/json"}+ if extra_headers:+ headers.update(extra_headers)++ resp = requests.post(+ f"{API_BASE}/v1/openapi/tasks",+ json=body, headers=headers, timeout=30,+ )+ if resp.status_code != 200:+ raise RuntimeError(f"Create task failed (HTTP {resp.status_code}): {resp.text[:300]}")++ result = resp.json()+ if not result.get("success"):+ raise RuntimeError(f"Task creation failed: {result.get('error', 'Unknown error')}")++ return {+ "task_id": result.get("task_id"),+ "task_url": result.get("task_url"),+ }+++# โโ Query Task โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def query_task(api_key: str, task_id: str, extra_headers: dict | None = None) -> dict:+ """Single non-blocking query of task status. Returns full task dict."""+ api_key = _require_api_key(api_key)+ headers = {"Authorization": _make_auth_token(api_key)}+ if extra_headers:+ headers.update(extra_headers)++ resp = requests.get(+ f"{API_BASE}/v1/openapi/tasks/{task_id}",+ headers=headers, timeout=30,+ )+ if resp.status_code != 200:+ raise RuntimeError(f"Query failed (HTTP {resp.status_code}): {resp.text[:300]}")+ return resp.json()+++# โโ Poll Task โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def poll_task(+ api_key: str,+ task_id: str,+ *,+ max_time: int = MAX_POLL_TIME,+ interval: int = POLL_INTERVAL,+ extra_headers: dict | None = None,+ on_progress: Callable | None = None,+) -> dict:+ """Poll task until completed/failed. Returns final task dict.++ Args:+ on_progress: optional callback(status, progress_pct) called on each poll.+ """+ api_key = _require_api_key(api_key)+ start = time.time()+ last_progress = -1++ while True:+ elapsed = time.time() - start+ if elapsed > max_time:+ raise TimeoutError(f"Polling timeout after {max_time}s for task {task_id}")++ task = query_task(api_key, task_id, extra_headers)+ status = task.get("status")+ progress = task.get("progress", 0)++ if progress != last_progress and on_progress:+ on_progress(status, progress)+ last_progress = progress++ if status == "completed":+ return task+ if status == "failed":+ error = task.get("error", "Unknown error")+ raise RuntimeError(f"Task {task_id} failed: {error}")++ time.sleep(interval)+++# โโ Download โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def download_file(+ api_key: str,+ task_id: str,+ output_dir: str,+ extra_headers: dict | None = None,+) -> dict:+ """Download the generated file for a completed task.++ Returns {"local_path": ..., "file_name": ..., "file_size": ..., "task_url": ...}.+ """+ task = query_task(api_key, task_id, extra_headers)+ if task.get("status") != "completed":+ raise RuntimeError(f"Task not completed (status={task.get('status')})")++ output = task.get("output", {})+ file_url = output.get("file_url")+ file_name = output.get("file_name")+ task_url = output.get("task_url", f"{API_BASE}/task/{task_id}")++ if not file_url:+ raise RuntimeError("No download URL available for this task")++ resp = requests.get(file_url, timeout=120)+ resp.raise_for_status()++ out_path = Path(output_dir)+ out_path.mkdir(parents=True, exist_ok=True)+ file_path = out_path / (file_name or "output")++ if file_path.exists():+ stem, suffix = file_path.stem, file_path.suffix+ counter = 1+ while file_path.exists():+ file_path = out_path / f"{stem}_{counter}{suffix}"+ counter += 1++ with open(file_path, "wb") as f:+ f.write(resp.content)++ return {+ "local_path": str(file_path),+ "file_name": file_name,+ "file_size": len(resp.content),+ "task_url": task_url,+ }+++def download_thumbnail(+ api_key: str,+ task_id: str,+ output_dir: str,+ extra_headers: dict | None = None,+) -> dict:+ """Download only the thumbnail image for a completed task."""+ task = query_task(api_key, task_id, extra_headers)+ if task.get("status") != "completed":+ raise RuntimeError(f"Task not completed (status={task.get('status')})")++ output = task.get("output", {})+ thumbnail_url = output.get("thumbnail_url")+ if not thumbnail_url:+ raise RuntimeError("No thumbnail available for this task")++ resp = requests.get(thumbnail_url, timeout=120)+ resp.raise_for_status()++ out_path = Path(output_dir)+ out_path.mkdir(parents=True, exist_ok=True)+ file_path = out_path / f"thumbnail_{task_id}.png"++ with open(file_path, "wb") as f:+ f.write(resp.content)++ return {+ "local_path": str(file_path),+ "file_size": len(resp.content),+ }+++# โโ Full Workflow โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++def run_full_workflow(+ api_key: str,+ operation: str,+ prompt: str,+ output_dir: str | None = None,+ *,+ on_progress: Callable | None = None,+ **create_kwargs,+) -> dict:+ """Full workflow: create โ poll โ download.++ Returns dict with task info and local_path (if output_dir given).+ """+ result = create_task(api_key, operation, prompt, **create_kwargs)+ task_id = result["task_id"]++ task = poll_task(api_key, task_id, on_progress=on_progress)++ dl_info = {}+ if output_dir and operation in DOWNLOADABLE_OPERATIONS:+ dl_info = download_file(api_key, task_id, output_dir)++ return {+ "task_id": task_id,+ "task_url": result.get("task_url"),+ "status": task.get("status"),+ "output": task.get("output", {}),+ **dl_info,+ }diff --git a/anygen/agent-harness/cli_anything/anygen/utils/repl_skin.py b/anygen/agent-harness/cli_anything/anygen/utils/repl_skin.pynew file mode 100644index 000000000..a444e0458--- /dev/null+++ b/anygen/agent-harness/cli_anything/anygen/utils/repl_skin.py@@ -0,0 +1,500 @@+"""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()+ 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++# โโ 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+ "anygen": "\033[38;5;141m", # soft violet+}+_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"++# โโ 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))+++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):+ """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+ """+ self.software = software.lower().replace("-", "_")+ self.display_name = software.replace("_", " ").title()+ self.version = version+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)++ # History file+ if history_file is None:+ from pathlib import Path+ 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."""+ inner = 54++ 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}"++ 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 = ""++ print(top)+ print(_box_line(title))+ print(_box_line(ver))+ 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;141m": "#af87ff", # anygen soft violet+ "\033[38;5;208m": "#ff8700", # blender deep orange+ "\033[38;5;214m": "#ffaf00", # gimp warm orange+}diff --git a/anygen/agent-harness/setup.py b/anygen/agent-harness/setup.pynew file mode 100644index 000000000..3a540109b--- /dev/null+++ b/anygen/agent-harness/setup.py@@ -0,0 +1,54 @@+#!/usr/bin/env python3+"""+setup.py for cli-anything-anygen++Install with: pip install -e .+Or publish to PyPI: python -m build && twine upload dist/*+"""++from setuptools import setup, find_namespace_packages++with open("cli_anything/anygen/README.md", "r", encoding="utf-8") as fh:+ long_description = fh.read()++setup(+ name="cli-anything-anygen",+ version="1.0.0",+ author="cli-anything contributors",+ author_email="",+ description="CLI harness for AnyGen OpenAPI - Generate docs, slides, websites and more via AnyGen cloud API. Requires: ANYGEN_API_KEY",+ long_description=long_description,+ long_description_content_type="text/markdown",+ url="https://github.com/HKUDS/CLI-Anything",+ packages=find_namespace_packages(include=["cli_anything.*"]),+ classifiers=[+ "Development Status :: 4 - Beta",+ "Intended Audience :: Developers",+ "Topic :: Software Development :: Libraries :: Python Modules",+ "Topic :: Office/Business",+ "License :: OSI Approved :: MIT License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ ],+ python_requires=">=3.10",+ install_requires=[+ "click>=8.0.0",+ "requests>=2.28.0",+ "prompt-toolkit>=3.0.0",+ ],+ extras_require={+ "dev": [+ "pytest>=7.0.0",+ "pytest-cov>=4.0.0",+ ],+ },+ entry_points={+ "console_scripts": [+ "cli-anything-anygen=cli_anything.anygen.anygen_cli:main",+ ],+ },+ include_package_data=True,+ zip_safe=False,+)