diff --git a/packages/core/src/opendirector/agent/command_help.py b/packages/core/src/opendirector/agent/command_help.py new file mode 100644 index 000000000..cda520ce5 --- /dev/null +++ b/packages/core/src/opendirector/agent/command_help.py @@ -0,0 +1,193 @@ +import difflib +from uuid import UUID + +from pydantic import JsonValue + +from opendirector.domain.creation.commands import COMMAND_MODELS +from opendirector.domain.creation.contract_messages import contract_text, kebab +from opendirector.domain.projects import ProjectError + +EXCLUDED = {'project.create', 'project.trash', 'project.restore', 'asset.import', 'job.checkpoint', + 'canvas.applyEdit', 'canvas.publishMedia', 'timeline.publishRender'} + +COMMANDS = {name: model for name, model in COMMAND_MODELS.items() + if name not in EXCLUDED} +for command_name, command_model in COMMANDS.items(): + assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}' + + +def command_help(schema: dict, path: str, project_id: UUID) -> dict: + definitions = schema.get('$defs', {}) + + def resolve(node: dict) -> dict: + if '$ref' in node: + return {**definitions[node['$ref'].rsplit('/', 1)[1]], **node} + return node + + def branches(node: dict) -> dict: + mapping = node.get('discriminator', {}).get('mapping') + if mapping: + return {key: {'$ref': value} for key, value in mapping.items()} + choices = node.get('anyOf', node.get('oneOf', [])) + return {str(index): choice for index, choice in enumerate(choices)} + + def summary(node: dict, target: str) -> dict: + node = resolve(node) + details = {key: node[key] for key in ( + 'type', 'format', 'const', 'enum', 'default', 'description', 'minimum', 'maximum', + 'exclusiveMinimum', 'exclusiveMaximum', 'minLength', 'maxLength', + 'minItems', 'maxItems', 'pattern', + ) if key in node} + choices = branches(node) + if choices: + details.setdefault('type', 'union') + details['branches'] = {} + for key, choice in choices.items(): + branch = resolve(choice) + details['branches'][key] = { + 'path': f'{target}@{key}', + 'description': branch.get('description', branch.get('title', branch.get('type', key))), + **{name: branch[name] for name in ('type', 'required', 'const', 'enum') if name in branch}, + } + if target: + details['path'] = target + return details + + def minimal_value(node: dict, branch: str | None = None) -> JsonValue: + node = resolve(node) + if 'examples' in node: + return node['examples'][0] + if 'const' in node: + return node['const'] + if 'enum' in node: + return node['enum'][0] + choices = branches(node) + if choices: + return minimal_value(choices.get(branch, next(iter(choices.values())))) + kind = node.get('type') + if kind == 'object': + return {key: minimal_value(node['properties'][key], 'timeline' if key == 'document' else None) for key in node.get('required', [])} + if kind == 'array': + return [minimal_value(node['items']) for _ in range(node.get('minItems', 0))] + if kind == 'string': + if node.get('format') == 'uuid': + return str(project_id) + if node.get('pattern') == '^sha256:[0-9a-f]{64}$': + return 'sha256:' + '0' * 64 + if node.get('pattern') == '^[0-9a-f]{64}$': + return '0' * 64 + return 'x' * max(1, node.get('minLength', 0)) + if kind in {'integer', 'number'}: + return node.get('minimum', node.get('exclusiveMinimum', -1) + 1) + if kind == 'boolean': + return False + return None + + def field_paths(node: dict, prefix: str, depth: int = 0) -> list[str]: + node = resolve(node) + if depth > 6: + return [] + found = [] + children = [(f'{prefix}.{key}' if prefix else key, child) for key, child in node.get('properties', {}).items()] + if 'items' in node: + children.append((f'{prefix}.[]' if prefix else '[]', node['items'])) + children += [(f'{prefix}@{key}', child) for key, child in branches(node).items()] + for target, child in children: + found.append(target) + found += field_paths(child, target, depth + 1) + return found + + def invalid_path(level: str, node: dict, requested: str) -> ProjectError: + paths = field_paths(schema, '') + last = requested.replace('@', '.').rsplit('.', 1)[-1] + nearest = '' + for scope in ([value for value in paths if value.startswith(level)], paths) if level else (paths,): + same_name = sorted((value for value in scope if value.replace('@', '.').rsplit('.', 1)[-1] == last), + key=lambda value: (value.count('.') + value.count('@'), value)) + nearest = same_name[0] if same_name else next(iter(difflib.get_close_matches(requested, scope, n=1, cutoff=0.5)), '') + if nearest: + break + nearest = nearest or level + available = [*resolve(node).get('properties', {}), *(f'@{key}' for key in branches(resolve(node)))] + command = resolve(schema).get('properties', {}).get('type', {}).get('const') + target = nearest or (f'{level}.{available[0]}' if level and available else available[0] if available else '') + example = '-' + if command and target: + namespace, action = command.split('.', 1) + example = (f'command_schema {{"type":"{command}","path":"{target}"}} | ' + f'opendirector {kebab(namespace)} {kebab(action)} --help-field {target}') + return ProjectError(contract_text('help_field_invalid', requested=requested, nearest=nearest or '-', level=level or '$', + fields=', '.join(available) or '-', example=example), code='help_field_invalid') + + node = schema + remaining = path + level = '' + while remaining: + node = resolve(node) + if remaining.startswith('@'): + choices = branches(node) + selector = next((key for key in sorted(choices, key=len, reverse=True) + if remaining[1:] == key or remaining[1:].startswith((key + '.', key + '@'))), None) + child = choices.get(selector) if selector is not None else None + remaining = remaining[len(selector) + 1:] if selector is not None else '' + else: + boundary = min((remaining.find(mark) for mark in ('.', '@') if mark in remaining), default=len(remaining)) + field = remaining[:boundary] + child = node.get('items') if field == '[]' else node.get('properties', {}).get(field) + remaining = remaining[boundary:] + if child is None: + raise invalid_path(level, node, path) + level = path[:len(path) - len(remaining)] + node = child + if remaining.startswith('.'): + remaining = remaining[1:] + + node = resolve(node) + prefix = f'{path}.' if path else '' + result = {'path': path, **summary(node, path)} + if 'description' in node: + result['description'] = node['description'] + if 'properties' in node: + result['required'] = node.get('required', []) + result['fields'] = {key: summary(value, prefix + key) for key, value in node['properties'].items()} + if not path: + payload = resolve(node['properties']['payload']) + command = node['properties']['type']['const'] + fields = result['fields'] + fields.pop('type') + fields['payload']['required'] = payload.get('required', []) + fields['payload']['fields'] = { + key: summary(value, f'payload.{key}') for key, value in payload.get('properties', {}).items() + } + example = {'type': command, 'payload': minimal_value(payload)} + if command == 'canvas.createGeneration': + spec = example['payload']['spec'] + item = example['payload']['item'] + spec['purpose'] = 'generation' + item['kind'] = spec['kind'] + item['binding'] = {'role': 'generation', 'objectRef': {'id': spec['id']}} + if command == 'generation.submit': + example['payload']['originItemId'] = str(project_id) + model = COMMANDS[command] + parsed_payload = model.model_fields['payload'].annotation.model_validate(example['payload']) + sample = model.model_construct(type=command, payload=parsed_payload, projectId=project_id) + versions = sample.required_versions() + if versions: + owned = next((getattr(parsed_payload, field, None) for field in ('spec', 'reference', 'document') + if getattr(parsed_payload, field, None) is not None), None) + revision = getattr(parsed_payload, 'expectedSpecRevision', getattr(owned, 'revision', 1)) + example['expectedVersions'] = [ + {'objectType': kind, 'id': str(identity), 'revision': revision} + for kind, identity in dict.fromkeys(versions) + ] + if command == 'asset.delete': + example['expectedPreview'] = '0' * 64 + return { + 'command': command, + 'description': node['description'], + 'example': example, + 'fields': fields, + } + if 'items' in node: + result['items'] = summary(node['items'], prefix + '[]') + return result diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 3d481890f..a4636fc3a 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -11,6 +11,7 @@ from uuid import UUID, uuid5 from pydantic import JsonValue, TypeAdapter, ValidationError +from opendirector.agent.command_help import COMMANDS, EXCLUDED, command_help from opendirector.domain.creation.base import agent_command_id from opendirector.application.creation_artifacts import publish_artifact from opendirector.application.creation_assets import CreationAssets @@ -23,7 +24,6 @@ from opendirector.domain.creation.assets import AssetDownloadFile, AssetProvenance from opendirector.domain.creation.base import ObjectVersion from opendirector.domain.creation.commands import Query, COMMAND_MODELS, parse_command -from opendirector.domain.creation.contract_messages import contract_text, kebab from opendirector.domain.creation.models import ModelSnapshot from opendirector.domain.projects import ProjectError from opendirector.domain.rule_facts import MAX_REFERENCES @@ -35,8 +35,6 @@ from opendirector.installation import SOURCE_ROOT, BUNDLED ROOT = SOURCE_ROOT or BUNDLED -EXCLUDED = {'project.create', 'project.trash', 'project.restore', 'asset.import', 'job.checkpoint', - 'canvas.applyEdit', 'canvas.publishMedia', 'timeline.publishRender'} QUERY_MODELS = get_args(get_args(Query)[0]) #: The legal `type` values, read from the union itself. A new query type cannot @@ -60,10 +58,6 @@ def query_guidance(failure): hint = f' Did you mean {closest[0]}?' if closest else '' return f'Unsupported query type {given!r}.{hint} Valid types: {", ".join(QUERY_TYPES)}.' return str(failure) -COMMANDS = {name: model for name, model in COMMAND_MODELS.items() - if name not in EXCLUDED} -for command_name, command_model in COMMANDS.items(): - assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}' CLI_DISCOVERY_RULE = ( 'Run opendirector capabilities once, and inspect a command with opendirector COMMAND --help-field payload ' 'only when one field\'s shape is unclear. Do not run --help for each command.' @@ -135,183 +129,6 @@ def restrict_batch_schema(definitions: dict) -> None: definitions.pop(reference.rsplit('/', 1)[1]) -def command_help(schema: dict, path: str, project_id: UUID) -> dict: - definitions = schema.get('$defs', {}) - - def resolve(node: dict) -> dict: - if '$ref' in node: - return {**definitions[node['$ref'].rsplit('/', 1)[1]], **node} - return node - - def branches(node: dict) -> dict: - mapping = node.get('discriminator', {}).get('mapping') - if mapping: - return {key: {'$ref': value} for key, value in mapping.items()} - choices = node.get('anyOf', node.get('oneOf', [])) - return {str(index): choice for index, choice in enumerate(choices)} - - def summary(node: dict, target: str) -> dict: - node = resolve(node) - details = {key: node[key] for key in ( - 'type', 'format', 'const', 'enum', 'default', 'description', 'minimum', 'maximum', - 'exclusiveMinimum', 'exclusiveMaximum', 'minLength', 'maxLength', - 'minItems', 'maxItems', 'pattern', - ) if key in node} - choices = branches(node) - if choices: - details.setdefault('type', 'union') - details['branches'] = {} - for key, choice in choices.items(): - branch = resolve(choice) - details['branches'][key] = { - 'path': f'{target}@{key}', - 'description': branch.get('description', branch.get('title', branch.get('type', key))), - **{name: branch[name] for name in ('type', 'required', 'const', 'enum') if name in branch}, - } - if target: - details['path'] = target - return details - - def minimal_value(node: dict, branch: str | None = None) -> JsonValue: - node = resolve(node) - if 'examples' in node: - return node['examples'][0] - if 'const' in node: - return node['const'] - if 'enum' in node: - return node['enum'][0] - choices = branches(node) - if choices: - return minimal_value(choices.get(branch, next(iter(choices.values())))) - kind = node.get('type') - if kind == 'object': - return {key: minimal_value(node['properties'][key], 'timeline' if key == 'document' else None) for key in node.get('required', [])} - if kind == 'array': - return [minimal_value(node['items']) for _ in range(node.get('minItems', 0))] - if kind == 'string': - if node.get('format') == 'uuid': - return str(project_id) - if node.get('pattern') == '^sha256:[0-9a-f]{64}$': - return 'sha256:' + '0' * 64 - if node.get('pattern') == '^[0-9a-f]{64}$': - return '0' * 64 - return 'x' * max(1, node.get('minLength', 0)) - if kind in {'integer', 'number'}: - return node.get('minimum', node.get('exclusiveMinimum', -1) + 1) - if kind == 'boolean': - return False - return None - - def field_paths(node: dict, prefix: str, depth: int = 0) -> list[str]: - node = resolve(node) - if depth > 6: - return [] - found = [] - children = [(f'{prefix}.{key}' if prefix else key, child) for key, child in node.get('properties', {}).items()] - if 'items' in node: - children.append((f'{prefix}.[]' if prefix else '[]', node['items'])) - children += [(f'{prefix}@{key}', child) for key, child in branches(node).items()] - for target, child in children: - found.append(target) - found += field_paths(child, target, depth + 1) - return found - - def invalid_path(level: str, node: dict, requested: str) -> ProjectError: - paths = field_paths(schema, '') - last = requested.replace('@', '.').rsplit('.', 1)[-1] - nearest = '' - for scope in ([value for value in paths if value.startswith(level)], paths) if level else (paths,): - same_name = sorted((value for value in scope if value.replace('@', '.').rsplit('.', 1)[-1] == last), - key=lambda value: (value.count('.') + value.count('@'), value)) - nearest = same_name[0] if same_name else next(iter(difflib.get_close_matches(requested, scope, n=1, cutoff=0.5)), '') - if nearest: - break - nearest = nearest or level - available = [*resolve(node).get('properties', {}), *(f'@{key}' for key in branches(resolve(node)))] - command = resolve(schema).get('properties', {}).get('type', {}).get('const') - target = nearest or (f'{level}.{available[0]}' if level and available else available[0] if available else '') - example = '-' - if command and target: - namespace, action = command.split('.', 1) - example = (f'command_schema {{"type":"{command}","path":"{target}"}} | ' - f'opendirector {kebab(namespace)} {kebab(action)} --help-field {target}') - return ProjectError(contract_text('help_field_invalid', requested=requested, nearest=nearest or '-', level=level or '$', - fields=', '.join(available) or '-', example=example), code='help_field_invalid') - - node = schema - remaining = path - level = '' - while remaining: - node = resolve(node) - if remaining.startswith('@'): - choices = branches(node) - selector = next((key for key in sorted(choices, key=len, reverse=True) - if remaining[1:] == key or remaining[1:].startswith((key + '.', key + '@'))), None) - child = choices.get(selector) if selector is not None else None - remaining = remaining[len(selector) + 1:] if selector is not None else '' - else: - boundary = min((remaining.find(mark) for mark in ('.', '@') if mark in remaining), default=len(remaining)) - field = remaining[:boundary] - child = node.get('items') if field == '[]' else node.get('properties', {}).get(field) - remaining = remaining[boundary:] - if child is None: - raise invalid_path(level, node, path) - level = path[:len(path) - len(remaining)] - node = child - if remaining.startswith('.'): - remaining = remaining[1:] - - node = resolve(node) - prefix = f'{path}.' if path else '' - result = {'path': path, **summary(node, path)} - if 'description' in node: - result['description'] = node['description'] - if 'properties' in node: - result['required'] = node.get('required', []) - result['fields'] = {key: summary(value, prefix + key) for key, value in node['properties'].items()} - if not path: - payload = resolve(node['properties']['payload']) - command = node['properties']['type']['const'] - fields = result['fields'] - fields.pop('type') - fields['payload']['required'] = payload.get('required', []) - fields['payload']['fields'] = { - key: summary(value, f'payload.{key}') for key, value in payload.get('properties', {}).items() - } - example = {'type': command, 'payload': minimal_value(payload)} - if command == 'canvas.createGeneration': - spec = example['payload']['spec'] - item = example['payload']['item'] - spec['purpose'] = 'generation' - item['kind'] = spec['kind'] - item['binding'] = {'role': 'generation', 'objectRef': {'id': spec['id']}} - if command == 'generation.submit': - example['payload']['originItemId'] = str(project_id) - model = COMMANDS[command] - parsed_payload = model.model_fields['payload'].annotation.model_validate(example['payload']) - sample = model.model_construct(type=command, payload=parsed_payload, projectId=project_id) - versions = sample.required_versions() - if versions: - owned = next((getattr(parsed_payload, field, None) for field in ('spec', 'reference', 'document') - if getattr(parsed_payload, field, None) is not None), None) - revision = getattr(parsed_payload, 'expectedSpecRevision', getattr(owned, 'revision', 1)) - example['expectedVersions'] = [ - {'objectType': kind, 'id': str(identity), 'revision': revision} - for kind, identity in dict.fromkeys(versions) - ] - if command == 'asset.delete': - example['expectedPreview'] = '0' * 64 - return { - 'command': command, - 'description': node['description'], - 'example': example, - 'fields': fields, - } - if 'items' in node: - result['items'] = summary(node['items'], prefix + '[]') - return result - - def tools() -> list[dict]: result = [tool_schema('read_project', 'Read project objects, model catalog and user selections. turnReferences carries the selected nodes and frozen assets in chat order, plus fields for pinned generation references. Pass referenceIds to look up known IDs from earlier turns of this conversation. Model configuration IDs come from models.', {'type': 'object', 'properties': {'referenceIds': {'type': 'array', 'minItems': 1, diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 53ee65271..f4b0f7a14 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -30,8 +30,9 @@ from pydantic import ValidationError import typer from typer._click.exceptions import UsageError +from typer.core import TyperCommand -from opendirector.agent.tools import COMMANDS, command_help +from opendirector.agent.command_help import COMMANDS, command_help from opendirector.domain.creation.assets import ( ASSET_DOWNLOAD_ENGLISH, ASSET_REVISION_HEADER, AssetDownloadFile, AssetDownloadReceipt, ) @@ -590,9 +591,20 @@ def __init__(self, project, url, session, operation_id, take_over=False): self.live = bool(self.gateway.get("OPENDIRECTOR_AGENT_SOCKET") or self.gateway.get("OPENDIRECTOR_AGENT_HOST")) self.opened = False self.owns_session = session is None - self.http = httpx.Client(base_url=url, trust_env=False, timeout=120, - headers={"X-OpenDirector-Request": "1", "X-OpenDirector-Session": self.session, - "Accept-Language": os.environ.get('OPENDIRECTOR_LANGUAGE', 'en-US')}) + self._url = url + self._http = None + + @property + def http(self): + if self._http is None: + self._http = httpx.Client(base_url=self._url, trust_env=False, timeout=120, + headers={"X-OpenDirector-Request": "1", "X-OpenDirector-Session": self.session, + "Accept-Language": os.environ.get('OPENDIRECTOR_LANGUAGE', 'en-US')}) + return self._http + + @http.setter + def http(self, value): + self._http = value @staticmethod def response_error(response): @@ -696,7 +708,7 @@ def execute(self, kind, payload, versions=(), preview=None, *, identity=None): if value.get("status") == "accepted" and value.get("jobIds"): value = {**value, "next": { "description": "Wait for every accepted job in one call. On timeout, run the same wait command again.", - "commands": [shlex.join(["opendirector", "--url", str(self.http.base_url).rstrip("/"), + "commands": [shlex.join(["opendirector", "--url", str(httpx.URL(self._url)).rstrip("/"), "--project", value["projectId"], "job", "wait", *value["jobIds"], "--timeout", "60"])], }} canvas_versions = {item["id"]: item["revision"] for item in value.get("changed", []) @@ -751,7 +763,8 @@ def close(): if client.opened and client.owns_session: client.request("DELETE", f"/api/creation/sessions/{client.session}") finally: - client.http.close() + if client._http is not None: + client._http.close() ctx.call_on_close(close) @@ -1473,18 +1486,29 @@ def read_file(path): return value +class LazyEpilogCommand(TyperCommand): + @property + def epilog(self): + if callable(self._epilog): + self._epilog = self._epilog() + return self._epilog + + @epilog.setter + def epilog(self, value): + self._epilog = value + + def register_command(kind, model): namespace, action = kind.split(".", 1) - payload_schema = model.model_json_schema() payload = model.model_fields["payload"].annotation - properties = payload.model_json_schema().get("properties", {}) parameters = [ inspect.Parameter("ctx", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=typer.Context), inspect.Parameter("file", inspect.Parameter.KEYWORD_ONLY, default=None, annotation=Annotated[Path | None, typer.Option(help="Command JSON file with payload and expectedVersions; - reads stdin.")]), ] - for name, definition in properties.items(): - description = definition.get("description", name) + for field_name, field in payload.model_fields.items(): + name = field.alias or field_name + description = field.description if field.description is not None else name flags = ["--" + kebab(name)] if kind == "video.trim" and name in {"startSeconds", "endSeconds"}: flags.append("--" + name.removesuffix("Seconds")) @@ -1508,27 +1532,29 @@ def register_command(kind, model): def execute(ctx, file=None, expected_version=None, help_field=None, turn_reference=None, **values): ctx.obj.command = ctx.command_path if help_field is not None: - emit(command_help(payload_schema, help_field, ctx.obj.project or UUID(int=0))) + emit(command_help(model.model_json_schema(), help_field, ctx.obj.project or UUID(int=0))) return body = read_file(file) if file else {"payload": {}} if body.get("type", kind) != kind: raise ValueError("Command file type does not match this subcommand.") arguments = dict(body.get("payload", {})) - for name, value in values.items(): - if value is not None: - definition = properties[name] - alternatives = definition.get("anyOf", definition.get("oneOf", [definition])) - accepts_string = any(option.get("type") == "string" for option in alternatives) - if accepts_string and (value != "null" or len(alternatives) == 1): - arguments[name] = value - else: - try: - arguments[name] = json.loads(value) - except json.JSONDecodeError as error: - hint = (" --spec needs a complete JSON object, not a configuration ID. Put the ID in payload.spec.id; " - "if --file already contains it, omit --spec.") if name == "spec" else "" - raise ValueError(f"--{kebab(name)}: invalid JSON at column {error.colno}.{hint} " - f"Inspect --help-field payload.{name}.") from None + if any(value is not None for value in values.values()): + properties = payload.model_json_schema().get("properties", {}) + for name, value in values.items(): + if value is not None: + definition = properties[name] + alternatives = definition.get("anyOf", definition.get("oneOf", [definition])) + accepts_string = any(option.get("type") == "string" for option in alternatives) + if accepts_string and (value != "null" or len(alternatives) == 1): + arguments[name] = value + else: + try: + arguments[name] = json.loads(value) + except json.JSONDecodeError as error: + hint = (" --spec needs a complete JSON object, not a configuration ID. Put the ID in payload.spec.id; " + "if --file already contains it, omit --spec.") if name == "spec" else "" + raise ValueError(f"--{kebab(name)}: invalid JSON at column {error.colno}.{hint} " + f"Inspect --help-field payload.{name}.") from None if kind == "generationSpec.update" and isinstance(arguments.get("spec"), dict): required = ("purpose", "modelConfigId", "prompt", "promptContent", "parameters", "currentResultId") missing = [f"payload.spec.{field}" for field in required if field not in arguments["spec"]] @@ -1568,13 +1594,17 @@ def execute(ctx, file=None, expected_version=None, help_field=None, turn_referen arguments.update(sourceItemId=reference["sourceItemId"], source=reference["asset"]) emit(ctx.obj.execute(kind, arguments, versions, body.get("expectedPreview"), identity=operation)) execute.__signature__ = inspect.Signature(parameters) - help = command_help(payload_schema, "", UUID(int=0)) if kind in COMMANDS else None + + def epilog(): + help = command_help(model.model_json_schema(), "", UUID(int=0)) + return ("Example command document for --file:\n" + json.dumps(help["example"], ensure_ascii=False, indent=2) + + "\nUse --help-field payload to inspect structured fields and branches.") + description = model.__doc__ if kind == "generation.submit": description += " Accepted receipts return job wait commands; use them to wait for completion." - group(kebab(namespace)).command(kebab(action), help=description, - epilog=("Example command document for --file:\n" + json.dumps(help["example"], ensure_ascii=False, indent=2) + - "\nUse --help-field payload to inspect structured fields and branches.") if help else None)(execute) + group(kebab(namespace)).command(kebab(action), cls=LazyEpilogCommand, help=description, + epilog=epilog if kind in COMMANDS else None)(execute) for command_type, command_model in COMMAND_MODELS.items(): diff --git a/tests/test_cli.py b/tests/test_cli.py index 17c53e624..e793ff2c2 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -895,6 +895,103 @@ def invoke(args, *, content=None, status=0): assert not_a_job.value.issue.code == "missing_object" +def test_cli_defers_command_schemas_and_http_client_until_used(help_color): + probe = """ +import json +import os +import sys +from uuid import uuid4 +import httpx +from pydantic import BaseModel +from typer.testing import CliRunner + +schemas = [] +original_schema = BaseModel.model_json_schema + +def record_schema(cls, *args, **kwargs): + schemas.append(cls.__name__) + return original_schema.__func__(cls, *args, **kwargs) + +BaseModel.model_json_schema = classmethod(record_schema) + +http_clients = 0 +original_http = httpx.Client + +def record_http(*args, **kwargs): + global http_clients + http_clients += 1 + return original_http(*args, **kwargs) + +httpx.Client = record_http + +from opendirector import cli + +after_import_schemas = list(schemas) +loaded_modules = [ + name for name in ("opendirector.agent.tools", "opendirector.application.creation_canvas") + if name in sys.modules +] + +os.environ["OPENDIRECTOR_AGENT_SOCKET"] = "/tmp/unused-agent.sock" +project_id = str(uuid4()) +spec_id = str(uuid4()) + +def fake_call(self, name, arguments, *, identity=None): + if name == "read_project": + return {"project": {"project": {"id": project_id, "name": "Lazy", "revision": 1}}} + return {"status": "applied", "projectId": project_id, "changed": []} + +cli.Client.call = fake_call +runner = CliRunner() + +summary = runner.invoke(cli.app, ["--project", project_id, "project", "show", "--summary"]) +assert summary.exit_code == 0, summary.output +after_summary_schemas = list(schemas) +live_http_clients = http_clients + +submitted = runner.invoke(cli.app, [ + "--project", project_id, "generation", "submit", + "--spec-id", spec_id, "--expected-spec-revision", "1", + "--expected-version", f"generation_spec:{spec_id}:1", +]) +assert submitted.exit_code == 0, submitted.output +after_submit_schemas = list(schemas) + +print(json.dumps({ + "afterImportSchemas": after_import_schemas, + "loadedModules": loaded_modules, + "afterSummarySchemas": after_summary_schemas, + "liveHttpClients": live_http_clients, + "afterSubmitSchemas": after_submit_schemas, +})) +""" + completed = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, check=True, timeout=20) + report = json.loads(completed.stdout) + assert report["afterImportSchemas"] == [] + assert report["loadedModules"] == [] + assert report["afterSummarySchemas"] == [] + assert report["liveHttpClients"] == 0 + assert report["afterSubmitSchemas"] == ["GenerationSubmit"] + + runner = CliRunner() + editor_help = runner.invoke(cli.app, ["editor", "save", "--help"], terminal_width=120) + assert editor_help.exit_code == 0, editor_help.output + rendered = plain_help(editor_help.output) + assert "Example command document for --file:" in rendered + assert '"type": "editor.save"' in rendered + assert '"expectedVersions"' in rendered + + branch_help = runner.invoke(cli.app, ["editor", "save", "--help-field", "payload.document@timeline"]) + assert branch_help.exit_code == 0, branch_help.output + branch = json.loads(branch_help.output) + assert branch["path"] == "payload.document@timeline" + assert "data" in branch["fields"] + + create_help = runner.invoke(cli.app, ["project", "create", "--help"], terminal_width=120) + assert create_help.exit_code == 0, create_help.output + assert "Example command document for --file:" not in plain_help(create_help.output) + + @pytest.mark.parametrize("live", [False, True], ids=["http", "agent"]) def test_receipt_show_works_in_http_and_agent_modes_and_reports_missing_receipt(tmp_path, monkeypatch, live): import asyncio