← Files AstriaARCHIVED FILE

bin/astria

177 KB · Nov 30, 2026 · 07:47 UTC

↓ Download file

#!/usr/bin/env python3
"""astria — command-line client for the Astria API.

Credentials resolve in this order:
  1. Environment variables  (ASTRIA_API_KEY or ASTRIA_AUTH_TOKEN, ASTRIA_BASE_URL,
     WORKSPACE_ID, GEMINI_TUNE_ID, SEEDREAM_TUNE_ID, GPT_IMAGE_2_TUNE_ID)
  2. ~/.astria/config.json  (written by `astria login`)

Profiles work like the AWS CLI: `ASTRIA_PROFILE=localhost` (or
`astria --profile localhost ...`) reads ~/.astria/config.localhost.json — a
separate API key, base URL and workspace. The Astria web agent injects the
environment variables instead, so it never needs a config file.

Only depends on Python 3 stdlib + `curl` (used for the actual HTTP).
"""
import argparse
import ast
import base64
import concurrent.futures
import contextvars
import hashlib
import json
import mimetypes
import os
import platform
import re
import shutil
import sqlite3
import subprocess
import sys
import threading
import time
import uuid
import webbrowser
from pathlib import Path
from urllib.parse import quote, urlencode, urlparse

VERSION = "1.30.0"


def _platform_token():
    system = platform.system() or sys.platform
    machine = platform.machine()
    release = platform.release()
    return "; ".join(part for part in [system, release, machine] if part)


def _client_token():
    """Identify the host environment for the User-Agent comment — an explicit
    ASTRIA_CLIENT override, else the generic AI_AGENT marker, else Claude Code."""
    val = (os.environ.get("ASTRIA_CLIENT")
           or os.environ.get("AI_AGENT")
           or ("claude-code" if os.environ.get("CLAUDECODE") else None))
    if not val:
        return None
    return "".join(c for c in val if c.isalnum() or c in " ._/-")[:80]


def _user_agent():
    comment = "; ".join(part for part in [
        _platform_token(),
        f"Python/{platform.python_version()}",
        _client_token(),
    ] if part)
    return f"astria-cli/{VERSION} ({comment})"


USER_AGENT = _user_agent()
DEFAULT_BASE_URL = "https://api.astria.ai"
UPGRADE_URL = "https://raw.githubusercontent.com/astriaai/cli/main/astria"

CONFIG_DIR = Path(os.environ.get("ASTRIA_CONFIG_DIR") or (Path.home() / ".astria"))
# CONFIG_PATH / MODELS_CACHE are profile-specific — finalised by apply_profile().
ACTIVE_PROFILE = "default"
CONFIG_PATH = CONFIG_DIR / "config.json"
MODELS_CACHE = CONFIG_DIR / "models.json"

# Offline fallback for the platform model tunes. The live ids come from the
# /cli/models endpoint (cached in MODELS_CACHE, refreshed daily) — these values
# are only used when that endpoint has never been reachable.
MODEL_TUNES = {
    "gemini": "3618064",
    "seedream": "3691308",
    "gpt-image-2": "4665564",
}
MODEL_ENV = {
    "gemini": "GEMINI_TUNE_ID",
    "seedream": "SEEDREAM_TUNE_ID",
    "gpt-image-2": "GPT_IMAGE_2_TUNE_ID",
}
MODELS_TTL_DEFAULT = 86400

# Prompt-list parameter metadata is shared by CLI flags, wire mappings and MCP.
# Rails specs check this exported contract against the actual filter handlers.
PROMPT_FILTERS = {
    "text": {"mode": "truthy", "help": "filter by prompt text substring"},
    "text_ne": {"mode": "array", "help": "exclude a text substring (repeatable)"},
    "skill_name": {"mode": "truthy", "help": "filter by originating database skill name (exact slug, including unpublished skills)"},
    "t": {"mode": "truthy", "help": "filter by prompt theme"},
    "pack_id": {"mode": "truthy", "help": "template prompts owned by a pack"},
    "base_pack_id": {"mode": "truthy", "help": "prompts generated from a pack"},
    "tune_id": {"mode": "truthy", "help": "filter by checkpoint or reference tune"},
    "tune_id_ne": {"mode": "truthy", "help": "exclude a checkpoint or reference tune"},
    "name": {"mode": "truthy", "help": "filter by tune subject class"},
    "branch": {"mode": "truthy", "help": "filter by tune branch"},
    "controlnet": {"mode": "truthy", "help": "filter by ControlNet type; other values select any ControlNet"},
    "user_id": {"mode": "truthy", "help": "filter by creator within the authorized workspace scope"},
    "user_id_ne": {"mode": "truthy", "help": "exclude a creator within the authorized workspace scope"},
    "payer_id": {"mode": "truthy", "help": "filter by payer within the authorized workspace scope"},
    "affiliate_id": {"mode": "truthy", "help": "filter by affiliate within the authorized workspace scope"},
    "orig_prompt_id": {"mode": "truthy", "help": "prompts cloned from this prompt id"},
    "order_id": {"mode": "truthy", "help": "prompts generated for one order"},
    "review": {"mode": "truthy", "choices": ["pending", "ready", "comments", "synced"],
               "help": "filter by image review status; comments includes resolved comments"},
    "liked": {"mode": "flag", "help": "only prompts that have likes"},
    "today": {"mode": "flag", "help": "only prompts created today"},
    "archived": {"mode": "flag", "help": "only archived prompts; omitted selects unarchived prompts"},
    "is_multiperson": {"mode": "boolean", "help": "filter by multiperson status"},
    "is_video": {"mode": "boolean", "help": "filter by video status"},
    "media_type": {"mode": "truthy", "choices": ["image", "video", "music"],
                   "help": "filter by media type; image excludes music; takes precedence over is_video"},
    "creation_source": {"mode": "truthy", "choices": ["web", "mcp", "cli", "photoshop", "api"],
                        "help": "filter by creation source"},
    "is_api": {"mode": "boolean", "help": "legacy filter: web versus all API-authenticated sources"},
    "is_input_video": {"mode": "boolean", "help": "filter by input video presence"},
    "has_input_image": {"mode": "boolean", "help": "filter by input image presence"},
    "user_error": {"mode": "boolean", "help": "filter by user-visible error presence"},
    "inpaint_faces": {"mode": "boolean", "help": "filter by face inpainting status"},
    "limit": {"mode": "truthy", "help": "maximum number of prompts, capped at 120"},
    "offset": {"mode": "truthy", "help": "pagination offset, capped at 10000; use before_id for deeper pages"},
    "before_id": {"mode": "truthy", "help": "keyset cursor: return prompts older than this id"},
}


# Shared request contract. Rails consumes the JSON export of these definitions;
# CLI-only uploads, caching and waiting remain in the terminal handlers.
API_OPERATIONS = {'list_models': {'method': 'GET',
                 'path': '/cli/models',
                 'fields': [],
                 'target': 'query',
                 'result': {'object': {'default': ['default', 'gemini'],
                                       'model_selection_guidance': ['model_selection_guidance', None],
                                       'default_video_model': ['default_video_model', None],
                                       'default_video_model_family': ['default_video_model_family', None],
                                       'models': ['models', {}],
                                       'video_models': ['video_models', {}],
                                       'video_model_families': ['video_model_families', {}],
                                       'default_music_model': ['default_music_model', None],
                                       'music_models': ['music_models', {}]},
                            'sections': {'argument': 'type',
                                         'keys': {'image': ['default', 'model_selection_guidance', 'models'],
                                                  'video': ['default_video_model', 'default_video_model_family',
                                                            'video_models', 'video_model_families'],
                                                  'music': ['default_music_model', 'music_models']}},
                            'constants': {'note': 'this is the curated set of popular models only — any '
                                                  '--model also accepts a raw tune id directly. Browse every '
                                                  'model and its tune id at astria.ai/gallery/tunes (or run '
                                                  '`astria tunes list --gallery`).'},
                            'choices': {'source': ['builtin', 'built-in (offline)', 'server']}},
                 'no_workspace': True,
                 'auth': False},
 'list_workspaces': {'method': 'GET',
                     'path': '/workspaces.json',
                     'fields': [],
                     'target': 'query',
                     'result': {'pick': ['id', 'title', 'slug', 'url', 'favicon_url', 'logo_url']},
                     'no_workspace': True},
 'list_references': {'method': 'GET',
                     'path': '/tunes',
                     'fields': [['title', 'title', 'truthy'],
                                ['name[]', 'name', 'array'],
                                ['limit', 'limit', 'truthy'],
                                ['offset', 'offset', 'truthy'],
                                ['model_type', 'model_type', 'truthy'],
                                ['branch', 'branch', 'truthy'],
                                ['creation_source', 'creation_source', 'truthy'],
                                ['archived', 'archived', 'truthy']],
                     'target': 'query',
                     'result': {'pick': ['id', 'title', 'name', 'model_type', 'creation_source', 'creation_client', 'orig_images']},
                     'path_choice': ['gallery', '/gallery/tunes']},
 'get_reference': {'method': 'GET', 'path': '/tunes/{id}', 'fields': [], 'target': 'query', 'result': {}},
 'create_reference': {'method': 'POST',
                      'path': '/tunes',
                      'fields': [['tune[title]', 'title', 'value'],
                                 ['tune[name]', 'name', 'value'],
                                 ['tune[model_type]', 'model_type', 'value'],
                                 ['tune[base_tune_id]', 'model_id', 'value'],
                                 ['tune[characteristics]', 'characteristics', 'json_string'],
                                 ['tune[image_urls][]', 'image_url', 'array'],
                                 ['tune[images][]', 'image', 'array'],
                                 ['tune[image_captions][]', 'image_caption', 'array']],
                      'target': 'form',
                      'result': {},
                      'model': {'argument': 'model', 'output': 'model_id'},
                      'requires_any': ['image_url', 'image'],
                      'per_image': {'argument': 'image_caption', 'images': ['image_url', 'image']},
                      'characteristics': {'short_description': 'description', 'text': 'text'}},
 'generate_images': {'method': 'POST',
                     'path': '/tunes/{model_id}/prompts',
                     'fields': [['prompt[text]', 'text', 'value'],
                                ['prompt[num_images]', 'num_images', 'value'],
                                ['prompt[seed]', 'seed', 'truthy'],
                                ['prompt[film_grain]', 'film_grain', 'boolean'],
                                ['prompt[inpaint_faces]', 'inpaint_faces', 'boolean'],
                                ['prompt[inpaint_preset]', 'inpaint_preset', 'value'],
                                ['prompt[background_color]', 'background_color', 'value'],
                                ['prompt[create_crops]', 'create_crops', 'value'],
                                ['prompt[lynx]', 'lynx', 'boolean'],
                                ['prompt[aspect_ratio]', 'aspect_ratio', 'truthy'],
                                ['prompt[resolution]', 'resolution', 'truthy'],
                                ['prompt[input_image]', 'input_image', 'media'],
                                ['prompt[mask_image]', 'mask_image', 'media'],
                                ['prompt[pack_id]', 'pack_id', 'truthy'],
                                ['prompt[base_pack_id]', 'base_pack_id', 'truthy']],
                     'target': 'form',
                     'result': {'first': True},
                     'model': {'argument': 'model', 'output': 'model_id'},
                     'references': {'argument': 'references', 'model': 'model_id', 'texts': ['text']},
                     'image_count': {'argument': 'num_images',
                                     'input': 'input_image',
                                     'edit': 1,
                                     'generate': 2}},
 'generate_video': {'method': 'POST',
                    'path': '/tunes/{model_id}/prompts',
                    'fields': [['prompt[text]', 'text', 'value'],
                               ['prompt[num_images]', 'num_images', 'value'],
                               ['prompt[seed]', 'seed', 'truthy'],
                               ['prompt[film_grain]', 'film_grain', 'boolean'],
                               ['prompt[aspect_ratio]', 'aspect_ratio', 'truthy'],
                               ['prompt[resolution]', 'resolution', 'truthy'],
                               ['prompt[input_image]', 'input_image', 'media'],
                               ['prompt[mask_image]', 'mask_image', 'media'],
                               ['prompt[pack_id]', 'pack_id', 'truthy'],
                               ['prompt[base_pack_id]', 'base_pack_id', 'truthy'],
                               ['prompt[video_model]', 'video_model', 'truthy'],
                               ['prompt[video_resolution]', 'video_resolution', 'truthy'],
                               ['prompt[video_prompt]', 'video_prompt', 'value'],
                               ['prompt[image_references][]', 'image_references', 'media_array', 'prompt[image_reference_urls][]'],
                               ['prompt[video_duration]', 'duration', 'truthy'],
                               ['prompt[video_first_frame]', 'first_frame', 'media'],
                               ['prompt[video_last_frame]', 'last_frame', 'media'],
                               ['prompt[video_references][]', 'video_references', 'media_array', 'prompt[video_references][]'],
                               ['prompt[audio_references][]', 'audio_references', 'media_array', 'prompt[audio_references][]'],
                               ['prompt[generate_audio]', 'generate_audio', 'boolean'],
                               ['prompt[video_audio]', 'generate_audio', 'boolean']],
                    'target': 'form',
                    'result': {'first': True},
                    'model': {'argument': 'model', 'output': 'model_id'},
                    'catalog_defaults': {'video_model': 'default_video_model_family'},
                    'references': {'argument': 'references',
                                   'model': 'model_id',
                                   'texts': ['text', 'video_prompt']}},
 'generate_music': {'method': 'POST',
                    'path': '/tunes/{model_id}/prompts',
                    'fields': [['prompt[text]', 'text', 'value'],
                               ['prompt[lyrics]', 'lyrics', 'truthy'],
                               ['prompt[instrumental]', 'instrumental', 'flag'],
                               ['prompt[audio_reference]', 'audio_reference', 'media'],
                               ['prompt[num_images]', 'num_images', 'value']],
                    'target': 'form',
                    'result': {'first': True},
                    'model': {'argument': 'model', 'output': 'model_id',
                              'catalog': ['music_models', 'default_music_model']}},
 'list_prompts': {'method': 'GET',
                  'path': '/prompts',
                  'fields': [[name + ('[]' if spec['mode'] == 'array' else ''), name, spec['mode']]
                             for name, spec in PROMPT_FILTERS.items()] + [['expand[]', 'expand', 'array']],
                  'target': 'query',
                  'result': {'pick': ['id',
                                      'creation_source',
                                      'creation_client',
                                      'text',
                                      'num_images',
                                      'cost_mc',
                                      'images',
                                      'aspect_ratio',
                                      'resolution',
                                      'pack_id',
                                      'tune_id',
                                      'order_id'],
                             'expand': {'debug_images': ['debug_images',
                                                         'debug_filenames',
                                                         'debug_content_types'],
                                        'prompt.debug_images': ['debug_images',
                                                                'debug_filenames',
                                                                'debug_content_types'],
                                        'comments': ['comments'],
                                        'prompt.comments': ['comments']}},
                  'path_choice': ['tune_id', '/tunes/{tune_id}/prompts']},
 'get_prompt': {'method': 'GET',
                'path': '/prompts/{id}',
                'fields': [['expand[]', 'expand', 'array']],
                'target': 'query',
                'result': {}},
 'list_templates': {'method': 'GET',
                    'path': '/packs',
                    'fields': [['limit', 'limit', 'truthy'], ['offset', 'offset', 'truthy'], ['sort', 'sort', 'truthy']],
                    'target': 'query',
                    'result': {'pick': ['id', 'title', 'slug', 'subtitle', 'main_class_name', 'costs', 'thumbnail_url']}},
 'get_template': {'method': 'GET', 'path': '/p/{slug}.json', 'fields': [], 'target': 'query', 'result': {}},
 'get_template_text': {'method': 'GET',
                       'path': '/p/{slug}.txt',
                       'fields': [['class', 'class_name', 'truthy'], ['limit', 'limit', 'truthy'], ['offset', 'offset', 'truthy']],
                       'target': 'query',
                       'result': {'text': True}},
 'run_template': {'method': 'POST',
                  'path': '/p/{slug}/tunes',
                  'fields': [['tune[tune_ids][]', 'tune_id', 'ids'],
                             ['tune[title]', 'title', 'truthy'],
                             ['tune[name]', 'name', 'truthy'],
                             ['tune[images][]', 'image', 'array'],
                             ['tune[image_urls][]', 'image_url', 'array'],
                             ['tune[brief]', 'brief', 'truthy'],
                             ['tune[prompt_ids][]', 'prompt_ids', 'ids'],
                             ['tune[prompt_attributes][num_images]', 'num_images', 'truthy'],
                             ['tune[prompt_attributes][aspect_ratio]', 'aspect_ratio', 'truthy'],
                             ['tune[prompt_attributes][resolution]', 'resolution', 'truthy'],
                             ['tune[prompt_attributes][inpaint_faces]', 'inpaint_faces', 'boolean']],
                  'target': 'form',
                  'result': {},
                  'requires_any': ['tune_id', 'title', 'name', 'image', 'image_url']}}


API_OPERATIONS.update({
    "classify_image": {"method": "POST", "path": "/images/class_name", "target": "form",
        "fields": [["file_url", "source", "value"], ["class_names[]", "class_name", "array"]], "result": {}},
    "compose_video_edit": {"method": "POST", "path": "/variate/prompt", "target": "json_body",
        "fields": [["brief", "brief", "value"], ["tune_ids", "tune_id", "json"]], "result": {}},
    "inspect_image": {"method": "POST", "path": "/images/describe", "target": "form",
        "fields": [["file_url", "source", "value"], ["names[]", "name", "array"]], "result": {}},
    "inspect_video": {"method": "POST", "path": "/videos/inspect", "target": "json_body",
        "fields": [["file_url", "file_url", "value"], ["blob_signed_id", "blob_signed_id", "value"],
            ["tune_ids", "tune_id", "json"]], "result": {}},
    "get_video_inspection": {"method": "GET", "path": "/videos/inspect/{id}", "target": "query",
        "fields": [], "result": {}, "no_workspace": True},
    "enhance_video": {"method": "POST", "path": "/prompts/{id}/enhance_video", "target": "json_body",
        "fields": [["video_upscale_model", "video_upscale_model", "truthy"],
            ["video_upscale_target_resolution", "video_upscale_target_resolution", "truthy"],
            ["video_fps_model", "video_fps_model", "truthy"]],
        "result": {}, "requires_any": ["video_upscale_model", "video_fps_model"]},
    "attach_prompt_media": {"method": "POST", "path": "/prompts/{id}/images", "target": "json_body",
        "fields": [["blob_signed_id", "blob_signed_id", "value"]], "result": {}},
    "replace_prompt_media": {"method": "POST", "path": "/prompts/{id}/images", "target": "json_body",
        "fields": [["blob_signed_id", "blob_signed_id", "value"], ["replace_blob_id", "replace_blob_id", "value"],
            ["replace", "replace", "value"]], "result": {}},
    "create_workspace": {"method": "POST", "path": "/workspaces.json", "target": "json_body", "root": "workspace",
        "fields": [["title", "title", "value"], ["url", "url", "value"]], "result": {}, "no_workspace": True},
    "attach_workspace_images": {"method": "POST", "path": "/workspaces/{id}/attach_images.json", "target": "json_body",
        "fields": [["signed_ids", "signed_ids", "json"], ["image_urls", "image_urls", "json"]],
        "result": {}, "requires_any": ["signed_ids", "image_urls"]},
    "get_workspace": {"method": "GET", "path": "/workspaces/{id}.json", "target": "query", "fields": [], "result": {}},
    "update_workspace": {"method": "PATCH", "path": "/workspaces/{id}.json", "target": "json_body", "root": "workspace",
        "fields": [["title", "title", "value"], ["url", "url", "value"], ["landing_page_html", "landing_page_html", "value"], ["brief", "brief", "value"]],
        "result": {}, "requires_present": ["title", "url", "landing_page_html", "brief"]},
    "create_template": {"method": "POST", "path": "/packs", "target": "json_body", "root": "pack",
        "fields": [["title", "title", "value"], ["subtitle", "subtitle", "value"], ["base_tune_id", "model_id", "value"],
            ["model_type", "model_type", "value"], ["main_class_name", "main_class_name", "value"]],
        "model": {"argument": "model", "output": "model_id"}, "result": {}},
    "update_template": {"method": "PATCH", "path": "/packs/{id}", "target": "json_body", "root": "pack",
        "fields": [["title", "title", "value"], ["subtitle", "subtitle", "value"], ["main_class_name", "main_class_name", "value"],
            ["reference_class_names", "reference_class_names", "json"]], "result": {},
        "requires_present": ["title", "subtitle", "main_class_name", "reference_class_names"]},
    "update_reference": {"method": "PATCH", "path": "/tunes/{id}", "target": "json_body", "root": "tune",
        "fields": [["title", "title", "value"], ["name", "name", "value"], ["characteristics", "characteristics", "json"],
            ["sources", "sources", "json"]], "result": {}, "requires_present": ["title", "name", "description", "text", "sources"],
        "characteristics": {"short_description": "description", "text": "text"}},
    "update_prompt": {"method": "PATCH", "path": "/prompts/{id}", "target": "json_body", "root": "prompt",
        "fields": [["pack_id", "pack_id", "nullable_id"], ["base_pack_id", "base_pack_id", "nullable_id"],
            ["workspace_id", "workspace_id", "nullable_id"]], "result": {},
        "requires_present": ["pack_id", "base_pack_id", "workspace_id"]},
    # Archiving hides a prompt or reference from lists and is undone by unarchive; nothing is deleted.
    "archive_prompt": {"method": "PATCH", "path": "/prompts/{id}/archive", "target": "json_body", "fields": [], "result": {},
        "path_choice": ["unarchive", "/prompts/{id}/unarchive"]},
    "archive_reference": {"method": "PATCH", "path": "/tunes/{id}/archive", "target": "json_body", "fields": [], "result": {},
        "path_choice": ["unarchive", "/tunes/{id}/unarchive"]},
    # Headless agent runs, reported as A2A tasks. The run id is its chat session id.
    "start_agent_run": {"method": "POST", "path": "/api/agent_runs", "target": "form",
        "fields": [["workspace_id", "workspace", "value"], ["message", "message", "value"]], "result": {}},
    "get_agent_run": {"method": "GET", "path": "/api/agent_runs/{id}", "target": "query", "fields": [], "result": {},
        "no_workspace": True},
    "reply_agent_run": {"method": "POST", "path": "/api/agent_runs/{id}/reply", "target": "json_body",
        "fields": [["tool_call_id", "tool_call_id", "value"], ["answers", "answers", "json"]], "result": {}, "no_workspace": True},
    "cancel_agent_run": {"method": "POST", "path": "/api/agent_runs/{id}/cancel", "target": "form", "fields": [], "result": {},
        "no_workspace": True},
})
API_OPERATIONS["run_template"]["fields"].append(["tune[tune_replacements]", "tune_replacements", "replacements"])
API_OPERATIONS["run_template"]["requires_any"].append("tune_replacements")
API_OPERATIONS["run_template"]["fields"].append(["tune[prompt_attributes]", "prompt_attributes", "attributes"])
API_OPERATIONS["generate_video"]["fields"].append(["prompt[order_id]", "order_id", "truthy"])
for generation_operation in ("generate_images", "generate_video", "generate_music"):
    API_OPERATIONS[generation_operation]["fields"].append(["prompt[skill_name]", "skill_name", "truthy"])

JSON_ARGUMENT_SCHEMAS = {
    "background_color": {"type": "string", "pattern": "#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})"},
    "create_crops": {"type": "integer", "minimum": 0, "maximum": 100},
    "prompt_attributes": {"type": "object", "propertyNames": {"pattern": "^[a-z][a-z0-9_]*$"},
        "additionalProperties": {"type": "string"}},
    "sources": {"type": "array", "items": {"type": "object", "properties": {
        "provider": {"type": "string"}, "account_key": {"type": "string"},
        "resource_type": {"type": "string"}, "external_id": {"type": "string"},
        "metadata": {"type": "object", "additionalProperties": True}},
        "required": ["provider", "account_key", "resource_type", "external_id", "metadata"], "additionalProperties": False}},
    "tune_replacements": {"type": "object", "propertyNames": {"pattern": "^[1-9][0-9]*$"},
        "additionalProperties": {"type": "array", "minItems": 1,
            "items": {"type": "string", "pattern": "^[1-9][0-9]*$"}}},
    # As the chat UI answers ask_user: a label per question, or labels for multi-select.
    "answers": {"type": "object", "additionalProperties": {"anyOf": [
        {"type": "string", "minLength": 1}, {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}}]}},
}


def validate_argument(schema, value):
    if "anyOf" in schema:
        return any(validate_argument(option, value) for option in schema["anyOf"])
    kind = schema["type"]
    if kind == "string":
        return (isinstance(value, str) and len(value) >= schema.get("minLength", 0)
            and ("pattern" not in schema or re.fullmatch(schema["pattern"], value) is not None)
            and ("enum" not in schema or value in schema["enum"]))
    if kind == "integer":
        return (type(value) is int and schema.get("minimum", value) <= value <= schema.get("maximum", value))
    if kind == "null":
        return value is None
    if kind == "boolean":
        return isinstance(value, bool)
    if kind == "array":
        return (isinstance(value, list) and len(value) >= schema.get("minItems", 0)
            and all(validate_argument(schema["items"], item) for item in value))
    if kind == "object":
        if not isinstance(value, dict) or not set(schema.get("required", [])).issubset(value):
            return False
        properties = schema.get("properties", {})
        extra = schema.get("additionalProperties", True)
        for key, item in value.items():
            if "propertyNames" in schema and re.fullmatch(schema["propertyNames"]["pattern"], key) is None:
                return False
            rule = properties.get(key, extra)
            if rule is False or (isinstance(rule, dict) and not validate_argument(rule, item)):
                return False
        return True
    raise AstriaError(f"Unsupported argument type: {kind}")


def structured_argument(name):
    def parse(value):
        try:
            result = json.loads(value)
        except json.JSONDecodeError as error:
            raise argparse.ArgumentTypeError(str(error)) from error
        if not validate_argument(JSON_ARGUMENT_SCHEMAS[name], result):
            raise argparse.ArgumentTypeError(f"Invalid {name} JSON")
        return result
    return parse


def nullable_id(value):
    if value == "null":
        return None
    if not re.fullmatch(r"[1-9][0-9]*", str(value)):
        raise AstriaError("IDs must be positive integers or 'null' to clear the assignment")
    return int(value)


def operation_path(definition, values):
    path = definition["path"]
    if "path_choice" in definition:
        argument, alternative = definition["path_choice"]
        if values.get(argument):
            path = alternative
    return re.sub(r"\{([^}]+)\}", lambda match: quote(str(values[match[1]]), safe=""), path)


def operation_fields(name, values, resolved_media=None):
    result = []
    resolved_media = resolved_media or {}
    for spec in API_OPERATIONS[name]["fields"]:
        wire, argument, mode = spec[:3]
        value = values.get(argument)
        if value is None or (mode not in ("value", "boolean", "json", "nullable_id") and not value):
            continue
        if mode in ("truthy", "value"):
            result.append(field(wire, value))
        elif mode in ("boolean", "flag"):
            result.append(field(wire, "true" if value else "false"))
        elif mode == "array":
            result.extend(field(wire, item) for item in value)
        elif mode == "ids":
            items = value if isinstance(value, list) else [value]
            result.extend(field(wire, item) for raw in items for item in _id_list(raw))
        elif mode == "json":
            result.append((wire, value))
        elif mode == "attributes":
            if not validate_argument(JSON_ARGUMENT_SCHEMAS["prompt_attributes"], value):
                raise AstriaError("Invalid prompt_attributes: use plain attribute names and string values")
            result.extend(field(f"{wire}[{key}]", item) for key, item in value.items())
        elif mode == "nullable_id":
            result.append((wire, nullable_id(value)))
        elif mode == "replacements":
            if not validate_argument(JSON_ARGUMENT_SCHEMAS["tune_replacements"], value):
                raise AstriaError("Invalid tune_replacements")
            result.extend(field(f"{wire}[{source}][]", int(target))
                          for source, targets in value.items() for target in targets)
        elif mode == "json_string":
            result.append(field(wire, json.dumps(value, ensure_ascii=False, separators=(",", ":"))))
        elif mode == "media":
            result.append(media_field(wire, value, resolved_media.get(argument, value)))
        elif mode == "media_array":
            result.extend(field(spec[3] if remote_url(original) else wire, resolved)
                          for original, resolved in zip(value, resolved_media.get(argument, value)))
        else:
            raise AstriaError(f"Unknown operation field mode: {mode}")
    return result


def operation_result(definition, value, values):
    spec = definition["result"]
    if spec.get("first") and isinstance(value, list):
        return value[0]
    if "pick" in spec:
        keys = list(spec["pick"])
        for expanded in values.get("expand") or []:
            keys.extend(spec.get("expand", {}).get(expanded, []))
        return [{key: item.get(key) for key in dict.fromkeys(keys)} for item in value]
    if "object" in spec:
        section = values.get(spec["sections"]["argument"]) if "sections" in spec else None
        keys = spec["sections"]["keys"][section] if section else spec["object"]
        projected = {key: value.get(source, default) for key, (source, default) in spec["object"].items() if key in keys}
        projected.update(spec.get("constants", {}))
        projected.update({key: yes if value.get(condition) else no
                          for key, (condition, yes, no) in spec.get("choices", {}).items()})
        return projected
    return value


def execute_api_operation(name, args, cfg, *, extra_fields=None):
    definition = API_OPERATIONS[name]
    values = vars(args).copy()
    if "model" in definition:
        model = definition["model"]
        values[model["output"]] = resolve_model(cfg, values.get(model["argument"]), model.get("catalog", MODEL_CATALOG))
    apply_catalog_defaults(cfg, definition, values)
    if "requires_present" in definition and not any(values.get(key) is not None for key in definition["requires_present"]):
        raise AstriaError("Provide at least one of: " + ", ".join(definition["requires_present"]))
    if "per_image" in definition:
        spec = definition["per_image"]
        items = values.get(spec["argument"])
        count = sum(len(values.get(key) or []) for key in spec["images"])
        if items and len(items) != count:
            raise AstriaError(f"Provide one {spec['argument']} per image: {count} images, {len(items)} given")
    if "characteristics" in definition:
        changes = {key: values[argument] for key, argument in definition["characteristics"].items()
                   if values.get(argument) is not None}
        if changes:
            existing = request(cfg, "GET", operation_path(definition, values), query=[],
                               workspace=values.get("workspace"))["characteristics"] if definition["method"] == "PATCH" else {}
            values["characteristics"] = {**existing, **changes}
    fields = operation_fields(name, values) + (extra_fields or [])
    # A JSON body nests its fields under root, or sends them top-level when it has none.
    body = {definition["root"]: dict(fields)} if "root" in definition else dict(fields)
    options = {definition["target"]: body if definition["target"] == "json_body" else fields}
    if definition.get("no_workspace"):
        options["no_workspace"] = True
    else:
        options["workspace"] = values.get("workspace")
    result = request(cfg, definition["method"], operation_path(definition, values), **options)
    return operation_result(definition, result, values)


# --------------------------------------------------------------------------
# errors / output
# --------------------------------------------------------------------------
class AstriaError(Exception):
    pass


_operation_output = contextvars.ContextVar("astria_operation_output", default=None)


def die(msg, code=1):
    if _operation_output.get() is not None:
        raise AstriaError(msg)
    print(f"astria: {msg}", file=sys.stderr)
    sys.exit(code)


def emit(obj):
    """Print a result as JSON on stdout — skills parse this."""
    sink = _operation_output.get()
    if sink is not None:
        sink.append(obj)
        return
    json.dump(obj, sys.stdout, ensure_ascii=False, indent=2)
    sys.stdout.write("\n")


# --------------------------------------------------------------------------
# config + credential resolution
# --------------------------------------------------------------------------
def resolve_profile(cli_value):
    """Profile precedence: --profile flag > ASTRIA_PROFILE env > 'default'."""
    profile = cli_value or os.environ.get("ASTRIA_PROFILE") or "default"
    if not profile.replace("-", "").replace("_", "").replace(".", "").isalnum():
        die(f"invalid profile name {profile!r} — use letters, digits, '-', '_', '.'")
    return profile


def argv_profile():
    """Peek at --profile in argv before the parser exists, so build_parser()
    can read the right profile's models cache for the --help enum text."""
    argv = sys.argv[1:]
    for i, token in enumerate(argv):
        if token == "--profile":
            return argv[i + 1] if i + 1 < len(argv) else None
        if token.startswith("--profile="):
            return token.split("=", 1)[1]
    return None


def normalize_meta_argv(argv):
    """Support command-style help/version aliases before argparse requires a verb."""
    command_index = 0
    while command_index < len(argv):
        token = argv[command_index]
        if token == "--profile":
            command_index += 2
            continue
        if token.startswith("--profile="):
            command_index += 1
            continue
        break

    if command_index >= len(argv):
        return argv
    command = argv[command_index]
    if command == "help":
        return argv[:command_index] + argv[command_index + 1:] + ["--help"]
    if command == "version" and command_index == len(argv) - 1:
        return argv[:command_index] + ["--version"]
    return argv


def apply_profile(profile):
    """Point CONFIG_PATH / MODELS_CACHE at this profile's files. The 'default'
    profile keeps the original config.json / models.json names; a named profile
    'X' uses config.X.json / models.X.json — like the AWS CLI's profiles."""
    global ACTIVE_PROFILE, CONFIG_PATH, MODELS_CACHE
    ACTIVE_PROFILE = profile
    suffix = "" if profile == "default" else f".{profile}"
    CONFIG_PATH = CONFIG_DIR / f"config{suffix}.json"
    MODELS_CACHE = CONFIG_DIR / f"models{suffix}.json"


def load_config():
    if CONFIG_PATH.is_file():
        try:
            return json.loads(CONFIG_PATH.read_text())
        except (OSError, ValueError):
            return {}
    return {}


def save_config(cfg):
    CONFIG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
    CONFIG_PATH.write_text(json.dumps(cfg, indent=2) + "\n")
    CONFIG_PATH.chmod(0o600)


def api_key(cfg):
    key = os.environ.get("ASTRIA_API_KEY") or os.environ.get("ASTRIA_AUTH_TOKEN") or cfg.get("api_key")
    if not key:
        die("not authenticated — run `astria login` (or set ASTRIA_API_KEY)")
    return key


def base_url(cfg):
    return (os.environ.get("ASTRIA_BASE_URL") or cfg.get("base_url") or DEFAULT_BASE_URL).rstrip("/")


def login_hint(cfg, override_base_url=None):
    return f"{(override_base_url or base_url(cfg)).rstrip('/')}/users/edit/api"


def resolve_workspace(cfg, override):
    """Workspace scope: --workspace flag > env > config. `all` and `personal` pass through."""
    ws = override or os.environ.get("ASTRIA_WORKSPACE_ID") or os.environ.get("WORKSPACE_ID") or cfg.get("workspace_id")
    return str(ws) if ws not in (None, "", "personal") else None


def resolve_num_images(cfg, override, fallback):
    value = override or cfg.get("default_num_images") or fallback
    if not str(value).isdigit() or int(value) < 1:
        die("default_num_images / --num-images must be a positive integer")
    return str(value)


# --- model catalog (/cli/models, cached daily) ---
def load_models_cache():
    if MODELS_CACHE.is_file():
        try:
            return json.loads(MODELS_CACHE.read_text())
        except (OSError, ValueError):
            return None
    return None


def models_cache_stale(record, cfg):
    if not record or not record.get("models"):
        return True
    # caches written before music models / the video family default were recorded lack the key entirely
    if "music_models" not in record or "default_video_model_family" not in record:
        return True
    if record.get("base_url") != base_url(cfg):
        return True
    return time.time() - record.get("fetched_at", 0) > record.get("ttl", MODELS_TTL_DEFAULT)


def fetch_models(cfg):
    """Fetch /cli/models and write the cache. Returns the record, or None on failure."""
    try:
        payload = request(cfg, "GET", "/cli/models", auth=False, no_workspace=True)
    except AstriaError:
        return None
    if not isinstance(payload, dict) or not isinstance(payload.get("models"), dict):
        return None
    record = {
        "base_url": base_url(cfg),
        "fetched_at": int(time.time()),
        "ttl": payload.get("cache_ttl") or MODELS_TTL_DEFAULT,
        "default": payload.get("default", "gemini"),
        "model_selection_guidance": payload.get("model_selection_guidance"),
        "default_video_model": payload.get("default_video_model"),
        "default_video_model_family": payload.get("default_video_model_family"),
        "models": payload["models"],
        "video_models": payload.get("video_models") or {},
        "video_model_families": payload.get("video_model_families") or {},
        "default_music_model": payload.get("default_music_model"),
        "music_models": payload.get("music_models") or {},
        "cli": payload.get("cli") or {},
        "skills": payload.get("skills") or {},
    }
    try:
        CONFIG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
        MODELS_CACHE.write_text(json.dumps(record, indent=2) + "\n")
    except OSError:
        pass
    return record


def _version_tuple(v):
    try:
        return tuple(int(x) for x in str(v).split("."))
    except (TypeError, ValueError):
        return None


def install_cli_upgrade(url, target, *, force=False):
    current = _version_tuple(VERSION)

    try:
        proc = subprocess.run(["curl", "-fsSL", "-A", USER_AGENT, url], capture_output=True)
    except FileNotFoundError:
        raise AstriaError("`curl` not found on PATH — install curl")
    if proc.returncode != 0:
        raise AstriaError(f"could not download upgrade from {url}: {proc.stderr.decode('utf-8', 'replace').strip()}")

    try:
        source = proc.stdout.decode("utf-8")
        ast.parse(source)
    except (UnicodeDecodeError, SyntaxError) as exc:
        raise AstriaError(f"downloaded upgrade is not a valid astria CLI script: {exc}")

    new_version = downloaded_cli_version(source)
    downloaded = _version_tuple(new_version)
    if current and downloaded and downloaded < current and not force:
        raise AstriaError(f"refusing to downgrade astria {VERSION} to {new_version}; pass --force to install anyway")
    if current and downloaded and downloaded == current and not force:
        return None
    if not target.is_file():
        raise AstriaError(f"cannot upgrade {target}: executable file not found")
    if not os.access(target, os.W_OK):
        raise AstriaError(f"cannot write {target}; rerun with permissions to update that file")

    tmp = target.with_name(f".{target.name}.upgrade-{os.getpid()}")
    try:
        mode = target.stat().st_mode & 0o777
        tmp.write_bytes(proc.stdout)
        tmp.chmod(mode or 0o755)
        os.replace(tmp, target)
    except OSError as exc:
        raise AstriaError(f"could not install upgrade at {target}: {exc}")
    finally:
        try:
            tmp.unlink()
        except FileNotFoundError:
            pass

    return new_version


def auto_upgrade_cli(cli):
    if os.environ.get("ASTRIA_NO_AUTO_UPGRADE") or os.environ.get("ASTRIA_UPGRADED"):
        return False

    upgrade = cli.get("upgrade") or "please upgrade the astria CLI"
    target = current_executable_path()
    if not target.is_file() or not os.access(target, os.W_OK):
        print(f"astria: a newer CLI is available ({cli.get('latest_version')}) — {upgrade}", file=sys.stderr)
        return True

    try:
        new_version = install_cli_upgrade(cli.get("download_url") or UPGRADE_URL, target)
    except Exception as exc:
        print(f"astria: auto-upgrade failed: {exc}; {upgrade}", file=sys.stderr)
        return True

    if not new_version:
        return True

    print(f"astria: upgraded {VERSION} -> {new_version}; restarting", file=sys.stderr)
    os.environ["ASTRIA_UPGRADED"] = "1"
    try:
        os.execv(str(target), [str(target)] + sys.argv[1:])
    except OSError as exc:
        print(f"astria: restart after auto-upgrade failed: {exc}", file=sys.stderr)
    return True


def check_cli_version(record, *, auto_upgrade=False):
    """Enforce the min/latest CLI version from the cached /cli/models `cli` block:
    below min_version is a hard stop, below latest_version is an upgrade nudge."""
    cli = (record or {}).get("cli") or {}
    current = _version_tuple(VERSION)
    if not current:
        return
    upgrade = cli.get("upgrade") or "please upgrade the astria CLI"
    minimum = _version_tuple(cli.get("min_version"))
    if minimum and current < minimum:
        die(f"this astria CLI ({VERSION}) is no longer supported — {upgrade}")
    latest = _version_tuple(cli.get("latest_version"))
    if latest and current < latest:
        if auto_upgrade and auto_upgrade_cli(cli):
            return
        print(f"astria: a newer CLI is available ({cli.get('latest_version')}) — {upgrade}",
              file=sys.stderr)


def installed_skills_version():
    root = os.environ.get("CLAUDE_PLUGIN_ROOT")
    if not root:
        return None
    try:
        data = json.loads((Path(root) / ".claude-plugin" / "plugin.json").read_text())
    except (OSError, json.JSONDecodeError):
        return None
    return data.get("version")


def skills_upgrade_context(record):
    current = installed_skills_version()
    if not current:
        return None

    skills = (record or {}).get("skills") or {}
    latest = skills.get("latest_version")
    current_tuple = _version_tuple(current)
    latest_tuple = _version_tuple(latest)
    if not current_tuple or not latest_tuple or current_tuple >= latest_tuple:
        return None

    upgrade = skills.get("upgrade") or "reinstall the Astria skills plugin from astriaai/skills"
    return (
        f"The Astria skills plugin is outdated ({current} < {latest}). "
        f"If the user asks to do anything with Astria, tell them to {upgrade}."
    )


def downloaded_cli_version(source):
    match = re.search(r'^VERSION = "([^"]+)"', source, re.MULTILINE)
    return match.group(1) if match else None


def current_executable_path(override=None):
    if override:
        return Path(override).resolve()
    candidate = Path(sys.argv[0])
    if not candidate.is_absolute() and candidate.parent == Path("."):
        found = shutil.which(sys.argv[0])
        if found:
            candidate = Path(found)
    return candidate.resolve()


def model_catalog(cfg):
    """Model name -> tune id catalog: the cached /cli/models response (refreshed
    daily), falling back to built-in MODEL_TUNES when the endpoint is unreachable."""
    if isinstance(cfg, OperationContext):
        return request(cfg, "GET", "/cli/models", auth=False, no_workspace=True)
    record = load_models_cache()
    if models_cache_stale(record, cfg):
        record = fetch_models(cfg) or record
    if record and record.get("models"):
        return record
    return {
        "default": "gemini",
        "models": {name: {"tune_id": tid} for name, tid in MODEL_TUNES.items()},
        "builtin": True,
    }


# (catalog section, its default key) in /cli/models; songs use ("music_models", "default_music_model")
MODEL_CATALOG = ("models", "default")


def apply_catalog_defaults(cfg, definition, values):
    """Fill omitted arguments from catalog keys, e.g. video_model from default_video_model_family."""
    for argument, key in definition.get("catalog_defaults", {}).items():
        if values.get(argument) is None:
            values[argument] = model_catalog(cfg).get(key)
            if values[argument] is None:
                die(f"the model catalog has no {key} — run `astria models --refresh` or pass --{argument.replace('_', '-')}")


def resolve_model(cfg, name, catalog_keys=MODEL_CATALOG):
    """Map a model name (gemini/seedream/mureka-v9.5/...) or a raw tune id to a tune id."""
    models_key, default_key = catalog_keys
    catalog = None
    if name is None and catalog_keys == MODEL_CATALOG:
        name = cfg.get("default_model")
    if name is None:
        catalog = model_catalog(cfg)
        name = catalog.get(default_key)
        if name is None:
            die(f"the model catalog has no {default_key} — run `astria models --refresh` or pass --model")
    if str(name).isdigit():
        return str(name)
    key = str(name).lower()
    # 1. environment override — the Astria web app injects these
    if not isinstance(cfg, OperationContext) and key in MODEL_ENV and os.environ.get(MODEL_ENV[key]):
        return os.environ[MODEL_ENV[key]]
    # 2. explicit per-model override in the config file
    if cfg.get(f"{key}_tune_id"):
        return str(cfg[f"{key}_tune_id"])
    # 3. the server catalog (cached daily)
    if catalog is None:
        catalog = model_catalog(cfg)
    entry = catalog.get(models_key, {}).get(key)
    if entry and entry.get("tune_id"):
        return str(entry["tune_id"])
    # 4. built-in offline fallback
    if key in MODEL_TUNES:
        return MODEL_TUNES[key]
    die(f"unknown model {name!r} — run `astria models` to list available models, or pass a numeric tune id")


# --------------------------------------------------------------------------
# HTTP — delegated to curl (handles redirects and retries)
# --------------------------------------------------------------------------
def request(cfg, method, path, *, query=None, form=None, json_body=None, workspace=None,
            no_workspace=False, auth=True, timeout=120, idempotency_key=None):
    if isinstance(cfg, OperationContext):
        return cfg.transport(method, path, query=query, form=form, json_body=json_body,
                             workspace=workspace, no_workspace=no_workspace, auth=auth)
    url = base_url(cfg) + path
    if query:
        url += ("&" if "?" in url else "?") + urlencode(query, doseq=True)

    argv = ["curl", "-sS", "--retry", "2", "--max-time", str(timeout), "-A", USER_AGENT, "-X", method,
            "-H", "Accept: application/json"]
    if auth:
        argv += ["-H", f"Authorization: Bearer {api_key(cfg)}"]
    if method != "GET":
        # curl --retry re-sends this exact argv after a timeout or 5xx, so every retry carries the same key and the
        # API returns the request it already accepted instead of creating (and billing) a second one.
        argv += ["-H", f"Idempotency-Key: {idempotency_key or 'astria-cli-' + uuid.uuid4().hex}"]

    if not no_workspace:
        ws = workspace if workspace is not None else resolve_workspace(cfg, None)
        if ws:
            argv += ["-H", f"X-Workspace-Id: {ws}"]

    stdin = None
    if json_body is not None:
        argv += ["-H", "Content-Type: application/json", "--data-binary", "@-"]
        stdin = json.dumps(json_body).encode()
    for key, value in (form or []):
        argv += ["--form-string", f"{key}={value}"]

    argv += ["-w", "\n%{http_code}", url]

    try:
        proc = subprocess.run(argv, input=stdin, capture_output=True)
    except FileNotFoundError:
        die("`curl` not found on PATH — install curl")

    if proc.returncode != 0:
        raise AstriaError(f"network error ({method} {path}): {proc.stderr.decode('utf-8', 'replace').strip()}")

    raw = proc.stdout.decode("utf-8", "replace")
    body, _, status = raw.rpartition("\n")
    try:
        status = int(status)
    except ValueError:
        raise AstriaError(f"unexpected curl output for {method} {path}")

    parsed = None
    if body.strip():
        try:
            parsed = json.loads(body)
        except ValueError:
            parsed = None

    if status == 426:
        hint = (parsed.get("upgrade") or parsed.get("error")) if isinstance(parsed, dict) else None
        die(f"this astria CLI ({VERSION}) is no longer supported — {hint or 'please upgrade to continue'}")
    if status >= 400:
        msg = None
        if isinstance(parsed, dict):
            msg = parsed.get("error") or parsed.get("message")
        raise AstriaError(f"{method} {path} → HTTP {status}: {msg or body.strip()[:400]}")

    return parsed if parsed is not None else body


def field(key, value):
    """A form field. Local attachments are represented by direct-upload signed ids."""
    return (key, value)


def remote_url(value):
    return str(value).startswith(("http://", "https://"))


def media_field(prefix, value, resolved):
    """Resolve an image/video argument to the right form field: URL vs signed id.

    A URL goes in the `_url` variant of the field, with the suffix inserted
    inside the param brackets — `prompt[input_image]` -> `prompt[input_image_url]`."""
    if remote_url(value):
        url_key = f"{prefix[:-1]}_url]" if prefix.endswith("]") else f"{prefix}_url"
        return field(url_key, value)
    return field(prefix, resolved)


DIRECT_UPLOAD_MAX_BYTES = 100 * 1024 * 1024
DIRECT_UPLOAD_WORKERS = 6
CONTENT_TYPE_OVERRIDES = {
    ".avif": "image/avif",
    ".heic": "image/heic",
    ".heif": "image/heif",
    ".mov": "video/quicktime",
    ".webp": "image/webp",
}
DIRECT_UPLOAD_CONTENT_TYPE_PREFIXES = ("image/", "video/", "audio/")


def file_content_type(path):
    return (CONTENT_TYPE_OVERRIDES.get(path.suffix.lower())
            or mimetypes.guess_type(path.name)[0]
            or "application/octet-stream")


def file_md5(path):
    digest = hashlib.md5()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return base64.b64encode(digest.digest()).decode("ascii")


def direct_upload(cfg, value):
    """Upload one local file straight to Active Storage and return its signed id."""
    return direct_uploads(cfg, [value])[0]


def prepare_direct_upload(value):
    path = Path(value)
    if not path.is_file():
        die(f"file not found: {value}")
    size = path.stat().st_size
    if size > DIRECT_UPLOAD_MAX_BYTES:
        die(f"file must be at most 100 MB: {value}")
    content_type = file_content_type(path)
    if content_type != "text/plain" and not content_type.startswith(DIRECT_UPLOAD_CONTENT_TYPE_PREFIXES):
        die(f"unsupported upload content type {content_type}: {value}")
    return path, size, content_type


def perform_direct_upload_record(cfg, prepared):
    path, size, content_type = prepared
    blob = request(cfg, "POST", "/api/direct_uploads", json_body={"blob": {
        "filename": path.name,
        "byte_size": size,
        "checksum": file_md5(path),
        "content_type": content_type,
    }}, no_workspace=True)
    upload = blob["direct_upload"]
    argv = ["curl", "-sS", "--retry", "2", "--max-time", "600", "-X", "PUT"]
    for key, header_value in upload["headers"].items():
        argv += ["-H", f"{key}: {header_value}"]
    argv += ["--data-binary", f"@{path}", "-w", "\n%{http_code}", upload["url"]]
    try:
        proc = subprocess.run(argv, capture_output=True)
    except FileNotFoundError:
        die("`curl` not found on PATH — install curl")
    raw = proc.stdout.decode("utf-8", "replace")
    body, _, status = raw.rpartition("\n")
    if proc.returncode != 0 or not status.isdigit() or int(status) >= 400:
        detail = proc.stderr.decode("utf-8", "replace").strip() or body.strip()[:400]
        raise AstriaError(f"direct upload failed for {path}: {detail or status or 'unexpected response'}")
    return blob


def perform_direct_upload(cfg, prepared):
    return perform_direct_upload_record(cfg, prepared)["signed_id"]


def parallel_direct_upload(cfg, values, upload):
    prepared = [prepare_direct_upload(value) for value in values]
    if not prepared:
        return []
    with concurrent.futures.ThreadPoolExecutor(
            max_workers=min(DIRECT_UPLOAD_WORKERS, len(prepared))) as executor:
        return list(executor.map(lambda item: upload(cfg, item), prepared))


def direct_uploads(cfg, values):
    """Direct-upload local files in parallel and return signed ids in input order."""
    return parallel_direct_upload(cfg, values, perform_direct_upload)


def direct_upload_records(cfg, values):
    """Direct-upload local files in parallel and retain signed ids + public URLs."""
    return parallel_direct_upload(cfg, values, perform_direct_upload_record)


def direct_upload_handoff_records(cfg, paths):
    """Upload bounded handoff files; opaque skill assets travel as text/plain."""
    prepared = []
    for path in paths:
        size = path.stat().st_size
        content_type = file_content_type(path)
        if content_type != "text/plain" and not content_type.startswith(DIRECT_UPLOAD_CONTENT_TYPE_PREFIXES):
            content_type = "text/plain"
        prepared.append((path, size, content_type))
    if not prepared:
        return []
    with concurrent.futures.ThreadPoolExecutor(
            max_workers=min(DIRECT_UPLOAD_WORKERS, len(prepared))) as executor:
        return list(executor.map(lambda item: perform_direct_upload_record(cfg, item), prepared))


def resolve_media_values(cfg, values):
    """Replace local paths with signed ids while leaving remote URLs untouched."""
    uploads = iter(direct_uploads(cfg, [value for value in values if not remote_url(value)]))
    return [value if remote_url(value) else next(uploads) for value in values]


def image_reference_fields(values, resolved_values):
    values = values or []
    source_kinds = {
        "url" if remote_url(value) else "file"
        for value in values
    }
    if len(source_kinds) > 1:
        die("--image-reference cannot mix URLs and local files in one request")

    fields = []
    for value, resolved in zip(values, resolved_values):
        if source_kinds == {"url"}:
            fields.append(field("prompt[image_reference_urls][]", value))
            continue
        fields.append(field("prompt[image_references][]", resolved))
    return fields


# --------------------------------------------------------------------------
# polling
# --------------------------------------------------------------------------
WAIT_TIMEOUT_SEC = 600
WAIT_INTERVAL_SEC = 5
WAIT_INTERVAL_MIN = 2
WAIT_WORKERS = 6


def prompt_settled(prompt):
    """A prompt is settled once it has images OR a user_error — both are terminal."""
    return bool(prompt.get("images")) or bool(prompt.get("user_error"))


def wait_prompts(cfg, ids, *, workspace=None, timeout=WAIT_TIMEOUT_SEC,
                 interval=WAIT_INTERVAL_SEC, on_settled=None):
    """Poll many prompt ids in parallel until each settles or the wall-clock
    timeout fires. Returns {id: prompt_record_or_None}. on_settled(id, record)
    fires once per id as soon as it settles, so callers can stream output."""
    interval = max(WAIT_INTERVAL_MIN, interval)
    deadline = time.monotonic() + timeout
    settled = {}
    pending = list(ids)

    while pending and time.monotonic() < deadline:
        round_start = time.monotonic()
        queue = list(pending)
        lock = threading.Lock()
        results = {}
        errors = {}

        def pump():
            while True:
                with lock:
                    if not queue:
                        return
                    pid = queue.pop(0)
                try:
                    results[pid] = request(cfg, "GET", f"/prompts/{pid}.json", workspace=workspace)
                except AstriaError as exc:
                    # Transient — retry this id next round, don't mark settled.
                    errors[pid] = str(exc)

        threads = [threading.Thread(target=pump) for _ in range(min(WAIT_WORKERS, len(queue)))]
        for t in threads:
            t.start()
        for t in threads:
            t.join()

        still_pending = []
        for pid in pending:
            record = results.get(pid)
            if record is not None and prompt_settled(record):
                settled[pid] = record
                if on_settled:
                    on_settled(pid, record)
            else:
                still_pending.append(pid)
        pending = still_pending

        if not pending:
            break
        # Sleep the remainder of the interval — but not past the deadline.
        elapsed = time.monotonic() - round_start
        nap = min(max(0.0, interval - elapsed), max(0.0, deadline - time.monotonic()))
        if nap > 0:
            time.sleep(nap)

    for pid in pending:
        settled.setdefault(pid, None)
    return settled


def poll_prompt(cfg, tune_id, prompt_id, workspace=None):
    """Single-prompt wait used by `generate --wait` / `video --wait`. Delegates
    to wait_prompts so both code paths share the same settle rules."""
    results = wait_prompts(cfg, [str(prompt_id)], workspace=workspace,
                           timeout=WAIT_TIMEOUT_SEC, interval=WAIT_INTERVAL_SEC)
    record = results.get(str(prompt_id))
    if record is None:
        raise AstriaError(f"prompt {prompt_id} did not finish within {WAIT_TIMEOUT_SEC}s")
    return record


# --------------------------------------------------------------------------
# commands — auth
# --------------------------------------------------------------------------
def cmd_login(args, cfg):
    key = args.api_key
    if not key:
        if sys.stdin.isatty():
            try:
                import getpass
                key = getpass.getpass(f"Astria API key ({login_hint(cfg, args.base_url)}): ").strip()
            except (EOFError, KeyboardInterrupt):
                die("aborted")
        else:
            key = sys.stdin.readline().strip()
    if not key:
        die("no API key provided")

    cfg["api_key"] = key
    if args.base_url:
        cfg["base_url"] = args.base_url.rstrip("/")
    if args.workspace:
        cfg["workspace_id"] = args.workspace
    save_config(cfg)

    try:
        user = request(cfg, "GET", "/users", no_workspace=True)
        who = user.get("name") or user.get("email") or "your account"
        print(f"Logged in as {who} (profile '{ACTIVE_PROFILE}'). Config saved to {CONFIG_PATH}")
    except AstriaError as exc:
        die(f"saved key but verification failed: {exc}")


def cmd_logout(args, cfg):
    if CONFIG_PATH.is_file():
        CONFIG_PATH.unlink()
        print(f"Removed {CONFIG_PATH}")
    else:
        print("Not logged in.")


def cmd_whoami(args, cfg):
    user = request(cfg, "GET", "/users", no_workspace=True)
    emit({k: user.get(k) for k in ("id", "name", "email", "usd_balance_mc", "purchased_plugin_at")})


def cmd_config(args, cfg):
    if args.action == "get" or args.action is None:
        emit({
            "profile": ACTIVE_PROFILE,
            "base_url": base_url(cfg),
            "workspace_id": resolve_workspace(cfg, None),
            "default_model": cfg.get("default_model", "gemini"),
            "default_num_images": cfg.get("default_num_images"),
            "config_path": str(CONFIG_PATH),
            "authenticated": bool(os.environ.get("ASTRIA_API_KEY") or os.environ.get("ASTRIA_AUTH_TOKEN") or cfg.get("api_key")),
        })
    elif args.action == "set":
        if not args.key or args.value is None:
            die("usage: astria config set <key> <value>")
        aliases = {"workspace": "workspace_id"}
        allowed = {"base_url", "workspace_id", "workspace", "default_model", "default_num_images",
                   "gemini_tune_id", "seedream_tune_id", "gpt-image-2_tune_id"}
        if args.key not in allowed:
            die(f"unknown config key {args.key!r} — one of: {', '.join(sorted(allowed))}")
        key = aliases.get(args.key, args.key)
        if key == "default_num_images":
            if not str(args.value).isdigit() or int(args.value) < 1:
                die("default_num_images must be a positive integer")
            cfg[key] = str(int(args.value))
        else:
            cfg[key] = args.value
        save_config(cfg)
        print(f"Set {key} = {cfg[key]}")


def cmd_models(args, cfg):
    record = fetch_models(cfg) if args.refresh else model_catalog(cfg)
    if record is None:
        die("could not refresh models from the server")
    emit(operation_result(API_OPERATIONS["list_models"], record, vars(args)))

def cmd_upgrade(args, cfg):
    record = None if args.url else fetch_models(cfg)
    record = record or load_models_cache() or {}
    cli = record.get("cli") or {}
    url = args.url or cli.get("download_url") or UPGRADE_URL
    target = current_executable_path(args.path)
    new_version = install_cli_upgrade(url, target, force=args.force)
    if not new_version:
        print(f"astria {VERSION} is already current at {target}")
        return
    print(f"Upgraded astria {VERSION} -> {new_version or 'unknown'} at {target}")


# --------------------------------------------------------------------------
# commands — tunes / references
# --------------------------------------------------------------------------
def cmd_tunes_list(args, cfg):
    emit(execute_api_operation("list_references", args, cfg))

def cmd_tunes_get(args, cfg):
    emit(execute_api_operation("get_reference", args, cfg))

def cmd_tunes_create(args, cfg):
    if not (args.image_url or args.image):
        die("provide at least one --image-url or --image")
    if getattr(args, "image_caption", None) and args.image_url and args.image:
        # Rails attaches uploaded files before URLs, so a mixed set has no single caption order.
        die("--image-caption needs images from only --image-url or only --image")
    values = vars(args).copy()
    values["image"] = direct_uploads(cfg, args.image or [])
    emit(execute_api_operation("create_reference", argparse.Namespace(**values), cfg))

def cmd_tunes_update(args, cfg):
    emit(execute_api_operation("update_reference", args, cfg))

def cmd_tunes_archive(args, cfg):
    emit(execute_api_operation("archive_reference", args, cfg))


# --------------------------------------------------------------------------
# commands — prompts
# --------------------------------------------------------------------------
def cmd_prompts_list(args, cfg):
    emit(execute_api_operation("list_prompts", args, cfg))

def cmd_prompts_get(args, cfg):
    emit(execute_api_operation("get_prompt", args, cfg))

def cmd_prompts_update(args, cfg):
    emit(execute_api_operation("update_prompt", args, cfg))

def cmd_prompts_archive(args, cfg):
    emit(execute_api_operation("archive_prompt", args, cfg))

def cmd_prompts_enhance(args, cfg):
    emit(execute_api_operation("enhance_video", args, cfg))

def cmd_prompts_attach(args, cfg):
    # The Darkroom's save path, optionally replacing one result with a retained original.
    if bool(args.file) == bool(args.blob_signed_id):
        die("provide exactly one local file or --blob-signed-id")
    if args.file:
        args.blob_signed_id = direct_upload_records(cfg, [args.file])[0]["signed_id"]
    emit(execute_api_operation("replace_prompt_media" if args.replace else "attach_prompt_media", args, cfg))

def cmd_prompts_wait(args, cfg):
    ids = collect_prompt_ids(args)
    if not ids:
        die("no prompt ids — pass them as arguments, via --prompts-file, or on stdin")

    out_lock = threading.Lock()
    counts = {"done": 0, "failed": 0}

    def on_settled(pid, record):
        status = "done" if record.get("images") else "failed"
        counts[status] += 1
        line = {
            "id": pid,
            "images": record.get("images") or [],
            "user_error": record.get("user_error"),
            "status": status,
            "settled_at": int(time.time()),
        }
        with out_lock:
            json.dump(line, sys.stdout, ensure_ascii=False)
            sys.stdout.write("\n")
            sys.stdout.flush()

    results = wait_prompts(cfg, ids, workspace=args.workspace,
                           timeout=args.timeout, interval=args.interval,
                           on_settled=on_settled)
    timed_out = [pid for pid in ids if results.get(pid) is None]
    summary = {
        "total": len(ids),
        "succeeded": counts["done"],
        "failed": counts["failed"],
        "timed_out": timed_out,
    }
    with out_lock:
        json.dump(summary, sys.stdout, ensure_ascii=False)
        sys.stdout.write("\n")
        sys.stdout.flush()
    if timed_out:
        sys.exit(1)


# --------------------------------------------------------------------------
# commands — generate (image) / video
# --------------------------------------------------------------------------
def parse_reference_specs(values):
    specs = []
    for raw in values or []:
        if "=" not in raw:
            die("invalid --reference value: use NAME=PATH_OR_URL, e.g. --reference woman=./model.jpg")
        name, image = raw.split("=", 1)
        name = name.strip()
        image = image.strip()
        if not name or not image:
            die("invalid --reference value: both NAME and PATH_OR_URL are required")
        specs.append((name, image))
    return specs


def reference_image_field(value, resolved):
    if remote_url(value):
        return field("tune[image_urls][]", value)
    return field("tune[images][]", resolved)


def reference_title(name, image):
    parsed = urlparse(str(image))
    label = Path(parsed.path).stem if parsed.scheme else Path(image).stem
    return label or name


def create_reference_mentions(args, cfg, tune_id, reference_specs, resolved_images):
    mentions = []
    for (name, image), resolved in zip(reference_specs, resolved_images):
        values = {"title": reference_title(name, image), "name": name, "model_type": "faceid",
                  "model_id": tune_id, "image_url": [image] if remote_url(image) else [],
                  "image": [] if remote_url(image) else [resolved]}
        definition = API_OPERATIONS["create_reference"]
        tune = request(cfg, definition["method"], definition["path"],
                       form=operation_fields("create_reference", values), workspace=args.workspace)
        mentions.append(f"<faceid:{tune['id']}:1> {tune['name']}")
    return mentions

def prepend_reference_mentions(text, mentions):
    if text is None:
        return text
    missing = [mention for mention in mentions if mention.split(" ", 1)[0] not in text]
    return f"{' '.join(missing)} {text}".strip() if missing else text


def _generate(args, cfg, video):
    name = "generate_video" if video else "generate_images"
    definition = API_OPERATIONS[name]
    reference_specs = parse_reference_specs(getattr(args, "references", None))
    tune_id = resolve_model(cfg, args.model)
    image_references = args.image_references or [] if video else []
    if len({"url" if remote_url(value) else "file" for value in image_references}) > 1:
        die("--image-reference cannot mix URLs and local files in one request")
    reference_images = [image for _, image in reference_specs]
    # Contract field order preserves the existing single-batch upload order.
    media_inputs = []
    resolved = {spec[1]: [] for spec in definition["fields"] if spec[2] == "media_array"}
    for spec in definition["fields"]:
        if spec[2] not in ("media", "media_array"):
            continue
        value = getattr(args, spec[1], None)
        values = [value] if spec[2] == "media" else value or []
        media_inputs.extend((spec[1], item) for item in values if item)
    resolved_media = resolve_media_values(cfg, reference_images + [value for _, value in media_inputs])
    for (argument, _value), uploaded in zip(media_inputs, resolved_media[len(reference_images):]):
        if argument in resolved and isinstance(resolved[argument], list):
            resolved[argument].append(uploaded)
        else:
            resolved[argument] = uploaded
    reference_mentions = create_reference_mentions(args, cfg, tune_id, reference_specs, resolved_media[:len(reference_images)])
    values = vars(args).copy()
    apply_catalog_defaults(cfg, definition, values)
    values["model_id"] = tune_id
    for text_argument in definition["references"]["texts"]:
        values[text_argument] = prepend_reference_mentions(getattr(args, text_argument), reference_mentions)
    # Video omits num_images unless given; Astria renders one first frame.
    if "image_count" in definition:
        counts = definition["image_count"]
        values["num_images"] = resolve_num_images(cfg, args.num_images,
            counts["edit"] if values.get(counts["input"]) else counts["generate"])
    # Both generate_audio and video_audio remain in the shared definition,
    # preserving the existing audio compatibility patch.
    prompt = request(cfg, definition["method"], operation_path(definition, values),
                     form=operation_fields(name, values, resolved), workspace=args.workspace)
    prompt = operation_result(definition, prompt, values)
    if args.wait:
        prompt = poll_prompt(cfg, tune_id, prompt["id"], workspace=args.workspace)
    emit(prompt)

def cmd_generate(args, cfg):
    if getattr(args, "video_prompt", None):
        die("--video-prompt belongs to `astria video`, not `astria generate`. Use `astria video --video-prompt ...` for video generation.")
    if not args.text:
        die("--text is required for `astria generate`. For video generation without a first-frame prompt, use `astria video --video-prompt ...`.")
    _generate(args, cfg, video=False)


def cmd_video(args, cfg):
    if getattr(args, "input_image", None):
        die("--input-image is for image generation/editing. For video, use --first-frame, --last-frame, --video-reference, --image-reference, or --reference NAME=PATH_OR_URL.")
    _generate(args, cfg, video=True)


def cmd_music(args, cfg):
    if args.audio_reference:
        args.audio_reference = resolve_media_values(cfg, [args.audio_reference])[0]
    prompt = execute_api_operation("generate_music", args, cfg)
    if args.wait:
        prompt = poll_prompt(cfg, prompt["tune_id"], prompt["id"], workspace=args.workspace)
    emit(prompt)


VARIATE_VIDEO_MODEL = "seedance25_draft"


def parse_variate_reference_specs(values):
    specs = []
    for raw in values or []:
        name = None
        source = raw.strip()
        if "=" in source:
            candidate, separator, remainder = source.partition("=")
            if (separator and candidate.strip() and remainder.strip()
                    and not remote_url(candidate.strip())
                    and "/" not in candidate and "\\" not in candidate):
                name = candidate.strip()
                source = remainder.strip()
        if not source:
            die("invalid --reference value: PATH_OR_URL cannot be empty")
        specs.append({"name": name, "source": source})
    return specs


def variate_reference_title(name, source, class_info):
    parsed = urlparse(str(source))
    filename = Path(parsed.path).name if parsed.scheme else Path(source).name
    stem = Path(filename).stem
    return (class_info.get("first_name") or class_info.get("short_description")
            or stem or name or class_info.get("class_name") or "image")


def create_variate_reference(args, cfg, default_tune_id, spec, upload_record):
    source = spec["source"]
    class_info = {}
    if not spec["name"]:
        class_info = execute_api_operation("classify_image", argparse.Namespace(
            source=source if remote_url(source) else upload_record["public_url"],
            class_name=None, workspace=args.workspace), cfg)
    name = spec["name"] or class_info.get("class_name") or "image"
    characteristics = {
        key: value
        for key, value in class_info.items()
        if key not in ("class_name", "captions")
    }
    form = [
        field("tune[title]", variate_reference_title(name, source, class_info)),
        field("tune[name]", name),
    ]
    if characteristics.get("short_description"):
        form.append(field("tune[characteristics]", json.dumps(characteristics)))
    form += [
        field("tune[model_type]", "faceid"),
        field("tune[base_tune_id]", default_tune_id),
        reference_image_field(source, source if remote_url(source) else upload_record["signed_id"]),
        field("tune[image_captions][]", class_info.get("caption", "")),
    ]
    tune = request(cfg, "POST", "/tunes", form=form, workspace=args.workspace)
    return {
        "id": tune["id"],
        "name": tune["name"],
        "title": tune.get("title") or variate_reference_title(name, source, class_info),
        "source": source,
        "created": True,
    }


def compose_variate_video_prompt(args, cfg, references):
    result = execute_api_operation("compose_video_edit", argparse.Namespace(
        brief=args.brief, tune_id=[str(reference["id"]) for reference in references], workspace=args.workspace), cfg)
    return result["video_prompt"]


INSPECT_TIMEOUT_SEC = 240
INSPECT_INTERVAL_SEC = 2


def inspect_video(cfg, payload, workspace=None):
    """POST /videos/inspect only enqueues the inspection (download, ffmpeg and
    Gemini run on Astria's worker); poll GET /videos/inspect/<id> until it
    settles. Servers that still answer synchronously return `description`
    straight away and skip the loop."""
    record = request(cfg, "POST", "/videos/inspect", json_body=payload,
                     workspace=workspace, timeout=125)
    if not isinstance(record, dict):
        raise AstriaError("unexpected response from POST /videos/inspect")
    deadline = time.monotonic() + INSPECT_TIMEOUT_SEC
    while record.get("status") in ("pending", "processing"):
        if time.monotonic() > deadline:
            raise AstriaError(f"video inspection {record.get('id')} did not finish within {INSPECT_TIMEOUT_SEC}s")
        time.sleep(INSPECT_INTERVAL_SEC)
        record = request(cfg, "GET", f"/videos/inspect/{record['id']}",
                         workspace=workspace, timeout=30)
        if not isinstance(record, dict):
            raise AstriaError("unexpected response from GET /videos/inspect")
    if record.get("status") == "failed":
        raise AstriaError(f"video inspection failed: {record.get('error') or 'unknown error'}")
    if not str(record.get("description") or "").strip():
        raise AstriaError("video inspection returned no description")
    return record


def cmd_variate(args, cfg):
    if remote_url(args.source) and not args.source.startswith("https://"):
        die("video URL must use HTTPS")

    reference_specs = parse_variate_reference_specs(args.references)
    existing_ids = []
    for value in args.tune_ids or []:
        if not str(value).isdigit():
            die(f"invalid tune id: {value}")
        tune_id = int(value)
        if tune_id not in existing_ids:
            existing_ids.append(tune_id)
    if not args.brief.strip() and not reference_specs and not existing_ids:
        die("provide --brief, --reference, or --tune-id")

    catalog = model_catalog(cfg)
    video_models = catalog.get("video_models")
    if video_models is not None and VARIATE_VIDEO_MODEL not in video_models:
        die(f"{VARIATE_VIDEO_MODEL} is not available for this account")
    default_tune_id = resolve_model(cfg, None)

    local_values = ([] if remote_url(args.source) else [args.source]) + [
        spec["source"] for spec in reference_specs if not remote_url(spec["source"])
    ]
    upload_records = iter(direct_upload_records(cfg, local_values))
    source_record = None if remote_url(args.source) else next(upload_records)
    reference_uploads = [
        None if remote_url(spec["source"]) else next(upload_records)
        for spec in reference_specs
    ]
    references = [
        {"id": tune_id, "created": False}
        for tune_id in existing_ids
    ]
    references += [
        create_variate_reference(args, cfg, default_tune_id, spec, upload_record)
        for spec, upload_record in zip(reference_specs, reference_uploads)
    ]
    video_prompt = compose_variate_video_prompt(args, cfg, references)

    prompt_payload = {
        "text": "",
        "tune_id": int(default_tune_id),
        "video_model": VARIATE_VIDEO_MODEL,
        "video_prompt": video_prompt,
        "video_audio": True,
        "input_video_url" if remote_url(args.source) else "input_video": (
            args.source if remote_url(args.source) else source_record["signed_id"]
        ),
    }
    if args.base_pack_id:
        prompt_payload["base_pack_id"] = args.base_pack_id
    if args.order_id:
        prompt_payload["order_id"] = args.order_id
    response = request(
        cfg,
        "POST",
        "/prompts",
        query=[("view", "board")],
        json_body={"prompt": prompt_payload},
        workspace=args.workspace,
    )
    prompt = response["prompt"]
    if args.wait:
        prompt = poll_prompt(cfg, default_tune_id, prompt["id"], workspace=args.workspace)
    emit({
        "references": references,
        "video_prompt": video_prompt,
        "prompt": prompt,
    })


def cmd_video_inspections_create(args, cfg):
    emit(execute_api_operation("inspect_video", args, cfg))


def cmd_video_inspections_get(args, cfg):
    emit(execute_api_operation("get_video_inspection", args, cfg))


def cmd_inspect_video(args, cfg):
    if str(args.source).startswith(("http://", "https://")):
        if not str(args.source).startswith("https://"):
            die("video URL must use HTTPS")
        payload = {"file_url": args.source}
    else:
        payload = {"blob_signed_id": direct_upload(cfg, args.source)}
    if args.tune_id:
        payload["tune_ids"] = [int(tune_id) for tune_id in args.tune_id]
    emit(inspect_video(cfg, payload, workspace=args.workspace))


def cmd_classify_image(args, cfg):
    source = args.source if remote_url(args.source) else direct_upload_records(cfg, [args.source])[0]["public_url"]
    emit(execute_api_operation("classify_image", argparse.Namespace(**{**vars(args), "source": source}), cfg))


def cmd_compose_video_edit(args, cfg):
    emit(execute_api_operation("compose_video_edit", args, cfg))


def cmd_inspect(args, cfg):
    if remote_url(args.source):
        if not args.source.startswith("https://"):
            die("image URL must use HTTPS")
        image_url = args.source
    else:
        image_url = direct_upload_records(cfg, [args.source])[0]["public_url"]

    definition = API_OPERATIONS["inspect_image"]
    result = request(
        cfg,
        definition["method"],
        definition["path"],
        form=operation_fields("inspect_image", {**vars(args), "source": image_url}),
        workspace=args.workspace,
        timeout=125,
    )
    if not isinstance(result, dict) or not str(result.get("description") or "").strip():
        raise AstriaError("image inspection returned no description")
    emit(result)


# --------------------------------------------------------------------------
# commands — packs / workspaces
# --------------------------------------------------------------------------
def cmd_packs_list(args, cfg):
    emit(execute_api_operation("list_templates", args, cfg))

def cmd_packs_get(args, cfg):
    emit(execute_api_operation("get_template", args, cfg))

def cmd_packs_text(args, cfg):
    text = execute_api_operation("get_template_text", args, cfg)
    sink = _operation_output.get()
    sink.append(text) if sink is not None else sys.stdout.write(text)

def cmd_packs_create(args, cfg):
    emit(execute_api_operation("create_template", args, cfg))


def cmd_packs_update(args, cfg):
    emit(execute_api_operation("update_template", args, cfg))

def prompt_attribute_overrides(args):
    """Collect the per-prompt override flags into a prompt_attributes dict, sent
    under tune[prompt_attributes][...]. Named flags cover the common knobs;
    --attr KEY=VALUE is the escape hatch for any other prompt attribute."""
    attrs = {}
    if args.num_images:
        attrs["num_images"] = args.num_images
    if args.aspect_ratio:
        attrs["aspect_ratio"] = args.aspect_ratio
    if args.resolution:
        attrs["resolution"] = args.resolution
    if args.inpaint_faces is not None:
        attrs["inpaint_faces"] = "true" if args.inpaint_faces else "false"
    for raw in (args.attr or []):
        if "=" not in raw:
            die(f"--attr must be KEY=VALUE (got {raw!r})")
        key, value = raw.split("=", 1)
        attrs[key.strip()] = value.strip()
    return attrs


def _id_list(value):
    return [int(v) for v in str(value).split(",") if v.strip()] if value else []


def cmd_packs_run(args, cfg):
    if not any((args.tune_id, args.title, args.name, args.image, args.image_url, args.tune_replacements)):
        die("nothing to run — pass --tune-id (existing tunes) or a training set (--title/--name/--image)")
    values = vars(args).copy()
    values["image"] = direct_uploads(cfg, args.image or [])
    # Both --attr and structured MCP overrides use the same field encoder.
    values["prompt_attributes"] = dict(args.prompt_attributes or {})
    for raw in args.attr or []:
        if "=" not in raw:
            die(f"--attr must be KEY=VALUE (got {raw!r})")
        key, value = raw.split("=", 1)
        values["prompt_attributes"][key.strip()] = value.strip()
    emit(execute_api_operation("run_template", argparse.Namespace(**values), cfg))

def cmd_workspaces_list(args, cfg):
    emit(execute_api_operation("list_workspaces", args, cfg))

def cmd_workspaces_create(args, cfg):
    emit(execute_api_operation("create_workspace", args, cfg))


def cmd_workspaces_get(args, cfg):
    emit(execute_api_operation("get_workspace", args, cfg))


def cmd_workspaces_attach_images(args, cfg):
    emit(execute_api_operation("attach_workspace_images", args, cfg))


def cmd_workspaces_update(args, cfg):
    emit(execute_api_operation("update_workspace", args, cfg))


# --------------------------------------------------------------------------
# commands — external agent handoff
# --------------------------------------------------------------------------
HANDOFF_MAX_MARKDOWN_BYTES = 256 * 1024
HANDOFF_MAX_FILE_BYTES = 10 * 1024 * 1024
HANDOFF_MAX_TOTAL_BYTES = 25 * 1024 * 1024
HANDOFF_MAX_FILES = 50
HANDOFF_SECRET_NAMES = {
    ".env", ".git", ".ssh", ".aws", "credentials.json", "id_rsa", "id_ed25519",
}


def handoff_source():
    client = (_client_token() or "").lower()
    if "claude" in client:
        return "claude-code"
    if "chatgpt" in client or "codex" in client:
        return "chatgpt"
    if os.environ.get("CODEX_HOME"):
        return "chatgpt"
    if "cursor" in client:
        return "cursor"
    return "other"


def handoff_sha256(path):
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def safe_bundle_segment(value):
    cleaned = re.sub(r"[^A-Za-z0-9._ -]", "_", value).strip(" .")
    return cleaned or "file"


def validate_handoff_source(path):
    if path.is_symlink():
        die(f"handoff paths may not be symlinks: {path}")
    lowered = {part.lower() for part in path.parts}
    if lowered & HANDOFF_SECRET_NAMES or any(part.startswith(".env.") for part in lowered):
        die(f"refusing to upload likely credential material: {path}")


def collect_handoff_path(value, bundle_root, kind, require_skill=False):
    root = Path(value).expanduser()
    if not root.exists():
        die(f"handoff path not found: {value}")
    validate_handoff_source(root)
    if require_skill and (not root.is_dir() or not (root / "SKILL.md").is_file()):
        die(f"skill directory must contain SKILL.md: {value}")

    paths = [root] if root.is_file() else sorted(path for path in root.rglob("*") if path.is_file())
    records = []
    for path in paths:
        validate_handoff_source(path)
        relative = Path(path.name) if root.is_file() else path.relative_to(root)
        destination = Path(bundle_root)
        if root.is_dir():
            destination /= safe_bundle_segment(root.name)
        destination /= Path(*(safe_bundle_segment(part) for part in relative.parts))
        records.append({
            "local_path": path,
            "path": destination.as_posix(),
            "kind": kind,
        })
    return records


def cmd_agent_handoff(args, cfg):
    workspace = resolve_workspace(cfg, args.workspace)
    if not workspace or workspace == "all":
        die("a workspace is required — pass --workspace or set WORKSPACE_ID")

    handoff_path = Path(args.handoff).expanduser()
    if not handoff_path.is_file():
        die(f"handoff file not found: {args.handoff}")
    validate_handoff_source(handoff_path)
    handoff_bytes = handoff_path.read_bytes()
    if len(handoff_bytes) > HANDOFF_MAX_MARKDOWN_BYTES:
        die("handoff markdown must be at most 256 KB")
    try:
        handoff_markdown = handoff_bytes.decode("utf-8")
    except UnicodeDecodeError:
        die("handoff markdown must be UTF-8 text")

    records = [
        record
        for value in (args.attach or [])
        for record in collect_handoff_path(value, "files", "attachment")
    ] + [
        record
        for value in (args.skill or [])
        for record in collect_handoff_path(value, "skills", "skill", require_skill=True)
    ]
    if len(records) > HANDOFF_MAX_FILES:
        die(f"a handoff may contain at most {HANDOFF_MAX_FILES} files")
    if len({record["path"] for record in records}) != len(records):
        die("two handoff files resolve to the same bundle path")
    for record in records:
        if record["local_path"].stat().st_size > HANDOFF_MAX_FILE_BYTES:
            die(f"handoff file must be at most 10 MB: {record['local_path']}")
    if sum(record["local_path"].stat().st_size for record in records) > HANDOFF_MAX_TOTAL_BYTES:
        die("handoff files must total at most 25 MB")

    uploads = direct_upload_handoff_records(cfg, [record["local_path"] for record in records])
    files = [{
        "path": record["path"],
        "kind": record["kind"],
        "signed_id": upload["signed_id"],
        "sha256": handoff_sha256(record["local_path"]),
        "executable": os.access(record["local_path"], os.X_OK),
    } for record, upload in zip(records, uploads)]
    result = request(cfg, "POST", "/api/agent_handoffs", json_body={"agent_handoff": {
        "workspace_id": workspace,
        "source": args.source or handoff_source(),
        "title": args.title or handoff_path.stem.replace("_", " ").replace("-", " ").title() or "Agent handoff",
        "handoff_markdown": handoff_markdown,
        "files": files,
    }}, workspace=workspace)
    emit(result)
    if args.open:
        webbrowser.open(result["deep_link"])


def cmd_agent_start(args, cfg):
    args.workspace = resolve_workspace(cfg, args.workspace)
    if not args.workspace or args.workspace == "all":
        die("a workspace is required — pass --workspace or set WORKSPACE_ID")
    emit(execute_api_operation("start_agent_run", args, cfg))


def cmd_agent_get(args, cfg):
    emit(execute_api_operation("get_agent_run", args, cfg))


def cmd_agent_reply(args, cfg):
    emit(execute_api_operation("reply_agent_run", args, cfg))


def cmd_agent_cancel(args, cfg):
    emit(execute_api_operation("cancel_agent_run", args, cfg))


# --------------------------------------------------------------------------
# commands — workspace landing page
# --------------------------------------------------------------------------
def cmd_landing_get(args, cfg):
    ws = resolve_workspace(cfg, args.workspace)
    if not ws:
        die("a workspace is required — pass --workspace or set WORKSPACE_ID")
    workspace = request(cfg, "GET", f"/workspaces/{ws}.json", workspace=ws)
    if args.html:
        sys.stdout.write((workspace.get("landing_page_html") or "") + "\n")
    else:
        emit(workspace)


def cmd_landing_set(args, cfg):
    ws = resolve_workspace(cfg, args.workspace)
    if not ws:
        die("a workspace is required — pass --workspace or set WORKSPACE_ID")
    # Send as a JSON body, not a multipart field. A multipart `@file` part is
    # parsed server-side as an ActionDispatch::Http::UploadedFile, and assigning
    # that to the string column stores its literal inspect string instead of the
    # HTML. JSON keeps landing_page_html unambiguously a string.
    if args.brief:
        workspace = {"brief": args.brief}
    else:
        if not Path(args.html_file).is_file():
            die(f"file not found: {args.html_file}")
        workspace = {"landing_page_html": Path(args.html_file).read_text(encoding="utf-8")}
    emit(request(cfg, "PATCH", f"/workspaces/{ws}.json",
                 json_body={"workspace": workspace}, workspace=ws))


# --------------------------------------------------------------------------
# commands — cache (local snapshot of tunes/prompts/packs/user)
# --------------------------------------------------------------------------
CACHE_FIELDS = {
    "tunes": ("id", "title", "name", "orig_images"),
    "prompts": ("id", "text", "num_images", "images", "aspect_ratio", "resolution", "input_image", "input_video", "order_id"),
    "packs": ("id", "title", "slug", "main_class_name", "multiplier", "multiplier_api"),
    "user": ("usd_balance_mc", "email", "name", "purchased_plugin_at"),
}
CACHE_MAX_AGE = 86400


def cache_dir(cfg, override):
    ws = resolve_workspace(cfg, override) or "personal"
    slug = "".join(c if c.isalnum() or c in "_.-" else "_" for c in ws)
    root = Path(os.environ.get("ASTRIA_CACHE_DIR") or (Path.cwd() / ".cache"))
    return root / f"ws_{slug}"


# Indexed columns mirrored from the full record into the SQLite store. Each
# table also gets a `json` TEXT column holding the complete record. These are
# the columns `astria cache get/find/uses` query against — no API calls.
DB_COLUMNS = {
    "tunes": ("id", "name", "title"),
    "prompts": ("id", "text", "pack_id", "tune_id", "order_id", "num_images", "aspect_ratio", "resolution"),
    "packs": ("id", "title", "slug", "main_class_name"),
}
CACHE_DB_NAME = "cache.db"


def cache_fetch(cfg, resource, workspace, out_dir):
    """Fetch one resource, write its `<resource>.json` snapshot, and return the
    raw API data so the caller can also load it into the SQLite store."""
    endpoint = "/users" if resource == "user" else f"/{resource}"
    data = request(cfg, "GET", endpoint, workspace=workspace, no_workspace=(workspace is None))
    fields = CACHE_FIELDS[resource]
    if isinstance(data, list):
        shaped = [{k: row.get(k) for k in fields} for row in data]
    else:
        shaped = {k: data.get(k) for k in fields}
    (out_dir / f"{resource}.json").write_text(json.dumps(shaped, ensure_ascii=False, indent=2))
    return data


def cache_db_path(cfg, override):
    return cache_dir(cfg, override) / CACHE_DB_NAME


def open_cache_db(cfg, override, *, require=False):
    """Open the local cache SQLite DB. With require=True, die() if it is missing
    so query commands point the user at `astria cache refresh`."""
    path = cache_db_path(cfg, override)
    if require and not path.is_file():
        die(f"no local cache at {path} — run `astria cache refresh` first")
    conn = sqlite3.connect(path)
    conn.row_factory = sqlite3.Row
    return conn


def db_init_schema(conn):
    """(Re)create the tunes/prompts/packs tables and their indexes."""
    for table, columns in DB_COLUMNS.items():
        conn.execute(f"DROP TABLE IF EXISTS {table}")
        cols = ", ".join(f"{c} INTEGER PRIMARY KEY" if c == "id" else f"{c} TEXT" for c in columns)
        conn.execute(f"CREATE TABLE {table} ({cols}, json TEXT NOT NULL)")
        for col in columns:
            if col != "id":
                conn.execute(f"CREATE INDEX idx_{table}_{col} ON {table} ({col})")


def db_load_resource(conn, resource, data):
    """Replace one table's rows from raw API data (a list of records)."""
    columns = DB_COLUMNS[resource]
    conn.execute(f"DELETE FROM {resource}")
    rows = data if isinstance(data, list) else [data]
    placeholders = ", ".join(["?"] * (len(columns) + 1))
    conn.executemany(
        f"INSERT OR REPLACE INTO {resource} ({', '.join(columns)}, json) VALUES ({placeholders})",
        [tuple(row.get(c) for c in columns) + (json.dumps(row, ensure_ascii=False),) for row in rows],
    )


def cmd_cache(args, cfg):
    if args.action == "path":
        print(cache_dir(cfg, args.workspace))
        return
    if args.action == "get":
        cmd_cache_get(args, cfg)
        return
    if args.action == "find":
        cmd_cache_find(args, cfg)
        return
    if args.action == "uses":
        cmd_cache_uses(args, cfg)
        return
    if args.action == "stats":
        cmd_cache_stats(args, cfg)
        return

    # action == "refresh"
    workspace = resolve_workspace(cfg, args.workspace)
    out_dir = cache_dir(cfg, args.workspace)
    out_dir.mkdir(parents=True, exist_ok=True)
    stamp = out_dir / "_refreshed_at"

    if args.resource:
        data = cache_fetch(cfg, args.resource, workspace, out_dir)
        if args.resource in DB_COLUMNS:
            conn = open_cache_db(cfg, args.workspace)
            conn.execute(f"CREATE TABLE IF NOT EXISTS {args.resource} "
                         f"({', '.join(DB_COLUMNS[args.resource])}, json TEXT NOT NULL)")
            db_load_resource(conn, args.resource, data)
            conn.commit()
            conn.close()
        stamp.write_text(str(int(time.time())))
        print(f"refreshed {args.resource} → {out_dir}")
        return

    if not args.force and stamp.is_file():
        age = time.time() - int(stamp.read_text() or 0)
        if age < CACHE_MAX_AGE:
            print(f"cache fresh ({int(age)}s old) — {out_dir}")
            return

    errors = []
    fetched = {}

    def worker(resource):
        try:
            fetched[resource] = cache_fetch(cfg, resource, workspace, out_dir)
        except AstriaError as exc:
            errors.append(str(exc))

    threads = [threading.Thread(target=worker, args=(r,)) for r in CACHE_FIELDS]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    if errors:
        die("; ".join(errors))

    conn = open_cache_db(cfg, args.workspace)
    db_init_schema(conn)
    for resource in DB_COLUMNS:
        db_load_resource(conn, resource, fetched[resource])
    conn.commit()
    conn.close()

    stamp.write_text(str(int(time.time())))
    print(f"refreshed tunes, prompts, packs, user → {out_dir}")


def cmd_cache_get(args, cfg):
    conn = open_cache_db(cfg, args.workspace, require=True)
    row = conn.execute(f"SELECT json FROM {args.table} WHERE id = ?", (args.id,)).fetchone()
    conn.close()
    if row is None:
        die(f"no {args.table} record with id {args.id} in the local cache")
    emit(json.loads(row["json"]))


def cmd_cache_find(args, cfg):
    conn = open_cache_db(cfg, args.workspace, require=True)
    # filter -> (column, mode): 'eq' for exact match, 'like' for substring
    filters = {
        "tunes": {"name": ("name", "like"), "title": ("title", "like")},
        "prompts": {"pack_id": ("pack_id", "eq"), "tune_id": ("tune_id", "eq"), "order_id": ("order_id", "eq"),
                    "text": ("text", "like")},
        "packs": {"main_class": ("main_class_name", "like"), "title": ("title", "like")},
    }[args.table]
    clauses, params = [], []
    for arg_name, (column, mode) in filters.items():
        value = getattr(args, arg_name, None)
        if value is None:
            continue
        if mode == "like":
            clauses.append(f"{column} LIKE ?")
            params.append(f"%{value}%")
        else:
            clauses.append(f"{column} = ?")
            params.append(value)
    where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
    rows = conn.execute(f"SELECT json FROM {args.table}{where} ORDER BY id DESC", params).fetchall()
    conn.close()
    emit([json.loads(r["json"]) for r in rows])


# Tunes are referenced inside prompt text via tokens like <faceid:1234:1> or
# <lora:1234:0.8> — the id is the first colon-separated field after the type.
TUNE_TOKEN_RE = re.compile(r"<[a-z0-9_]+:(\d+):[^>]*>", re.IGNORECASE)


def cmd_cache_uses(args, cfg):
    conn = open_cache_db(cfg, args.workspace, require=True)
    rows = conn.execute("SELECT json FROM prompts WHERE text LIKE ?",
                        (f"%{args.tune_id}%",)).fetchall()
    conn.close()
    target = str(args.tune_id)
    matches = [
        json.loads(r["json"]) for r in rows
        if target in TUNE_TOKEN_RE.findall(json.loads(r["json"]).get("text") or "")
    ]
    emit(matches)


def cmd_cache_stats(args, cfg):
    path = cache_db_path(cfg, args.workspace)
    if not path.is_file():
        die(f"no local cache at {path} — run `astria cache refresh` first")
    conn = open_cache_db(cfg, args.workspace, require=True)
    counts = {t: conn.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0] for t in DB_COLUMNS}
    conn.close()
    stamp = cache_dir(cfg, args.workspace) / "_refreshed_at"
    age = int(time.time() - int(stamp.read_text() or 0)) if stamp.is_file() else None
    emit({
        "db_path": str(path),
        "counts": counts,
        "refreshed_age_seconds": age,
        "stale": age is None or age > CACHE_MAX_AGE,
    })


# --------------------------------------------------------------------------
# commands — download prompt images
# --------------------------------------------------------------------------
# Asset extensions we recognise from a URL path; anything else falls back to .jpg.
DOWNLOAD_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".mp4", ".webm", ".mov"}
DOWNLOAD_WORKERS = 6


def asset_ext(url):
    """Derive a file extension from an asset URL's path, defaulting to .jpg."""
    path = url.split("?", 1)[0].split("#", 1)[0]
    ext = os.path.splitext(path)[1].lower()
    return ext if ext in DOWNLOAD_EXTS else ".jpg"


def collect_prompt_ids(args):
    """Gather prompt ids from positional args, --prompts-file and stdin.
    Deduped, original order preserved."""
    raw = list(args.ids or [])
    if args.prompts_file:
        if not Path(args.prompts_file).is_file():
            die(f"file not found: {args.prompts_file}")
        raw += Path(args.prompts_file).read_text().split()
    if not raw and not sys.stdin.isatty():
        raw += sys.stdin.read().split()
    seen, ids = set(), []
    for token in raw:
        token = token.strip()
        if token and token not in seen:
            seen.add(token)
            ids.append(token)
    return ids


def download_asset(url, dest):
    """Fetch one asset URL to dest with curl. Raises AstriaError on failure."""
    argv = ["curl", "-sSL", "--fail", "--max-time", "120", "-A", USER_AGENT, "-o", str(dest), url]
    try:
        proc = subprocess.run(argv, capture_output=True)
    except FileNotFoundError:
        die("`curl` not found on PATH — install curl")
    if proc.returncode != 0:
        raise AstriaError(proc.stderr.decode("utf-8", "replace").strip() or f"curl exit {proc.returncode}")


def cmd_download(args, cfg):
    ids = collect_prompt_ids(args)
    if not ids:
        die("no prompt ids — pass them as arguments, via --prompts-file, or on stdin")

    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)

    results = {}

    def worker(prompt_id):
        entry = {"id": prompt_id, "images": 0, "saved": []}
        try:
            prompt = request(cfg, "GET", f"/prompts/{prompt_id}.json", workspace=args.workspace)
        except AstriaError as exc:
            entry["error"] = str(exc)
            results[prompt_id] = entry
            return
        urls = (prompt or {}).get("images") or []
        entry["images"] = len(urls)
        if not urls:
            entry["error"] = "no images yet"
            results[prompt_id] = entry
            return
        width = max(2, len(str(len(urls))))
        for idx, url in enumerate(urls):
            dest = out_dir / f"prompt-{prompt_id}-{idx:0{width}d}{asset_ext(url)}"
            try:
                download_asset(url, dest)
                entry["saved"].append(str(dest))
            except AstriaError as exc:
                entry.setdefault("errors", []).append(f"{url}: {exc}")
        if "errors" in entry and not entry["saved"]:
            entry["error"] = "; ".join(entry.pop("errors"))
        results[prompt_id] = entry

    pending = list(ids)
    lock = threading.Lock()

    def pump():
        while True:
            with lock:
                if not pending:
                    return
                prompt_id = pending.pop(0)
            worker(prompt_id)

    threads = [threading.Thread(target=pump) for _ in range(min(DOWNLOAD_WORKERS, len(ids)))]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

    prompts = [results[pid] for pid in ids]
    emit({
        "out": str(out_dir),
        "prompts": prompts,
        "totals": {
            "prompts": len(prompts),
            "downloaded": sum(len(p["saved"]) for p in prompts),
            "failed": sum(1 for p in prompts if p.get("error")),
        },
    })


# --------------------------------------------------------------------------
# commands — raw API escape hatch
# --------------------------------------------------------------------------
def cmd_api(args, cfg):
    form = [tuple(item.split("=", 1)) for item in args.form or [] if "=" in item]
    uploaded = iter(direct_uploads(cfg, [value[1:] for _, value in form if value.startswith("@")]))
    form = [(key, next(uploaded) if value.startswith("@") else value) for key, value in form]
    query = [tuple(item.split("=", 1)) for item in args.query or [] if "=" in item]
    json_body = json.loads(args.data) if args.data else None
    result = request(cfg, args.method.upper(), args.path, query=query, form=form, json_body=json_body,
                     workspace=args.workspace)
    emit(result) if not isinstance(result, str) else sys.stdout.write(result + "\n")


# --------------------------------------------------------------------------
# hidden — SessionStart hook
# --------------------------------------------------------------------------
def cmd_session_hook(args, cfg):
    # Best-effort: keep the /cli/models id cache warm (daily refresh).
    record = load_models_cache()
    try:
        if models_cache_stale(record, cfg):
            record = fetch_models(cfg) or record
    except Exception:
        pass
    authed = bool(os.environ.get("ASTRIA_API_KEY") or os.environ.get("ASTRIA_AUTH_TOKEN") or cfg.get("api_key"))
    out = {"hookSpecificOutput": {"hookEventName": "SessionStart"}}
    context = []
    if not authed:
        context.append(
            "The Astria plugin is installed but not authenticated. If the user asks to do "
            "anything with Astria (generate images, manage tunes/packs), tell them to run "
            f"`astria login` first (API key at {login_hint(cfg)})."
        )
    skills_context = skills_upgrade_context(record)
    if skills_context:
        context.append(skills_context)
    if context:
        out["hookSpecificOutput"]["additionalContext"] = "\n\n".join(context)
    emit(out)


# --------------------------------------------------------------------------
# argument parser
# --------------------------------------------------------------------------
# --help enum text is built from the cached /cli/models record so usage
# strings track the live catalog — never hardcode model names or resolutions.
def image_model_help(rec, prefix="model name or tune id"):
    models = rec.get("models") or {}
    if not models:
        return f"{prefix}; see 'astria models --type image', omit for the platform default"
    names = ", ".join(
        f"{name} (default)" if meta.get("default") or name == rec.get("default") else name
        for name, meta in models.items())
    return f"{prefix} — {names}; omit for the default"


def music_model_help(rec):
    models = rec.get("music_models") or {}
    if not models:
        return "music model name or tune id; see 'astria models --type music', omit for the default"
    names = ", ".join(f"{name} (default)" if name == rec.get("default_music_model") else name for name in models)
    return f"music model name or tune id — {names}; omit for the default"


def lyrics_help(rec):
    base = ("song lyrics, using the model's section tags such as [Verse] and [Chorus]; "
            "omit to let the model write them")
    limits = [f"{name}: {meta['lyrics_length']['min']}-{meta['lyrics_length']['max']} chars"
              for name, meta in (rec.get("music_models") or {}).items()]
    return f"{base} — {'; '.join(limits)}" if limits else f"{base}; see 'astria models --type music' for lengths and tags"


def resolution_help(rec, noun="output resolution"):
    res = sorted({r for meta in (rec.get("models") or {}).values()
                  for r in (meta.get("resolutions") or [])})
    if not res:
        return f"{noun}; see 'astria models --type image' for per-model supported values"
    return (f"{noun}, model-dependent — " + ", ".join(res)
            + "; see 'astria models --type image' for each model's set")


def video_model_help(rec):
    families = rec.get("video_model_families") or {}
    if not families:
        return ("video model family, e.g. seedance25 (pick its resolution with --video-resolution); "
                "see 'astria models --type video' for the list, omit for the catalog default")
    return ("video model family (pick its resolution with --video-resolution; variant ids such as "
            "seedance25_720p also work) — " + ", ".join(families)
            + f"; omit for {rec.get('default_video_model_family') or 'the catalog default'}")


def video_resolution_help(rec):
    families = rec.get("video_model_families") or {}
    listed = [f"{name}: {'/'.join(meta['resolutions'])}" for name, meta in families.items() if meta.get("resolutions")]
    base = "output resolution for --video-model, e.g. 720p; omit for the family default"
    return f"{base} — {'; '.join(listed)}" if listed else f"{base}; see 'astria models --type video' for each family's set"


def video_capability_help(rec, flag, base):
    models = [name for name, meta in (rec.get("video_model_families") or {}).items()
              if meta.get(flag)]
    if not models:
        return base
    return f"{base}; supported by {', '.join(models)}"


def build_parser(models_record=None):
    models_record = (load_models_cache() or {}) if models_record is None else models_record
    parser = argparse.ArgumentParser(prog="astria", description="Astria API command-line client.")
    parser.add_argument("--profile", metavar="NAME",
                        help="config profile to use (also ASTRIA_PROFILE env); default: 'default'")
    parser.add_argument("-v", "--version", action="version", version=f"astria {VERSION}")
    sub = parser.add_subparsers(dest="command", required=True)

    # shared --workspace for API commands
    ws_parent = argparse.ArgumentParser(add_help=False)
    ws_parent.add_argument("-w", "--workspace", help="workspace id, 'all', or 'personal'")

    # auth
    p = sub.add_parser("login", help="store an API key in ~/.astria/config.json")
    p.add_argument("--api-key", help="API key (else prompted / read from stdin)")
    p.add_argument("--base-url", help="override API base URL")
    p.add_argument("--workspace", help="default workspace id")
    p.set_defaults(func=cmd_login)

    sub.add_parser("logout", help="remove stored credentials").set_defaults(func=cmd_logout)
    sub.add_parser("whoami", parents=[ws_parent], help="show the authenticated account").set_defaults(func=cmd_whoami)

    p = sub.add_parser("config", help="show or change config")
    p.add_argument("action", nargs="?", choices=["get", "set"], help="get (default) or set")
    p.add_argument("key", nargs="?", help="config key for `set`")
    p.add_argument("value", nargs="?", help="config value for `set`")
    p.set_defaults(func=cmd_config)

    p = sub.add_parser("models", help="list available image, video and music models (name -> tune id)")
    p.add_argument("--refresh", action="store_true", help="force a refresh from the server")
    p.add_argument("--type", choices=list(API_OPERATIONS["list_models"]["result"]["sections"]["keys"]),
                   help="only the image, video or music catalog; omit for all three")
    p.set_defaults(func=cmd_models)

    p = sub.add_parser("upgrade", help="upgrade this astria executable in place")
    p.add_argument("--url", help=argparse.SUPPRESS)
    p.add_argument("--path", help=argparse.SUPPRESS)
    p.add_argument("--force", action="store_true", help="install even if the downloaded version is not newer")
    p.set_defaults(func=cmd_upgrade)

    # tunes
    tunes = sub.add_parser("tunes", help="references / fine-tuned models").add_subparsers(dest="sub", required=True)
    p = tunes.add_parser("list", parents=[ws_parent], help="List image reference sets and trained models accessible to your Astria account")
    p.add_argument("--title", help="filter by title / product name / SKU substring")
    p.add_argument("--name", action="append", help="filter by class name (repeatable)")
    p.add_argument("--model-type", help="filter by model_type (e.g. faceid)")
    p.add_argument("--branch", help="filter by branch (e.g. partner-1 to discover partner models)")
    p.add_argument("--creation-source", choices=["web", "mcp", "cli", "photoshop", "api"], help="filter by creation source")
    p.add_argument("--gallery", action="store_true", help="query the public gallery instead")
    p.add_argument("--archived", action="store_true", help="only archived tunes; omitted selects unarchived tunes")
    p.add_argument("--limit")
    p.add_argument("--offset")
    p.set_defaults(func=cmd_tunes_list)
    p = tunes.add_parser("get", parents=[ws_parent], help="Get an Astria image reference set or trained model by ID, including details and image URLs")
    p.add_argument("id")
    p.set_defaults(func=cmd_tunes_get)
    p = tunes.add_parser("create", parents=[ws_parent], help="create a tune / reference")
    p.add_argument("--title", required=True)
    p.add_argument("--name", required=True, help="subject class (man, woman, dress, shoes, pose, ...)")
    p.add_argument("--model", default=None, help=image_model_help(models_record, "base model for the reference"))
    p.add_argument("--model-type", default="faceid")
    p.add_argument("--description", help="short description (stored in characteristics.short_description)")
    p.add_argument("--text", help="injected text (stored in characteristics.text); an empty string clears it")
    p.add_argument("--image-url", action="append", help="training image URL (repeatable)")
    p.add_argument("--image", action="append", help="local training image file (repeatable)")
    p.add_argument("--image-caption", action="append",
                   help="view caption per training image, one per image in --image-url order (repeatable): front, back, "
                        "side, detail or logo; a close-up names its side, e.g. back detail. A generation asking for a "
                        "front or back view drops images whose caption names the other side")
    p.set_defaults(func=cmd_tunes_create)
    p = tunes.add_parser("update", parents=[ws_parent], help="update a tune")
    p.add_argument("id")
    p.add_argument("--title")
    p.add_argument("--name")
    p.add_argument("--description", help="short description (stored in characteristics.short_description); omitted preserves it")
    p.add_argument("--text", help="injected text (stored in characteristics.text); omitted preserves it, an empty string clears it")
    p.add_argument("--sources", type=structured_argument("sources"), help="catalog provenance as a JSON array of source records")
    p.set_defaults(func=cmd_tunes_update)
    p = tunes.add_parser("archive", parents=[ws_parent], help="archive a tune, hiding it from lists without deleting it")
    p.add_argument("id")
    p.add_argument("--unarchive", action="store_true", help="restore an archived tune instead")
    p.set_defaults(func=cmd_tunes_archive)

    # prompts
    prompts = sub.add_parser("prompts", help="image/video generation records").add_subparsers(dest="sub", required=True)
    p = prompts.add_parser("list", parents=[ws_parent], help="list prompts")
    for name, spec in PROMPT_FILTERS.items():
        options = {"help": spec["help"]}
        if "choices" in spec:
            options["choices"] = spec["choices"]
        if spec["mode"] == "flag":
            options["action"] = "store_true"
        elif spec["mode"] == "boolean":
            options.update(action=argparse.BooleanOptionalAction, default=None)
        elif spec["mode"] == "array":
            options["action"] = "append"
        p.add_argument("--" + name.replace("_", "-"), **options)
    p.add_argument("--expand", action="append", choices=["debug_images", "prompt.debug_images", "comments", "prompt.comments"],
                   help="expand a prompt field, e.g. debug_images (repeatable)")
    p.set_defaults(func=cmd_prompts_list)
    p = prompts.add_parser("get", parents=[ws_parent], help="get one prompt")
    p.add_argument("id")
    p.add_argument("--expand", action="append", choices=["debug_images", "prompt.debug_images", "comments", "prompt.comments"],
                   help="expand a prompt field, e.g. debug_images (repeatable)")
    p.set_defaults(func=cmd_prompts_get)
    p = prompts.add_parser("update", parents=[ws_parent], help="update a prompt (assign pack / move workspace)")
    p.add_argument("id")
    p.add_argument("--pack-id", help="assign as a pack template prompt; use null to clear")
    p.add_argument("--base-pack-id", help="bind as a pack one-off")
    p.add_argument("--workspace-id")
    p.set_defaults(func=cmd_prompts_update)
    p = prompts.add_parser("archive", parents=[ws_parent], help="archive a prompt, hiding it from lists without deleting it")
    p.add_argument("id")
    p.add_argument("--unarchive", action="store_true", help="restore an archived prompt instead")
    p.set_defaults(func=cmd_prompts_archive)
    p = prompts.add_parser("enhance", parents=[ws_parent], help="upscale a finished video or increase its frame rate, as a new paid prompt")
    p.add_argument("id", help="prompt ID of a finished video")
    p.add_argument("--video-upscale-model", choices=["seedvr2"], help="upscaler; pass this or --video-fps-model, not both")
    p.add_argument("--video-upscale-target-resolution", choices=["720p", "1080p", "2k", "4k"], help="target for --video-upscale-model; defaults to 1080p")
    p.add_argument("--video-fps-model", choices=["video_fps_increaser"], help="frame interpolation; pass this or --video-upscale-model, not both")
    p.set_defaults(func=cmd_prompts_enhance)
    p = prompts.add_parser("attach", parents=[ws_parent], help="add a local image or MP4 to a prompt's results, e.g. a muxed film onto its video prompt")
    p.add_argument("id")
    p.add_argument("file", nargs="?", help="PNG, JPEG, WebP or AVIF image, or MP4 video")
    p.add_argument("--blob-signed-id", help="signed upload ID from create_upload; upload the bytes before attaching")
    p.set_defaults(func=cmd_prompts_attach, replace=False, replace_blob_id=None)
    images = sub.add_parser("images", help="manage prompt result images and videos").add_subparsers(dest="images_cmd", required=True)
    p = images.add_parser("replace", parents=[ws_parent], help="replace the sole result of the same media type and retain its original in debug history")
    p.add_argument("id", help="prompt ID")
    p.add_argument("file", nargs="?", help="replacement image or MP4 video")
    p.add_argument("--blob-signed-id", help="signed upload ID from create_upload; upload the bytes before replacing")
    p.add_argument("--blob-id", dest="replace_blob_id", type=int, help="select a result when the prompt has multiple images or videos")
    p.set_defaults(func=cmd_prompts_attach, replace=True, blob_signed_id=None)
    p = prompts.add_parser("wait", parents=[ws_parent],
                           help="block until one or more prompts have images or a user_error")
    p.add_argument("ids", nargs="*", help="prompt ids (also accepted via --prompts-file or stdin)")
    p.add_argument("--prompts-file", help="file of prompt ids (one per line or whitespace-separated)")
    p.add_argument("--timeout", type=int, default=WAIT_TIMEOUT_SEC,
                   help=f"total wall-clock cap in seconds (default: {WAIT_TIMEOUT_SEC})")
    p.add_argument("--interval", type=int, default=WAIT_INTERVAL_SEC,
                   help=f"polling interval in seconds (default: {WAIT_INTERVAL_SEC}, min {WAIT_INTERVAL_MIN})")
    p.set_defaults(func=cmd_prompts_wait)

    # generate
    p = sub.add_parser(
        "generate", parents=[ws_parent], help="generate images",
        formatter_class=argparse.RawTextHelpFormatter,
        epilog=(
            "examples:\n"
            "  astria generate --model wan-2-7 --text \"plain white background\" \\\n"
            "    --reference \"dress=./dress.jpg\" --reference \"woman=./woman.jpg\" --num-images 1 --wait"
        ),
    )
    p.add_argument("--model", default=None, help=image_model_help(models_record))
    p.add_argument("--text", help="prompt text; embed references as <faceid:ID:1>")
    p.add_argument("--video-prompt", help=argparse.SUPPRESS)
    p.add_argument("--num-images", help="override config default_num_images; otherwise 2, or 1 with --input-image")
    p.add_argument("--seed", help="generation seed; also makes an otherwise-identical prompt distinct")
    p.add_argument("--film-grain", "--film_grain", action=argparse.BooleanOptionalAction, default=None,
                   help="enable film-grain post-processing as a separate prompt attribute; "
                        "--film_grain is an alias")
    p.add_argument("--aspect-ratio", default="3:4", help="e.g. 3:4, 1:1, 16:9 (default: %(default)s)")
    p.add_argument("--resolution", help=resolution_help(models_record))
    p.add_argument("--input-image", help="URL or local file to edit")
    p.add_argument("--inpaint-faces", action=argparse.BooleanOptionalAction, default=None,
                   help="enable or disable face inpainting; omit to use the model default")
    p.add_argument("--inpaint-preset", choices=("strong", "identity"),
                   help="face inpainting preset; enables face inpainting; cannot combine with inpaint_faces=false")
    p.add_argument("--background-color", help="target background hex color, e.g. #ffffff; overrides the text flag")
    p.add_argument("--create-crops", type=structured_argument("create_crops"), nargs="?", const=60,
                   help="top/bottom crop size as a percentage (1-100); bare CLI flag uses 60; 0 disables crops")
    p.add_argument("--lynx", action=argparse.BooleanOptionalAction, default=None,
                   help="enable or disable Lynx processing using reference image metadata; overrides the text flag")
    p.add_argument("--mask-image", help="URL or local file to use as an inpainting mask")
    p.add_argument("--reference", "--images", dest="references", action="append", metavar="NAME=PATH_OR_URL",
                   help="create and attach a reference; repeat for each NAME=PATH_OR_URL (--images is an alias)")
    p.add_argument("--pack-id", help="author the prompt as a pack template prompt")
    p.add_argument("--base-pack-id", help="bind as a pack one-off")
    p.add_argument("--wait", action="store_true", help="block until images are ready")
    p.add_argument("--skill-name", help="originating database skill name from get_skill; keep the main workflow name across helper skills; omit for unrelated generations")
    p.set_defaults(func=cmd_generate)

    # video
    p = sub.add_parser(
        "video", parents=[ws_parent], help="generate video",
        formatter_class=argparse.RawTextHelpFormatter,
        epilog=(
            "references use the same syntax as image prompts:\n"
            "  <faceid:TUNE_ID:1> TUNE_NAME\n"
            "The tune name must immediately follow its token. Put existing tune mentions in\n"
            "--video-prompt. --reference NAME=PATH_OR_URL creates a new reference and adds\n"
            "the correctly formatted mention to --text and --video-prompt automatically.\n\n"
            "examples:\n"
            "  # Existing reference tune\n"
            "  astria video --video-model seedance2_fast --video-resolution 720p \\\n"
            "    --video-prompt \"<faceid:1234:1> woman walks down a runway\" --duration 5 --wait\n\n"
            "  # Create and use references from local files or URLs\n"
            "  astria video --video-model seedance2_fast --video-resolution 480p \\\n"
            "    --video-prompt \"woman wearing dress, plain white background\" \\\n"
            "    --reference \"dress=./dress.jpg\" --reference \"woman=./woman.jpg\" \\\n"
            "    --num-images 1 --wait\n\n"
            "  # Attach ordered raw image references without creating tunes\n"
            "  astria video --video-model seedance2_fast --video-resolution 720p \\\n"
            "    --video-prompt \"transition through these looks in order\" \\\n"
            "    --image-reference ./look-1.jpg --image-reference ./look-2.jpg --wait"
        ),
    )
    p.add_argument("--model", default=None, help=image_model_help(models_record, "first-frame image model"))
    p.add_argument("--text", help="first-frame prompt text")
    p.add_argument("--video-model", help=video_model_help(models_record))
    p.add_argument("--video-resolution", help=video_resolution_help(models_record))
    p.add_argument("--video-prompt", required=True,
                   help="motion / action description; references use <faceid:TUNE_ID:1> TUNE_NAME")
    p.add_argument("--duration", help="seconds (model-dependent)")
    p.add_argument("--seed", help="generation seed; reuse a draft's seed to reproduce it at a higher resolution")
    p.add_argument("--aspect-ratio", help="e.g. 16:9, 9:16, 1:1 (model-dependent); omit to follow the model default and any frame or reference media")
    p.add_argument("--resolution", help=resolution_help(
        models_record, "first-frame image resolution (video resolution is set by --video-resolution)"))
    p.add_argument("--num-images", help="first-frame images; video prompts take 1, which Astria sets when omitted")
    p.add_argument("--input-image", help=argparse.SUPPRESS)
    p.add_argument("--reference", "--images", dest="references", action="append", metavar="NAME=PATH_OR_URL",
                   help="create and attach a reference; repeat for each NAME=PATH_OR_URL (--images is an alias)")
    p.add_argument("--image-reference", dest="image_references", action="append", metavar="PATH_OR_URL",
                   help=video_capability_help(
                       models_record, "supports_image_references",
                       "attach an ordered raw image reference; repeat for each image"))
    p.add_argument("--first-frame", help="URL or file overriding the rendered first frame")
    p.add_argument("--last-frame", help="URL or file for keyframe models")
    p.add_argument("--input-video", dest="video_references", action="append", help=argparse.SUPPRESS)
    p.add_argument("--video-reference", dest="video_references", action="append", metavar="PATH_OR_URL",
                   help="URL or file for a source or reference video; repeat for each, in the order the prompt names them "
                        "(@Video1, @Video2); list_models gives each model's max_reference_videos")
    p.add_argument("--audio-reference", dest="audio_references", action="append", metavar="PATH_OR_URL",
                   help=video_capability_help(
                       models_record, "supports_audio_reference",
                       "URL or file for a reference audio track; repeat for each, in the order the prompt names them "
                       "(@Audio1, @Audio2); list_models gives each model's max_reference_audios"))
    p.add_argument("--generate-audio", action=argparse.BooleanOptionalAction, default=None,
                   help=video_capability_help(
                       models_record, "generates_audio",
                       "generate a soundtrack (picks the audio version of families that price it separately); omit for silent"))
    p.add_argument("--wait", action="store_true")
    p.add_argument("--skill-name", help="originating database skill name from get_skill; keep the main workflow name across helper skills; omit for unrelated generations")
    p.add_argument("--order-id", help="associate the video with an accessible order")
    p.set_defaults(func=cmd_video)

    # music
    p = sub.add_parser(
        "music", parents=[ws_parent], help="generate a song",
        formatter_class=argparse.RawTextHelpFormatter,
        epilog=(
            "examples:\n"
            "  # Song with your own lyrics\n"
            "  astria music \"upbeat synth-pop, female vocals, 120 bpm\" \\\n"
            "    --lyrics \"[Verse]\\nCity lights are calling\\n[Chorus]\\nWe run all night\" --wait\n\n"
            "  # Let the model write the lyrics, or make an instrumental\n"
            "  astria music \"melancholic indie folk about leaving home\"\n"
            "  astria music \"lo-fi hip hop beat for studying\" --instrumental"
        ),
    )
    p.add_argument("text", help="song description: genre, mood, instruments, vocals and tempo")
    p.add_argument("--model", default=None, help=music_model_help(models_record))
    p.add_argument("--lyrics", help=lyrics_help(models_record))
    p.add_argument("--audio-reference", help="MiniMax Music Cover source: MP3 with vocals, 6 seconds to 6 minutes; prompt 10-300 characters; omit lyrics and instrumental")
    p.add_argument("--instrumental", action="store_true", help="make a song without vocals; cannot be combined with lyrics")
    p.add_argument("--num-images", default="1", help="number of songs to generate (default: %(default)s)")
    p.add_argument("--wait", action="store_true", help="block until the song is ready")
    p.add_argument("--skill-name", help="originating database skill name from get_skill; keep the main workflow name across helper skills; omit for unrelated generations")
    p.set_defaults(func=cmd_music)

    p = sub.add_parser(
        "variate", parents=[ws_parent],
        help="edit a source video while preserving its timing and performance",
        formatter_class=argparse.RawTextHelpFormatter,
        epilog=(
            "examples:\n"
            "  astria variate ./source.mp4 --brief 'Change the end card to Astria' --wait\n"
            "  astria variate ./source.mp4 --reference ./dress.jpg --reference woman=./model.jpg --wait\n"
            "  astria variate https://example.com/source.mp4 --tune-id 123 --brief 'Replace the presenter'"
        ),
    )
    p.add_argument("source", help="local MP4/MOV file or public HTTPS video URL")
    p.add_argument("--brief", default="", help="requested edit; optional when references are supplied")
    p.add_argument("--tune-id", dest="tune_ids", action="append", metavar="ID",
                   help="existing replacement reference (repeatable)")
    p.add_argument("--reference", dest="references", action="append", metavar="[NAME=]PATH_OR_URL",
                   help="create a replacement reference; omit NAME to auto-detect it (repeatable)")
    p.add_argument("--base-pack-id", type=int, help="bind the result as a pack one-off")
    p.add_argument("--order-id", type=int, help="associate the result with an accessible order")
    p.add_argument("--wait", action="store_true", help="block until the generated video is ready")
    p.set_defaults(func=cmd_variate)

    inspections = sub.add_parser("video-inspections", help="start and poll video inspections").add_subparsers(dest="sub", required=True)
    p = inspections.add_parser("create", parents=[ws_parent], help="start an inspection and return its id immediately")
    source = p.add_mutually_exclusive_group(required=True)
    source.add_argument("--file-url", help="public HTTPS video URL; supply exactly one of --file-url or --blob-signed-id")
    source.add_argument("--blob-signed-id", help="signed ID of a completed video upload; supply exactly one source")
    p.add_argument("--tune-id", action="append", metavar="ID",
                   help="reference whose appearance should be removed from the description (repeatable)")
    p.set_defaults(func=cmd_video_inspections_create)
    p = inspections.add_parser("get", help="read an inspection's current status and result")
    p.add_argument("id", help="inspection ID returned by video-inspections create")
    p.set_defaults(func=cmd_video_inspections_get)

    p = sub.add_parser("inspect-video", parents=[ws_parent],
                       help="describe a video as timestamped text-to-video prompt text")
    p.add_argument("source", help="local video file or public HTTPS URL")
    p.add_argument("--tune-id", action="append", metavar="ID",
                   help="reference whose appearance should be removed from the description (repeatable)")
    p.set_defaults(func=cmd_inspect_video)

    p = sub.add_parser("classify-image", parents=[ws_parent], help="identify an image reference's subject class and characteristics")
    p.add_argument("source", help="public HTTPS image URL; the CLI also accepts a local image")
    p.add_argument("--class-name", action="append", help="optional allowed subject class (repeatable)")
    p.set_defaults(func=cmd_classify_image)

    p = sub.add_parser("video-edit-prompt", parents=[ws_parent], help="compose a Variate edit prompt from a brief and saved reference IDs")
    p.add_argument("--brief", default="", help="requested edit; optional when references are supplied")
    p.add_argument("--tune-id", action="append", help="existing replacement reference ID (repeatable)")
    p.set_defaults(func=cmd_compose_video_edit)

    p = sub.add_parser("inspect", parents=[ws_parent],
                       help="describe an image as image-generation prompt text")
    p.add_argument("source", help="public HTTPS image URL; upload local images with create_upload first (the CLI also accepts local image files)")
    p.add_argument("--name", action="append",
                   help="reference name whose appearance should be removed from the description (repeatable)")
    p.set_defaults(func=cmd_inspect)

    # download — pull a prompt's rendered images/videos to a local directory
    p = sub.add_parser("download", parents=[ws_parent],
                       help="download the images/videos for one or more prompt ids")
    p.add_argument("ids", nargs="*", help="prompt ids (also accepted via --prompts-file or stdin)")
    p.add_argument("--out", default="./astria-downloads", help="target directory (created if missing)")
    p.add_argument("--prompts-file", help="file of prompt ids (one per line or whitespace-separated)")
    p.set_defaults(func=cmd_download)

    # packs
    packs = sub.add_parser("packs", help="prompt-template collections").add_subparsers(dest="sub", required=True)
    p = packs.add_parser("list", parents=[ws_parent], help="List reusable Astria photoshoot templates with their IDs and titles")
    p.add_argument("--limit")
    p.add_argument("--offset")
    p.add_argument("--sort", choices=["recently_used"], default="recently_used",
                   help="the templates last generated from in this workspace first, never-used ones after (default: %(default)s)")
    p.set_defaults(func=cmd_packs_list)
    p = packs.add_parser("get", parents=[ws_parent], help="get a pack and its template prompts")
    p.add_argument("slug", help="pack slug or id")
    p.set_defaults(func=cmd_packs_get)
    p = packs.add_parser("text", parents=[ws_parent], help="read a pack's prompts as text, one section per product class")
    p.add_argument("slug", help="pack slug or id")
    p.add_argument("--class", dest="class_name", help="only this section; the reply's first lines count them")
    p.add_argument("--limit", help="prompts per reply (at most 50, the default)")
    p.add_argument("--offset", help="prompts to skip, only when the user asks for more than a reply held")
    p.set_defaults(func=cmd_packs_text)
    p = packs.add_parser("create", parents=[ws_parent], help="create a pack")
    p.add_argument("--title", required=True)
    p.add_argument("--subtitle")
    p.add_argument("--model", default=None, help=image_model_help(models_record, "base model for the pack"))
    p.add_argument("--model-type", default="faceid")
    p.add_argument("--main-class-name", help="swappable product category")
    p.set_defaults(func=cmd_packs_create)
    p = packs.add_parser("update", parents=[ws_parent], help="update a template's title and reference categories")
    p.add_argument("id")
    p.add_argument("--title")
    p.add_argument("--subtitle")
    p.add_argument("--main-class-name")
    p.add_argument("--reference-class-name", dest="reference_class_names", action="append")
    p.set_defaults(func=cmd_packs_update)
    p = packs.add_parser(
        "run", parents=[ws_parent],
        formatter_class=argparse.RawTextHelpFormatter,
        help="run a pack (template): fire its prompts against tunes (or a fresh training set)",
        epilog=(
            "examples:\n"
            "  # multi pack — run against existing tunes, with overrides\n"
            "  astria packs run spring-lookbook --tune-id 123 --tune-id 456 \\\n"
            "    --brief \"golden hour, Lisbon\" --aspect-ratio 3:4 --inpaint-faces\n"
            "  # only a subset of the pack's template prompts\n"
            "  astria packs run spring-lookbook --tune-id 123 --prompt-ids 501,502\n"
            "  # regular pack — train a fresh tune from photos, then generate\n"
            "  astria packs run my-pack --title Jane --name woman --image ./a.jpg --image ./b.jpg"
        ),
    )
    p.add_argument("slug", help="pack slug or id")
    p.add_argument("--tune-id", action="append", metavar="ID",
                   help="existing tune to run the pack against (repeatable; multi packs need >=1)")
    p.add_argument("--tune-replacements", type=structured_argument("tune_replacements"), help="JSON object mapping original reference IDs to arrays of replacement IDs; other template references remain fixed")
    p.add_argument("--prompt-ids", help="subset of the pack's template prompt ids, comma-separated")
    p.add_argument("--brief", help="art-direction brief applied to the generated prompts")
    p.add_argument("--title", help="[train] tune title, e.g. the subject's name")
    p.add_argument("--name", help="[train] subject class: man, woman, dress, shoes, ...")
    p.add_argument("--image", action="append", metavar="FILE", help="[train] local image (repeatable)")
    p.add_argument("--image-url", action="append", metavar="URL", help="[train] remote image (repeatable)")
    p.add_argument("--num-images", help="override: images per prompt")
    p.add_argument("--aspect-ratio", help="override: e.g. 3:4, 1:1, 16:9")
    p.add_argument("--resolution", help="override: e.g. 1K, 2K")
    p.add_argument("--inpaint-faces", action=argparse.BooleanOptionalAction, default=None,
                   help="override: face inpainting on/off")
    p.add_argument("--attr", action="append", metavar="KEY=VALUE",
                   help="any other prompt attribute override (repeatable), e.g. --attr super_resolution=true")
    p.add_argument("--prompt-attributes", type=structured_argument("prompt_attributes"),
                   help="JSON object of extra prompt attribute overrides with string values; overrides matching named flags")
    p.set_defaults(func=cmd_packs_run)

    # workspaces
    workspaces = sub.add_parser("workspaces", help="workspaces").add_subparsers(dest="sub", required=True)
    wl = workspaces.add_parser("list", help="list workspaces")
    wl.set_defaults(func=cmd_workspaces_list)
    wg = workspaces.add_parser("get", parents=[ws_parent], help="inspect a workspace")
    wg.add_argument("id")
    wg.set_defaults(func=cmd_workspaces_get)
    wc = workspaces.add_parser("create", help="create a workspace")
    wc.add_argument("--title", required=True)
    wc.add_argument("--url", help="canonical brand website URL")
    wc.set_defaults(func=cmd_workspaces_create)
    wu = workspaces.add_parser("update", parents=[ws_parent], help="update brand workspace metadata or landing page HTML")
    wu.add_argument("id")
    wu.add_argument("--title")
    wu.add_argument("--url")
    wu.add_argument("--landing-page-html")
    wu.add_argument("--brief", help="regenerate the entire landing page from this brief; replaces existing HTML")
    wu.set_defaults(func=cmd_workspaces_update)
    wa = workspaces.add_parser("attach-images", parents=[ws_parent], help="save uploaded or remote images to a workspace")
    wa.add_argument("id")
    wa.add_argument("--signed-id", dest="signed_ids", action="append", help="signed blob ID from a completed upload (repeatable)")
    wa.add_argument("--image-url", dest="image_urls", action="append", help="public HTTPS image URL, including completed Astria direct uploads (repeatable)")
    wa.set_defaults(func=cmd_workspaces_attach_images)

    # agent handoff
    agent = sub.add_parser("agent", help="Astria embedded agent").add_subparsers(dest="sub", required=True)
    p = agent.add_parser("handoff", parents=[ws_parent], help="hand work from another agent into Astria")
    p.add_argument("--handoff", required=True, metavar="HANDOFF.md", help="UTF-8 handoff summary")
    p.add_argument("--attach", action="append", metavar="PATH", help="attach a file or directory (repeatable)")
    p.add_argument("--skill", action="append", metavar="DIR", help="include a skill directory containing SKILL.md (repeatable)")
    p.add_argument("--source", choices=["chatgpt", "claude-code", "claude-desktop", "cursor", "other"])
    p.add_argument("--title", help="title for the imported Astria chat")
    p.add_argument("--open", action="store_true", help="open the Astria deep link after upload")
    p.set_defaults(func=cmd_agent_handoff)
    # headless agent runs (A2A tasks): start, poll, answer, cancel
    p = agent.add_parser("start", parents=[ws_parent], help="run the Astria agent headlessly, e.g. a /music-video skill")
    p.add_argument("message", help="the request for the agent; start with /skill-name to run a skill and include every HTTPS media URL it needs")
    p.set_defaults(func=cmd_agent_start)
    p = agent.add_parser("get", help="poll an agent run: state, status message, questions, artifacts")
    p.add_argument("id", help="task id of the agent run")
    p.set_defaults(func=cmd_agent_get)
    p = agent.add_parser("reply", help="answer the pending question of an input_required agent run")
    p.add_argument("id", help="task id of the agent run")
    p.add_argument("--tool-call-id", required=True, help="tool_call_id of the pending question in the run's questions")
    p.add_argument("--answers", required=True, type=structured_argument("answers"),
                   help='JSON object mapping each question text to the chosen option label, an array of labels for multi-select, '
                        'or the user\'s own words, e.g. {"Which location?": "Beach"}')
    p.set_defaults(func=cmd_agent_reply)
    p = agent.add_parser("cancel", help="stop a working agent run")
    p.add_argument("id", help="task id of the agent run")
    p.set_defaults(func=cmd_agent_cancel)

    # landing page
    landing = sub.add_parser("landing", help="workspace landing page").add_subparsers(dest="sub", required=True)
    p = landing.add_parser("get", parents=[ws_parent], help="fetch the workspace JSON (incl. landing_page_html)")
    p.add_argument("--html", action="store_true", help="print only landing_page_html (raw)")
    p.set_defaults(func=cmd_landing_get)
    p = landing.add_parser("set", parents=[ws_parent], help="update the landing page")
    p.add_argument("--html-file", help="path to the edited inner-body HTML")
    p.add_argument("--brief", help="regenerate the whole page from this brief (Gemini)")
    p.set_defaults(func=cmd_landing_set)

    # cache — local snapshot (JSON + SQLite) of tunes/prompts/packs/user.
    # Query subcommands (get/find/uses/stats) read ONLY the local DB, never the API.
    cache = sub.add_parser("cache", parents=[ws_parent],
                           help="local snapshot + query layer for tunes/prompts/packs")
    cache_sub = cache.add_subparsers(dest="action")
    cache.set_defaults(action="refresh", resource=None, force=False, func=cmd_cache)

    p = cache_sub.add_parser("refresh", parents=[ws_parent],
                             help="pull tunes/prompts/packs/user into JSON + SQLite")
    p.add_argument("resource", nargs="?", choices=list(CACHE_FIELDS), help="refresh only one resource")
    p.add_argument("--force", action="store_true", help="refresh even if the cache is fresh")
    p.set_defaults(func=cmd_cache)

    p = cache_sub.add_parser("path", parents=[ws_parent], help="print the cache directory")
    p.set_defaults(func=cmd_cache, resource=None, force=False)

    p = cache_sub.add_parser("get", parents=[ws_parent], help="get one cached record by id (local DB)")
    p.add_argument("table", choices=list(DB_COLUMNS), help="tunes / prompts / packs")
    p.add_argument("id", help="record id")
    p.set_defaults(func=cmd_cache, resource=None, force=False)

    p = cache_sub.add_parser("find", parents=[ws_parent], help="filter cached records (local DB)")
    find_sub = p.add_subparsers(dest="table", required=True)
    f = find_sub.add_parser("tunes", parents=[ws_parent], help="find tunes by name / title substring")
    f.add_argument("--name", help="class-name substring filter")
    f.add_argument("--title", help="title substring filter")
    f.set_defaults(func=cmd_cache, action="find", resource=None, force=False)
    f = find_sub.add_parser("prompts", parents=[ws_parent], help="find prompts by pack / tune / text")
    f.add_argument("--pack-id", dest="pack_id", help="exact pack id")
    f.add_argument("--tune-id", dest="tune_id", help="exact tune id")
    f.add_argument("--order-id", dest="order_id", help="exact order id")
    f.add_argument("--text", help="prompt text substring filter")
    f.set_defaults(func=cmd_cache, action="find", resource=None, force=False)
    f = find_sub.add_parser("packs", parents=[ws_parent], help="find packs by main-class / title")
    f.add_argument("--main-class", dest="main_class", help="main_class_name substring filter")
    f.add_argument("--title", help="title substring filter")
    f.set_defaults(func=cmd_cache, action="find", resource=None, force=False)

    p = cache_sub.add_parser("uses", parents=[ws_parent],
                             help="prompts whose text references a tune id (<faceid:ID:..>)")
    p.add_argument("tune_id", help="tune id to cross-reference")
    p.set_defaults(func=cmd_cache, resource=None, force=False)

    p = cache_sub.add_parser("stats", parents=[ws_parent], help="row counts per table + cache age")
    p.set_defaults(func=cmd_cache, resource=None, force=False)

    # raw api
    p = sub.add_parser("api", parents=[ws_parent], help="raw API call (escape hatch)")
    p.add_argument("method", help="GET / POST / PATCH / DELETE")
    p.add_argument("path", help="API path, e.g. /tunes?limit=5")
    p.add_argument("--query", action="append", help="query param k=v (repeatable)")
    p.add_argument("--form", action="append",
                   help="form field k=v (repeatable; @file values are direct-uploaded first)")
    p.add_argument("--data", help="raw JSON request body")
    p.set_defaults(func=cmd_api)

    # hidden hook
    p = sub.add_parser("_session-hook")
    p.set_defaults(func=cmd_session_hook)

    return parser



# The command tree above is the parameter source of truth for CLI and MCP.
# Only transport policy lives here; no second set of API payload builders.
OPERATION_POLICIES = {
    "classify_image": (("classify-image",), False, set()),
    "compose_video_edit": (("video-edit-prompt",), False, set()),
    "inspect_image": (("inspect",), False, set()),
    "inspect_video": (("video-inspections", "create"), False, set()),
    "get_video_inspection": (("video-inspections", "get"), True, set()),
    "list_models": (("models",), True, {"refresh"}),
    "list_workspaces": (("workspaces", "list"), True, set()),
    "list_references": (("tunes", "list"), True, set()),
    "get_reference": (("tunes", "get"), True, set()),
    "update_reference": (("tunes", "update"), False, set()),
    "archive_reference": (("tunes", "archive"), False, set()),
    "create_reference": (("tunes", "create"), False, {"image", "model", "model_type"}),
    "generate_images": (("generate",), False, {"wait", "video_prompt"}),
    "generate_video": (("video",), False, {"wait", "input_image"}),
    "generate_music": (("music",), False, {"wait"}),
    "list_prompts": (("prompts", "list"), True, set()),
    "get_prompt": (("prompts", "get"), True, set()),
    "update_prompt": (("prompts", "update"), False, set()),
    "archive_prompt": (("prompts", "archive"), False, set()),
    "enhance_video": (("prompts", "enhance"), False, set()),
    "attach_prompt_media": (("prompts", "attach"), False, {"file"}),
    "replace_prompt_media": (("images", "replace"), False, {"file"}),
    "list_templates": (("packs", "list"), True, set()),
    "get_template": (("packs", "get"), True, set()),
    "get_template_text": (("packs", "text"), True, set()),
    "create_template": (("packs", "create"), False, set()),
    "update_template": (("packs", "update"), False, set()),
    "create_workspace": (("workspaces", "create"), False, set()),
    "attach_workspace_images": (("workspaces", "attach-images"), False, set()),
    "get_workspace": (("workspaces", "get"), True, set()),
    "update_workspace": (("workspaces", "update"), False, set()),
    "run_template": (("packs", "run"), False, {"image", "attr"}),
    "start_agent_run": (("agent", "start"), False, set()),
    "get_agent_run": (("agent", "get"), True, set()),
    "reply_agent_run": (("agent", "reply"), False, set()),
    "cancel_agent_run": (("agent", "cancel"), False, set()),
}
CLI_ONLY_COMMANDS = {
    ("login",): "Host-local credential storage", ("logout",): "Host-local credential removal",
    ("whoami",): "MCP exposes authenticated get_profile separately", ("config",): "Host-local configuration",
    ("upgrade",): "Installs the local executable", ("prompts", "wait"): "Blocking local polling; MCP uses get_prompt/events",
    ("variate",): "Local orchestration; MCP uses classify_image/create_reference, compose_video_edit, then generate_video with video_references",
    ("inspect-video",): "Local upload and blocking convenience; MCP uses inspect_video and get_video_inspection",
    ("download",): "Writes local files", ("agent", "handoff"): "Embedded-agent session handoff",
    ("landing", "get"): "Local HTML extraction; MCP get_workspace returns metadata",
    ("landing", "set"): "Local-file input; MCP update_workspace accepts supplied HTML or a regeneration brief",
    ("cache", "refresh"): "Local cache", ("cache", "path"): "Local cache",
    ("cache", "get"): "Local cache", ("cache", "find", "tunes"): "Local cache",
    ("cache", "find", "prompts"): "Local cache", ("cache", "find", "packs"): "Local cache",
    ("cache", "uses"): "Local cache", ("cache", "stats"): "Local cache",
    ("api",): "Unrestricted raw API escape hatch is CLI-only", ("_session-hook",): "Local agent hook",
}


def command_paths(parser, prefix=()):
    subparsers = [action for action in parser._actions if isinstance(action, argparse._SubParsersAction)]
    if not subparsers:
        return {prefix}
    return set().union(*(command_paths(child, prefix + (name,))
        for action in subparsers for name, child in action.choices.items()))


def validate_operation_coverage():
    commands = command_paths(build_parser(models_record={}))
    exposed = {path for path, _readonly, _excluded in OPERATION_POLICIES.values()}
    excluded = set(CLI_ONLY_COMMANDS)
    if exposed & excluded or commands != exposed | excluded:
        raise AstriaError(f"CLI/MCP coverage mismatch: unclassified={sorted(commands - exposed - excluded)}, "
            f"stale={sorted((exposed | excluded) - commands)}, duplicate={sorted(exposed & excluded)}")

OPERATION_DESCRIPTIONS = {
    'classify_image': 'Identify the subject class and characteristics of an image before creating a replacement reference. Supply source as a public HTTPS image URL, uploading local files with create_upload first. Optional class_name entries restrict the allowed classes. Returns class_name and available caption/description metadata, or error. Use the class_name with create_reference. May invoke a paid provider; requires an idempotency_key for safe retries.',
    'compose_video_edit': 'Prepare the Variate workflow when the user wants to edit an existing video while preserving its shots, timing and performance. Supply brief and/or saved replacement reference IDs in tune_id. For new reference images, first use classify_image if their class is unknown, then create_reference. Returns video_prompt, video_model, generate_audio and num_images for generate_video. Submit those returned fields with the source video HTTPS URL as the only item of video_references, and the same workspace; use get_prompt to follow the generation. No source-video inspection is needed. This tool only writes the edit prompt and does not generate a video. Requires an idempotency_key; reuse it for identical retries.',
    'inspect_image': 'Describe an image as image-generation prompt text using Astria. Pass source as a public HTTPS image URL. For a local image, first complete its create_upload upload and use the returned URL. Optional name entries omit the appearance of those named reference subjects, such as dress or shoes. This is a paid inspection. Requires an idempotency_key; reuse the same key and arguments for an identical retry. Returns description synchronously, or error if inspection fails. Does not generate an image.',
    'inspect_video': 'Start a paid video inspection to describe a video as timestamped text-to-video prompt text. Supply exactly one of file_url (public HTTPS) or blob_signed_id from a completed create_upload video upload. Optional tune_id reference IDs remove those subjects appearances from the description. Requires an idempotency_key; reuse the same key and arguments for a retry. Returns an inspection id and pending status immediately. Poll get_video_inspection every 2-5 seconds until completed or failed; do not resubmit to check progress.',
    'get_video_inspection': 'Poll a video inspection started with inspect_video. Pass its inspection id. Returns status pending, processing, completed or failed; completed includes description and available model/provider/usage metadata, failed includes error. Poll every 2-5 seconds while pending or processing and stop on completed or failed. Inspections expire one hour after their last update and are visible only to the user who started them. An unknown or expired inspection returns an error. Does not start an inspection or charge credits.',
    'enhance_video': 'Use this when the user asks to upscale a finished Astria video or increase its frame rate. Pass the prompt id of a completed video and either video_upscale_model or video_fps_model, not both; for both, call again with the first result id once it completes. Creates a new paid prompt and leaves the original unchanged. Each enhancement applies once per video. Use a unique idempotency_key per action and reuse it only for an identical retry. Returns the submitted prompt with id and cost_mc; check get_prompt for the final video or errors without resubmitting.',
    'attach_prompt_media': 'Append an uploaded image or MP4 to an existing prompt, for example a finished muxed film. First prepare an upload with create_upload and successfully upload its bytes, then pass its blob_signed_id and the prompt id. Supports PNG, JPEG, WebP, AVIF and MP4. Preserves existing results; does not generate or replace media. Requires an idempotency_key. Returns the saved asset and updated prompt; use get_prompt to view all results.',
    'replace_prompt_media': 'Replace a saved image or MP4 result only when requested. First successfully upload the replacement with create_upload, then pass its blob_signed_id and the prompt id. Omit replace_blob_id only when the prompt has exactly one result of the replacement media type; otherwise select its blob_id from get_prompt. Retains the original in debug history and preserves other results. Does not generate media. Requires an idempotency_key; reuse the same key and arguments for a retry. Returns the saved asset and updated prompt; use get_prompt with expand=["debug_images"] to inspect history.',
    'create_workspace': 'Create a separate brand/team workspace when requested. Supply its title and optional canonical website URL. Returns the workspace ID; use it on subsequent references, templates and generations. Does not invite members or generate images.',
    'get_workspace': 'Inspect a selected workspace by ID, including its brand website, favicon and logo URLs, landing_page_html and attached images with persistent URLs. Does not create or change the workspace.',
    'attach_workspace_images': 'Attach images to a selected workspace before using them on its landing page. Supply image_urls for public HTTPS images (including completed Astria direct uploads), signed_ids from completed create_upload uploads, or both. Reuses Astria uploads and imports external images into workspace storage. Supports PNG, JPEG, WebP, AVIF and GIF up to 100 MB each. Preserves existing workspace images and does not generate media. Returns workspace_id and images with id, blob_id, url, filename and content_type; use the returned URLs in landing_page_html. Requires an idempotency_key for safe retries.',
    'update_workspace': 'Update a selected workspace title, brand website URL or supplied landing page HTML. Does not publish the workspace, invite members or change billing. Provide only the fields to change. Set brief only when the user requests full landing-page regeneration; it replaces existing HTML. Use get_workspace to read the generated HTML. Requires an idempotency_key for safe retries.',
    'create_template': 'Create a reusable photoshoot template container in the selected workspace. Supply a title, model and optional main product category; author its shots with generate_images using the returned pack_id, then set reference categories with update_template. Creating the container does not generate images.',
    'update_template': 'Update an existing template title, subtitle or reference categories. Does not generate images or replace its prompts. Inspect get_template before changing its category slots.',
    'update_reference': 'Update a selected reference title, subject class, short description, injected text or verified catalog source records. text sets characteristics.text; omit it to preserve the current text or pass an empty string to clear it. Other characteristics are preserved. Sources include provider, account_key, resource_type, external_id and captured metadata. Does not retrain the reference or generate images.',
    'update_prompt': 'Assign an existing prompt to a template, clear template membership, or move it to an authorized workspace. Pass pack_id or base_pack_id as the string null to clear that assignment. Does not generate, delete or retry an image.',
    'archive_prompt': 'Archive an image, video or music prompt only when the user asks to archive, hide or clean up that result. Pass its id. Archiving hides the prompt from galleries and list_prompts without deleting its media or refunding credits; list_prompts archived=true finds archived prompts. Set unarchive=true to restore one. Requires an idempotency_key.',
    'archive_reference': 'Archive a saved reference only when the user asks to archive, hide or clean up that person, product or garment. Pass its id. Archiving hides the reference from list_references without deleting it or its training images; list_references archived=true finds archived references; templates and prompts that use it keep working. Set unarchive=true to restore one. Requires an idempotency_key. Returns id and archived.',
    'list_models': 'Use this when choosing an Astria image, video or music model or checking supported media inputs, image resolutions, aspect ratios, lyrics limits, song prices, and defaults. Pass type (image, video or music) to get only that catalog. Returns the live model catalog and model names/tune IDs; does not generate media or spend credits. For video generation, submit null model and resolution fields unless the user explicitly selected them; let Astria resolve defaults. For images and music, use the explicit user selection or catalog default.',
    'list_workspaces': 'Use this when finding an Astria workspace for a team or brand photoshoot. Returns authorized workspace IDs with their brand website, favicon and logo URLs, for duplicate detection. Use the selected ID consistently for references, templates, and generations. Does not create a workspace or generate media.',
    'list_references': 'Use this when finding a saved person, model, garment, product, or SKU for consistent photos, virtual try-on, headshots, or video. Search title/product name/SKU; gallery=true finds public model references. Returns reusable reference IDs and subject classes. Does not create references or generate media; inspect a selected match with get_reference.',
    'get_reference': 'Use this when inspecting a selected Astria identity or product reference and its training images before a photoshoot or try-on. Returns the saved subject class and reference details. A reference token uses <model_type:ID:1> followed by that class. Does not create or alter the reference.',
    'create_reference': 'Use this when a supplied person or product needs one reusable Astria reference for consistent headshots, virtual try-on, product shots, or multiple scenes. Provide real HTTPS photo URLs, a subject class in name, and a human label in title. Reuse an existing reference when available. Creates paid content only within the requested generation/reference scope; requires an idempotency_key. Returns the new reference ID and class; reuse them across generations. Does not return a finished photoshoot.',
    'generate_images': 'Use this when the user asks to create or edit images: product photography, ecommerce packshots, on-model fashion/virtual try-on, lookbooks, professional headshots from supplied photos, or consistent people/products across scenes. Reference tokens in text preserve selected subjects; input_image edits an existing HTTPS image, and mask_image limits an edit. Separate scene briefs need separate submissions; num_images varies one brief. model is optional: omit it for the catalog default image model, and call list_models type=image only to choose another model or check resolutions. Respect an explicitly chosen provider. Prompt advice or a text-only storyboard is not a generation request. Creates paid Astria content within the requested scope; use a unique idempotency_key per action and reuse it only for an identical retry. Returns a submitted prompt with id and tune_id and an embedded result preview; check get_prompt for finished assets or errors without resubmitting.',
    'generate_video': 'Use this when the user requests an Astria video, animating a photo/product, or motion with consistent person/product references. Provide video_prompt. Submit video_model=null and video_resolution=null unless the user explicitly selected those settings; Astria resolves its defaults. Do not select a model or resolution yourself or copy catalog defaults into the request. Call list_models type=video only to resolve an explicit selection or check capabilities. generate_audio=true picks the audio output of families that offer one. Use first_frame/last_frame for image-led video and video_references/audio_references only when the chosen model supports them; the prompt names their items by position as @Video1 and @Audio1. Do not call for storyboard writing, prompt advice, or an explicitly chosen other provider. Creates paid content within the requested scope; use a unique idempotency_key per action and reuse it only for an identical retry. Returns a submitted prompt with id and tune_id and an embedded result preview; check get_prompt for final video assets or errors without resubmitting.',
    'generate_music': 'Use this when the user asks for an Astria song, jingle, soundtrack, background music or instrumental track. Provide text as the song description (genre, mood, instruments, vocals, tempo); pass lyrics with the model\'s section tags such as [Verse] and [Chorus] to sing given words, omit lyrics to let the model write them, or set instrumental=true for no vocals. model is optional and defaults to default_music_model; call list_models type=music to choose another music model or check lyrics length limits, section tags and the price of each kind of song. For MiniMax, audio_reference selects Music Cover: an MP3 with vocals, 6 seconds to 6 minutes, a 10-300 character style prompt, and no lyrics or instrumental flag. It does not guarantee preservation of exact event timing. Do not call for lyric writing or music advice alone; use generate_video generate_audio for native video sound. Creates paid content within the requested scope; use a unique idempotency_key per action and reuse it only for an identical retry. Returns a submitted prompt with id and tune_id; check get_prompt for the finished audio or errors without resubmitting.',
    'list_prompts': 'Use this when finding recent Astria images/videos, checking existing submissions after an uncertain response, or locating outputs from a saved photoshoot run. Filter by reference, template, order, text, review status, source, or media type. Does not generate or charge credits. Results include prompt IDs for get_prompt; expand prompt.comments to inspect review feedback.',
    'get_prompt': 'Use this when checking progress, finished images/videos, or errors for an existing Astria generation. Pass its returned id. Returns the current prompt and available assets with an embedded preview; no generation is submitted or charged. Pending or failed results must not be treated as a new generation request. expand prompt.comments includes image review feedback.',
    'list_templates': 'Use this when finding an existing reusable Astria photoshoot/template (also called a pack) for product images, lookbooks, or headshots. Returns accessible template names/slugs and thumbnails, most recently used first; inspect a selected template with get_template before run_template. Browsing does not run a photoshoot or spend credits.',
    'get_template': 'Use this when resolving a selected Astria photoshoot template by slug or ID before running it or inspecting its prompts, reference slots, and baseline pricing. Does not generate images or modify the template. Preserve the returned reference-slot order when calling run_template.',
    'get_template_text': 'Use this when reading what a template\'s prompts say, to learn from or rebuild them: each prompt\'s verbatim text, aspect ratio, model, references and example images, as plain text with one section per product class. A reply holds at most 50 prompts and counts the sections; read further with offset only when the user asks for more. Does not generate images or modify the template. Use get_template for its reference slots before run_template.',
    'run_template': 'Use this when the user asks to run a saved Astria photoshoot/template on their person or product, repeat an existing lookbook with a new SKU, or generate portraits from a selected pack. Resolve the template and reference slots first with get_template; pass tune_id entries in slot order, supported photo inputs, or tune_replacements mapping original IDs to replacement ID arrays to swap selected products while retaining other references. Do not substitute one generic image for a requested template run, and do not run a template for browsing or pricing advice. Creates paid Astria content within the requested scope; requires an idempotency_key. prompt_attributes supplies additional per-prompt overrides as a JSON object of string values and takes precedence over matching named parameters. Returns the submitted order/prompt IDs; use list_prompts to find prompt IDs and get_prompt to check outputs without rerunning.',
    'start_agent_run': 'Delegate work to an Astria agent only when the user explicitly requests delegation or a required step cannot run in the current host. Execute workflows directly with available Astria tools and local capabilities; a named skill or multi-step request alone does not require an agent run. Assess available tools rather than desktop, web, or embedded client labels. Delegate only the necessary stage when practical: for muxing, pass existing video and audio URLs instead of regenerating them. Pass the workspace ID and a scoped message, starting with /skill-name when applicable, with every required HTTPS media URL (upload local files with create_upload first). The run may generate paid media within the request; requires an idempotency_key. Returns a task id; poll get_agent_run until completed, input_required, failed or canceled. Use generate_images, generate_video or generate_music for direct generations. An Astria agent run must never start another run.',
    'get_agent_run': 'Use this to follow a run started with start_agent_run; poll every 15-30 seconds while status.state is submitted or working. Returns the task: status.state (submitted, working, input_required, completed, failed or canceled), status.message with the agent\'s latest words, pending questions, artifacts and an Astria url. On input_required, put the questions to the user and answer them with reply_agent_run. Artifacts are the results: a file part has a downloadable uri (such as the final MP4) and a data part has a prompt_id for get_prompt. Does not start or charge anything.',
    'reply_agent_run': 'Use this when get_agent_run reports input_required. Pass the run id, the question\'s tool_call_id and answers mapping each question text to the chosen option label (an array of labels for multi-select, or the user\'s own words). The run resumes and may generate paid media within its original request; requires an idempotency_key. Then poll get_agent_run; the task can still show the answered question for a few seconds.',
    'cancel_agent_run': 'Use this only when the user asks to stop a run started with start_agent_run. Interrupts the working agent; generations it already submitted still finish and are billed. Only the user who started the run can cancel it. Requires an idempotency_key. Returns the task; get_agent_run reports canceled once the run stops.',
}


REMOTE_MEDIA_ARGUMENTS = {
    "image_urls", "image_url", "input_image", "mask_image", "references", "image_references",
    "first_frame", "last_frame", "video_references", "audio_references", "audio_reference", "file_url", "source",
}


class OperationContext(dict):
    """Request-scoped API transport. Never resolves CLI files or credentials."""
    def __init__(self, transport):
        super().__init__()
        self.transport = transport


def operation_parser(path):
    parser = build_parser(models_record={})
    for command in path:
        subcommands = next(action for action in parser._actions
                           if isinstance(action, argparse._SubParsersAction))
        help_text = next((choice.help for choice in subcommands._choices_actions
                          if choice.dest == command), "")
        parser = subcommands.choices[command]
        if not parser.description:
            parser.description = help_text
    return parser


# Updates replace saved metadata or assignments rather than only adding content;
# cancelling stops an agent's work in progress.
DESTRUCTIVE_OPERATIONS = {
    "update_reference", "update_prompt", "update_template", "update_workspace", "cancel_agent_run", "replace_prompt_media",
}


def mcp_help(parser, text):
    """CLI help in MCP terms: 'astria models --type X' is list_models type=X, --flag-name its argument."""
    text = re.sub(r"'astria models(?: --type (\w+))?'", lambda m: "list_models" + (f" type={m[1]}" if m[1] else ""), text)
    flags = {option: action.dest for action in parser._actions for option in action.option_strings}
    return re.sub(r"--[a-z][a-z-]*", lambda m: flags.get(m[0], m[0]), text)


def operation_catalog():
    validate_operation_coverage()
    tools = []
    for name, (path, readonly, excluded) in OPERATION_POLICIES.items():
        parser = operation_parser(path)
        properties = {}
        required = []
        for action in parser._actions:
            if action.dest in excluded or action.dest == "help":
                continue
            boolean = isinstance(action, (argparse._StoreTrueAction, argparse.BooleanOptionalAction))
            spec = {"type": "boolean" if boolean else "string"}
            if action.choices is not None:
                spec["enum"] = list(action.choices)
            if isinstance(action, argparse._AppendAction):
                spec = {"type": "array", "items": spec}
            if action.help and action.help != argparse.SUPPRESS:
                spec["description"] = mcp_help(parser, action.help.replace("%(default)s", str(action.default)))
            if action.dest in JSON_ARGUMENT_SCHEMAS:
                spec = JSON_ARGUMENT_SCHEMAS[action.dest].copy() | {"description": mcp_help(parser, action.help)}
            if name == "generate_video" and action.dest in ("video_model", "video_resolution"):
                spec = {"anyOf": [{"type": "string"}, {"type": "null"}],
                    "description": "User-selected video model family; submit null for Astria defaults." if action.dest == "video_model"
                    else "User-selected video resolution; submit null for Astria defaults."}
            properties[action.dest] = spec
            if action.required or not action.option_strings:
                required.append(action.dest)
        # These flags are validated by their handlers in terminal use.
        if name == "generate_images":
            required.append("text")
        if name == "create_reference":
            required.append("image_url")
        if name in ("attach_prompt_media", "replace_prompt_media"):
            required.append("blob_signed_id")
        if name == "start_agent_run":
            required.append("workspace")
        if not readonly:
            properties["idempotency_key"] = {"type": "string", "minLength": 1,
                "description": "Unique submission key. Reuse it only when retrying the same operation."}
            required.append("idempotency_key")
        tools.append({
            "name": name,
            "title": name.replace("_", " ").title(),
            "description": OPERATION_DESCRIPTIONS[name],
            "inputSchema": {"type": "object", "properties": properties,
                            "required": list(dict.fromkeys(required)), "additionalProperties": False},
            # A text result is the reply's content itself, with nothing structured to validate.
            **({} if API_OPERATIONS[name]["result"].get("text") else {
                "outputSchema": {"type": "object", "properties": {"result": {}},
                                 "required": ["result"], "additionalProperties": False}}),
            "annotations": {"readOnlyHint": readonly, "destructiveHint": name in DESTRUCTIVE_OPERATIONS,
                            "openWorldHint": not readonly},
            "securitySchemes": [{"type": "oauth2", "scopes": []}],
        })
    return tools


def operation_contract():
    operations = {}
    for tool in operation_catalog():
        name = tool["name"]
        definition = API_OPERATIONS[name]
        path, _readonly, _excluded = OPERATION_POLICIES[name]
        parser = operation_parser(path)
        actions = [action for action in parser._actions if action.dest != "help"]
        covered = {spec[1] for spec in definition["fields"]} | {"workspace", "idempotency_key"}
        covered.update(re.findall(r"\{([^}]+)\}", definition["path"]))
        covered.update(definition.get("characteristics", {}).values())
        if "path_choice" in definition:
            covered.add(definition["path_choice"][0])
            covered.update(re.findall(r"\{([^}]+)\}", definition["path_choice"][1]))
        if "model" in definition:
            covered.add(definition["model"]["argument"])
        if "references" in definition:
            covered.add(definition["references"]["argument"])
        if "sections" in definition["result"]:
            covered.add(definition["result"]["sections"]["argument"])
        unmapped = set(tool["inputSchema"]["properties"]) - covered
        if unmapped:
            raise AstriaError(f"{name} has unmapped parameters: {sorted(unmapped)}")
        operations[name] = {**definition,
            "defaults": {**{spec[1]: parser.get_default(spec[1]) for spec in definition["fields"]},
                         **{action.dest: action.default for action in actions}},
            "integer_arguments": [action.dest for action in actions if action.type is int]}
    return {"version": 1, "operations": operations, "cli_only_commands": {" ".join(path): reason for path, reason in CLI_ONLY_COMMANDS.items()}, "prompt_filters": PROMPT_FILTERS,
            "remote_media_arguments": sorted(REMOTE_MEDIA_ARGUMENTS),
            "fallback_models": MODEL_TUNES, "fallback_default": "gemini"}


def run_operation(name, arguments, transport):
    """Execute a shared handler without terminal output, local state or tokens."""
    path, _readonly, excluded = OPERATION_POLICIES[name]
    tool = next(tool for tool in operation_catalog() if tool["name"] == name)
    schema = tool["inputSchema"]
    unknown = set(arguments) - set(schema["properties"])
    missing = set(schema["required"]) - set(arguments)
    if unknown or missing:
        raise AstriaError(f"Invalid arguments: unknown={sorted(unknown)}, missing={sorted(missing)}")
    parser = operation_parser(path)
    values = {**parser._defaults, **{action.dest: action.default for action in parser._actions if action.dest != "help"}}
    for key, value in arguments.items():
        spec = schema["properties"][key]
        if not validate_argument(spec, value):
            raise AstriaError(f"Invalid value for {key}")
        if key in REMOTE_MEDIA_ARGUMENTS:
            media = value if isinstance(value, list) else [value]
            for item in media:
                url = item.split("=", 1)[1] if key == "references" and "=" in item else item
                parsed = urlparse(url)
                if parsed.scheme != "https" or not parsed.hostname or parsed.username:
                    raise AstriaError(f"{key} requires HTTPS URLs; local files belong to the CLI")
        if key != "idempotency_key":
            values[key] = value
    for action in parser._actions:
        if action.dest in values and action.type is not None and values[action.dest] is not None and action.dest not in JSON_ARGUMENT_SCHEMAS:
            values[action.dest] = action.type(values[action.dest])
    output = []
    marker = _operation_output.set(output)
    try:
        parser.get_default("func")(argparse.Namespace(**values), OperationContext(transport))
    finally:
        _operation_output.reset(marker)
    if len(output) != 1:
        raise AstriaError("Operation must return exactly one structured result")
    return output[0]


def main():
    # Resolve the profile up front so build_parser() reads that profile's
    # cached model catalog for the --help enum text; re-resolve from the
    # parsed args afterwards so the flag stays authoritative.
    sys.argv[1:] = normalize_meta_argv(sys.argv[1:])
    apply_profile(resolve_profile(argv_profile()))
    args = build_parser().parse_args()
    apply_profile(resolve_profile(args.profile))
    cfg = load_config()
    if args.command != "upgrade":
        check_cli_version(load_models_cache(), auto_upgrade=True)
    try:
        args.func(args, cfg)
    except AstriaError as exc:
        die(str(exc))
    except BrokenPipeError:
        sys.exit(0)
    except KeyboardInterrupt:
        die("interrupted", code=130)


if __name__ == "__main__":
    main()

SHA-256: cee863ff1974aa08f0a62c05da842f85ed6a1191f7a93698547ec434e8c65dde